blob: 7591f069b455d2c38ddd8df2a13d553bf776ec07 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner09532fe2019-05-10 23:39:09 +02007#include "pycore_ceval.h"
Victor Stinner99fcc612019-04-29 13:04:07 +02008#include "pycore_context.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02009#include "pycore_import.h" /* _PyImport_FindBuiltin */
Victor Stinner331a6a52019-05-27 16:39:22 +020010#include "pycore_initconfig.h"
Victor Stinner353933e2018-11-23 13:08:26 +010011#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010012#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010013#include "pycore_pathconfig.h"
Victor Stinnerb45d2592019-06-20 00:05:23 +020014#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010015#include "pycore_pylifecycle.h"
16#include "pycore_pymem.h"
17#include "pycore_pystate.h"
Victor Stinnered488662019-05-20 00:14:57 +020018#include "pycore_traceback.h"
Nick Coghland6009512014-11-20 21:39:37 +100019#include "grammar.h"
20#include "node.h"
21#include "token.h"
22#include "parsetok.h"
23#include "errcode.h"
24#include "code.h"
25#include "symtable.h"
26#include "ast.h"
27#include "marshal.h"
28#include "osdefs.h"
29#include <locale.h>
30
31#ifdef HAVE_SIGNAL_H
32#include <signal.h>
33#endif
34
35#ifdef MS_WINDOWS
36#include "malloc.h" /* for alloca */
37#endif
38
39#ifdef HAVE_LANGINFO_H
40#include <langinfo.h>
41#endif
42
43#ifdef MS_WINDOWS
44#undef BYTE
45#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070046
47extern PyTypeObject PyWindowsConsoleIO_Type;
48#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100049#endif
50
51_Py_IDENTIFIER(flush);
52_Py_IDENTIFIER(name);
53_Py_IDENTIFIER(stdin);
54_Py_IDENTIFIER(stdout);
55_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060056_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100057
58#ifdef __cplusplus
59extern "C" {
60#endif
61
Nick Coghland6009512014-11-20 21:39:37 +100062extern grammar _PyParser_Grammar; /* From graminit.c */
63
Victor Stinnerb45d2592019-06-20 00:05:23 +020064/* Forward declarations */
Victor Stinner331a6a52019-05-27 16:39:22 +020065static PyStatus add_main_module(PyInterpreterState *interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +020066static PyStatus init_import_site(void);
67static PyStatus init_sys_streams(PyThreadState *tstate);
68static PyStatus init_signals(PyThreadState *tstate);
69static void call_py_exitfuncs(PyThreadState *tstate);
70static void wait_for_thread_shutdown(PyThreadState *tstate);
Victor Stinner8e91c242019-04-24 17:24:01 +020071static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100072
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080073int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010075static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076
Victor Stinner331a6a52019-05-27 16:39:22 +020077PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078_PyRuntime_Initialize(void)
79{
80 /* XXX We only initialize once in the process, which aligns with
81 the static initialization of the former globals now found in
82 _PyRuntime. However, _PyRuntime *should* be initialized with
83 every Py_Initialize() call, but doing so breaks the runtime.
84 This is because the runtime state is not properly finalized
85 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010086 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020087 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080088 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010089 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080090
91 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092}
93
94void
95_PyRuntime_Finalize(void)
96{
97 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010098 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060099}
100
101int
102_Py_IsFinalizing(void)
103{
104 return _PyRuntime.finalizing != NULL;
105}
106
Nick Coghland6009512014-11-20 21:39:37 +1000107/* Hack to force loading of object files */
108int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
109 PyOS_mystrnicmp; /* Python/pystrcmp.o */
110
111/* PyModule_GetWarningsModule is no longer necessary as of 2.6
112since _warnings is builtin. This API should not be used. */
113PyObject *
114PyModule_GetWarningsModule(void)
115{
116 return PyImport_ImportModule("warnings");
117}
118
Eric Snowc7ec9982017-05-23 23:00:52 -0700119
Eric Snow1abcf672017-05-23 21:46:51 -0700120/* APIs to access the initialization flags
121 *
122 * Can be called prior to Py_Initialize.
123 */
Nick Coghland6009512014-11-20 21:39:37 +1000124
Eric Snow1abcf672017-05-23 21:46:51 -0700125int
126_Py_IsCoreInitialized(void)
127{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600128 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700129}
Nick Coghland6009512014-11-20 21:39:37 +1000130
131int
132Py_IsInitialized(void)
133{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600134 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000135}
136
Nick Coghlan6ea41862017-06-11 13:16:15 +1000137
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000138/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
139 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000140 initializations fail, a fatal error is issued and the function does
141 not return. On return, the first thread and interpreter state have
142 been created.
143
144 Locking: you must hold the interpreter lock while calling this.
145 (If the lock has not yet been initialized, that's equivalent to
146 having the lock, but you cannot use multiple threads.)
147
148*/
149
Victor Stinner331a6a52019-05-27 16:39:22 +0200150static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200151init_importlib(PyThreadState *tstate, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000152{
153 PyObject *importlib;
154 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000155 PyObject *value;
Victor Stinnerb45d2592019-06-20 00:05:23 +0200156 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +0200157 int verbose = interp->config.verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000158
159 /* Import _importlib through its frozen version, _frozen_importlib. */
160 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200161 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000162 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200163 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000164 PySys_FormatStderr("import _frozen_importlib # frozen\n");
165 }
166 importlib = PyImport_AddModule("_frozen_importlib");
167 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200168 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000169 }
170 interp->importlib = importlib;
171 Py_INCREF(interp->importlib);
172
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300173 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
174 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200175 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300176 Py_INCREF(interp->import_func);
177
Victor Stinnercd6e6942015-09-18 09:11:57 +0200178 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800179 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000180 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200181 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000182 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200183 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200184 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000185 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600186 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200187 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000188 }
189
Victor Stinnercd6e6942015-09-18 09:11:57 +0200190 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000191 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
192 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200193 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200194 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000195 }
196 Py_DECREF(value);
197 Py_DECREF(impmod);
198
Victor Stinner331a6a52019-05-27 16:39:22 +0200199 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000200}
201
Victor Stinner331a6a52019-05-27 16:39:22 +0200202static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200203init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700204{
205 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200206 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700207 "_install_external_importers", "");
208 if (value == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200209 _PyErr_Print(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200210 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700211 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200212 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200213 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700214}
Nick Coghland6009512014-11-20 21:39:37 +1000215
Nick Coghlan6ea41862017-06-11 13:16:15 +1000216/* Helper functions to better handle the legacy C locale
217 *
218 * The legacy C locale assumes ASCII as the default text encoding, which
219 * causes problems not only for the CPython runtime, but also other
220 * components like GNU readline.
221 *
222 * Accordingly, when the CLI detects it, it attempts to coerce it to a
223 * more capable UTF-8 based alternative as follows:
224 *
225 * if (_Py_LegacyLocaleDetected()) {
226 * _Py_CoerceLegacyLocale();
227 * }
228 *
229 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
230 *
231 * Locale coercion also impacts the default error handler for the standard
232 * streams: while the usual default is "strict", the default for the legacy
233 * C locale and for any of the coercion target locales is "surrogateescape".
234 */
235
236int
Victor Stinner0f721472019-05-20 17:16:38 +0200237_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000238{
239#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200240 if (!warn) {
241 const char *locale_override = getenv("LC_ALL");
242 if (locale_override != NULL && *locale_override != '\0') {
243 /* Don't coerce C locale if the LC_ALL environment variable
244 is set */
245 return 0;
246 }
247 }
248
Nick Coghlan6ea41862017-06-11 13:16:15 +1000249 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000250 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
251 * the POSIX locale as a simple alias for the C locale, so
252 * we may also want to check for that explicitly.
253 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000254 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
255 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
256#else
257 /* Windows uses code pages instead of locales, so no locale is legacy */
258 return 0;
259#endif
260}
261
Nick Coghlaneb817952017-06-18 12:29:42 +1000262static const char *_C_LOCALE_WARNING =
263 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
264 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
265 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
266 "locales is recommended.\n";
267
Nick Coghlaneb817952017-06-18 12:29:42 +1000268static void
Victor Stinner43125222019-04-24 18:23:53 +0200269emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000270{
Victor Stinner331a6a52019-05-27 16:39:22 +0200271 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200272 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200273 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000274 }
275}
276
Nick Coghlan6ea41862017-06-11 13:16:15 +1000277typedef struct _CandidateLocale {
278 const char *locale_name; /* The locale to try as a coercion target */
279} _LocaleCoercionTarget;
280
281static _LocaleCoercionTarget _TARGET_LOCALES[] = {
282 {"C.UTF-8"},
283 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000284 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000285 {NULL}
286};
287
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200288
289int
290_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000291{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200292 const _LocaleCoercionTarget *target = NULL;
293 for (target = _TARGET_LOCALES; target->locale_name; target++) {
294 if (strcmp(ctype_loc, target->locale_name) == 0) {
295 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000296 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200297 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200298 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000299}
300
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200301
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100303static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000304 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
305 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
306
Victor Stinner0f721472019-05-20 17:16:38 +0200307static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200308_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000309{
310 const char *newloc = target->locale_name;
311
312 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100313 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000314
315 /* Set the relevant locale environment variable */
316 if (setenv("LC_CTYPE", newloc, 1)) {
317 fprintf(stderr,
318 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200319 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000320 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200321 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100322 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000323 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000324
325 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100326 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200327 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328}
329#endif
330
Victor Stinner0f721472019-05-20 17:16:38 +0200331int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200332_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000333{
Victor Stinner0f721472019-05-20 17:16:38 +0200334 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000335#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200336 char *oldloc = NULL;
337
338 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
339 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200340 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200341 }
342
Victor Stinner94540602017-12-16 04:54:22 +0100343 const char *locale_override = getenv("LC_ALL");
344 if (locale_override == NULL || *locale_override == '\0') {
345 /* LC_ALL is also not set (or is set to an empty string) */
346 const _LocaleCoercionTarget *target = NULL;
347 for (target = _TARGET_LOCALES; target->locale_name; target++) {
348 const char *new_locale = setlocale(LC_CTYPE,
349 target->locale_name);
350 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400351#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100352 /* Also ensure that nl_langinfo works in this locale */
353 char *codeset = nl_langinfo(CODESET);
354 if (!codeset || *codeset == '\0') {
355 /* CODESET is not set or empty, so skip coercion */
356 new_locale = NULL;
357 _Py_SetLocaleFromEnv(LC_CTYPE);
358 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000359 }
Victor Stinner94540602017-12-16 04:54:22 +0100360#endif
361 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200362 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200363 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000364 }
365 }
366 }
367 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200368
369 setlocale(LC_CTYPE, oldloc);
370
371done:
372 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000373#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200374 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000375}
376
xdegaye1588be62017-11-12 12:45:59 +0100377/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
378 * isolate the idiosyncrasies of different libc implementations. It reads the
379 * appropriate environment variable and uses its value to select the locale for
380 * 'category'. */
381char *
382_Py_SetLocaleFromEnv(int category)
383{
Victor Stinner353933e2018-11-23 13:08:26 +0100384 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100385#ifdef __ANDROID__
386 const char *locale;
387 const char **pvar;
388#ifdef PY_COERCE_C_LOCALE
389 const char *coerce_c_locale;
390#endif
391 const char *utf8_locale = "C.UTF-8";
392 const char *env_var_set[] = {
393 "LC_ALL",
394 "LC_CTYPE",
395 "LANG",
396 NULL,
397 };
398
399 /* Android setlocale(category, "") doesn't check the environment variables
400 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
401 * check the environment variables listed in env_var_set. */
402 for (pvar=env_var_set; *pvar; pvar++) {
403 locale = getenv(*pvar);
404 if (locale != NULL && *locale != '\0') {
405 if (strcmp(locale, utf8_locale) == 0 ||
406 strcmp(locale, "en_US.UTF-8") == 0) {
407 return setlocale(category, utf8_locale);
408 }
409 return setlocale(category, "C");
410 }
411 }
412
413 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
414 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
415 * Quote from POSIX section "8.2 Internationalization Variables":
416 * "4. If the LANG environment variable is not set or is set to the empty
417 * string, the implementation-defined default locale shall be used." */
418
419#ifdef PY_COERCE_C_LOCALE
420 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
421 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
422 /* Some other ported code may check the environment variables (e.g. in
423 * extension modules), so we make sure that they match the locale
424 * configuration */
425 if (setenv("LC_CTYPE", utf8_locale, 1)) {
426 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
427 "environment variable to %s\n", utf8_locale);
428 }
429 }
430#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100431 res = setlocale(category, utf8_locale);
432#else /* !defined(__ANDROID__) */
433 res = setlocale(category, "");
434#endif
435 _Py_ResetForceASCII();
436 return res;
xdegaye1588be62017-11-12 12:45:59 +0100437}
438
Nick Coghlan6ea41862017-06-11 13:16:15 +1000439
Eric Snow1abcf672017-05-23 21:46:51 -0700440/* Global initializations. Can be undone by Py_Finalize(). Don't
441 call this twice without an intervening Py_Finalize() call.
442
Victor Stinner331a6a52019-05-27 16:39:22 +0200443 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700444 must have a corresponding call to Py_Finalize.
445
446 Locking: you must hold the interpreter lock while calling these APIs.
447 (If the lock has not yet been initialized, that's equivalent to
448 having the lock, but you cannot use multiple threads.)
449
450*/
451
Victor Stinner331a6a52019-05-27 16:39:22 +0200452static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200453pyinit_core_reconfigure(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200454 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200455 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200456{
Victor Stinner331a6a52019-05-27 16:39:22 +0200457 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100458 PyThreadState *tstate = _PyThreadState_GET();
459 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200460 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100461 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200462 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100463
464 PyInterpreterState *interp = tstate->interp;
465 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200466 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100467 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100468
Victor Stinner331a6a52019-05-27 16:39:22 +0200469 _PyConfig_Write(config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200470
Victor Stinner331a6a52019-05-27 16:39:22 +0200471 status = _PyConfig_Copy(&interp->config, config);
472 if (_PyStatus_EXCEPTION(status)) {
473 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200474 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200475 config = &interp->config;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200476
Victor Stinner331a6a52019-05-27 16:39:22 +0200477 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200478 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200479 if (_PyStatus_EXCEPTION(status)) {
480 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200481 }
482 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200483 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200484}
485
486
Victor Stinner331a6a52019-05-27 16:39:22 +0200487static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200488pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200489 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000490{
Victor Stinner43125222019-04-24 18:23:53 +0200491 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200492 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200493 }
Victor Stinnerda273412017-12-15 01:46:02 +0100494
Victor Stinner331a6a52019-05-27 16:39:22 +0200495 _PyConfig_Write(config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600496
Eric Snow1abcf672017-05-23 21:46:51 -0700497 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
498 * threads behave a little more gracefully at interpreter shutdown.
499 * We clobber it here so the new interpreter can start with a clean
500 * slate.
501 *
502 * However, this may still lead to misbehaviour if there are daemon
503 * threads still hanging around from a previous Py_Initialize/Finalize
504 * pair :(
505 */
Victor Stinner43125222019-04-24 18:23:53 +0200506 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600507
Victor Stinner331a6a52019-05-27 16:39:22 +0200508 PyStatus status = _Py_HashRandomization_Init(config);
509 if (_PyStatus_EXCEPTION(status)) {
510 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800511 }
512
Victor Stinner331a6a52019-05-27 16:39:22 +0200513 status = _PyInterpreterState_Enable(runtime);
514 if (_PyStatus_EXCEPTION(status)) {
515 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800516 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200517 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100518}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800519
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100520
Victor Stinner331a6a52019-05-27 16:39:22 +0200521static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200522pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200523 const PyConfig *config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200524 PyThreadState **tstate_p)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100525{
526 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100527 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200528 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100529 }
530
Victor Stinner331a6a52019-05-27 16:39:22 +0200531 PyStatus status = _PyConfig_Copy(&interp->config, config);
532 if (_PyStatus_EXCEPTION(status)) {
533 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100534 }
Nick Coghland6009512014-11-20 21:39:37 +1000535
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200536 PyThreadState *tstate = PyThreadState_New(interp);
Victor Stinnerb45d2592019-06-20 00:05:23 +0200537 if (tstate == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200538 return _PyStatus_ERR("can't make first thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +0200539 }
Nick Coghland6009512014-11-20 21:39:37 +1000540 (void) PyThreadState_Swap(tstate);
541
Victor Stinner99fcc612019-04-29 13:04:07 +0200542 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
543 destroying the GIL might fail when it is being referenced from
544 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000545 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000546 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner09532fe2019-05-10 23:39:09 +0200547 _PyEval_FiniThreads(&runtime->ceval);
Victor Stinner2914bb32018-01-29 11:57:45 +0100548
Nick Coghland6009512014-11-20 21:39:37 +1000549 /* Auto-thread-state API */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100550 _PyGILState_Init(tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000551
Victor Stinner2914bb32018-01-29 11:57:45 +0100552 /* Create the GIL */
553 PyEval_InitThreads();
554
Victor Stinnerb45d2592019-06-20 00:05:23 +0200555 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +0200556 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100557}
Nick Coghland6009512014-11-20 21:39:37 +1000558
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100559
Victor Stinner331a6a52019-05-27 16:39:22 +0200560static PyStatus
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100561pycore_init_types(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100562{
Victor Stinner444b39b2019-11-20 01:18:11 +0100563 PyStatus status;
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100564 int is_main_interp = _Py_IsMainInterpreter(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100565
Victor Stinner01b1cc12019-11-20 02:27:56 +0100566 status = _PyGC_Init(tstate);
Victor Stinner444b39b2019-11-20 01:18:11 +0100567 if (_PyStatus_EXCEPTION(status)) {
568 return status;
569 }
570
Victor Stinnere7e699e2019-11-20 12:08:13 +0100571 if (is_main_interp) {
572 status = _PyTypes_Init();
573 if (_PyStatus_EXCEPTION(status)) {
574 return status;
575 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100576
Victor Stinnere7e699e2019-11-20 12:08:13 +0100577 if (!_PyLong_Init()) {
578 return _PyStatus_ERR("can't init longs");
579 }
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100580 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100581
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100582 if (is_main_interp) {
Victor Stinnere7e699e2019-11-20 12:08:13 +0100583 status = _PyUnicode_Init();
584 if (_PyStatus_EXCEPTION(status)) {
585 return status;
586 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100587 }
588
Victor Stinner331a6a52019-05-27 16:39:22 +0200589 status = _PyExc_Init();
590 if (_PyStatus_EXCEPTION(status)) {
591 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100592 }
593
Victor Stinnere7e699e2019-11-20 12:08:13 +0100594 if (is_main_interp) {
595 if (!_PyFloat_Init()) {
596 return _PyStatus_ERR("can't init float");
597 }
Nick Coghland6009512014-11-20 21:39:37 +1000598
Victor Stinnere7e699e2019-11-20 12:08:13 +0100599 if (_PyStructSequence_Init() < 0) {
600 return _PyStatus_ERR("can't initialize structseq");
601 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100602 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200603
Victor Stinner331a6a52019-05-27 16:39:22 +0200604 status = _PyErr_Init();
605 if (_PyStatus_EXCEPTION(status)) {
606 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200607 }
608
Victor Stinnere7e699e2019-11-20 12:08:13 +0100609 if (is_main_interp) {
610 if (!_PyContext_Init()) {
611 return _PyStatus_ERR("can't init context");
612 }
Victor Stinneref5aa9a2019-11-20 00:38:03 +0100613 }
614
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100616}
617
618
Victor Stinner331a6a52019-05-27 16:39:22 +0200619static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200620pycore_init_builtins(PyThreadState *tstate)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100621{
Victor Stinnerb45d2592019-06-20 00:05:23 +0200622 PyInterpreterState *interp = tstate->interp;
623
624 PyObject *bimod = _PyBuiltin_Init(tstate);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100625 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200626 return _PyStatus_ERR("can't initialize builtins modules");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100627 }
628 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
629
630 interp->builtins = PyModule_GetDict(bimod);
631 if (interp->builtins == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200632 return _PyStatus_ERR("can't initialize builtins dict");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100633 }
634 Py_INCREF(interp->builtins);
635
Victor Stinner331a6a52019-05-27 16:39:22 +0200636 PyStatus status = _PyBuiltins_AddExceptions(bimod);
637 if (_PyStatus_EXCEPTION(status)) {
638 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100639 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200640 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100641}
642
643
Victor Stinner331a6a52019-05-27 16:39:22 +0200644static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +0200645pycore_init_import_warnings(PyThreadState *tstate, PyObject *sysmod)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100646{
Victor Stinnerb45d2592019-06-20 00:05:23 +0200647 const PyConfig *config = &tstate->interp->config;
648
649 PyStatus status = _PyImport_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200650 if (_PyStatus_EXCEPTION(status)) {
651 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800652 }
Nick Coghland6009512014-11-20 21:39:37 +1000653
Victor Stinnerb45d2592019-06-20 00:05:23 +0200654 status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200655 if (_PyStatus_EXCEPTION(status)) {
656 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800657 }
Nick Coghland6009512014-11-20 21:39:37 +1000658
659 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100660 if (_PyWarnings_Init() == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200661 return _PyStatus_ERR("can't initialize warnings");
Victor Stinner1f151112017-11-23 10:43:14 +0100662 }
Nick Coghland6009512014-11-20 21:39:37 +1000663
Victor Stinnerb45d2592019-06-20 00:05:23 +0200664 if (config->_install_importlib) {
Victor Stinner12f2f172019-09-26 15:51:50 +0200665 status = _PyConfig_WritePathConfig(config);
Victor Stinner331a6a52019-05-27 16:39:22 +0200666 if (_PyStatus_EXCEPTION(status)) {
667 return status;
Victor Stinnerb1147e42018-07-21 02:06:16 +0200668 }
669 }
670
Eric Snow1abcf672017-05-23 21:46:51 -0700671 /* This call sets up builtin and frozen import support */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200672 if (config->_install_importlib) {
673 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200674 if (_PyStatus_EXCEPTION(status)) {
675 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800676 }
Eric Snow1abcf672017-05-23 21:46:51 -0700677 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200678 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100679}
680
681
Victor Stinner331a6a52019-05-27 16:39:22 +0200682static PyStatus
683pyinit_config(_PyRuntimeState *runtime,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200684 PyThreadState **tstate_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200685 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100686{
Victor Stinner331a6a52019-05-27 16:39:22 +0200687 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100688
Victor Stinner331a6a52019-05-27 16:39:22 +0200689 PyStatus status = pycore_init_runtime(runtime, config);
690 if (_PyStatus_EXCEPTION(status)) {
691 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100692 }
693
Victor Stinnerb45d2592019-06-20 00:05:23 +0200694 PyThreadState *tstate;
695 status = pycore_create_interpreter(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200696 if (_PyStatus_EXCEPTION(status)) {
697 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100698 }
Victor Stinnerb45d2592019-06-20 00:05:23 +0200699 config = &tstate->interp->config;
700 *tstate_p = tstate;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100701
Victor Stinnerb93f31f2019-11-20 18:39:12 +0100702 status = pycore_init_types(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200703 if (_PyStatus_EXCEPTION(status)) {
704 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100705 }
706
707 PyObject *sysmod;
Victor Stinner01b1cc12019-11-20 02:27:56 +0100708 status = _PySys_Create(tstate, &sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200709 if (_PyStatus_EXCEPTION(status)) {
710 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711 }
712
Victor Stinnerb45d2592019-06-20 00:05:23 +0200713 status = pycore_init_builtins(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200714 if (_PyStatus_EXCEPTION(status)) {
715 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100716 }
717
Victor Stinnerb45d2592019-06-20 00:05:23 +0200718 status = pycore_init_import_warnings(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200719 if (_PyStatus_EXCEPTION(status)) {
720 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100721 }
Eric Snow1abcf672017-05-23 21:46:51 -0700722
723 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200724 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200725 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700726}
727
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100728
Victor Stinner331a6a52019-05-27 16:39:22 +0200729PyStatus
730_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100731{
Victor Stinner331a6a52019-05-27 16:39:22 +0200732 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100733
Victor Stinner6d1c4672019-05-20 11:02:00 +0200734 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200735 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200736 }
737
Victor Stinner331a6a52019-05-27 16:39:22 +0200738 status = _PyRuntime_Initialize();
739 if (_PyStatus_EXCEPTION(status)) {
740 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100741 }
Victor Stinner43125222019-04-24 18:23:53 +0200742 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100743
Victor Stinnerd3b90412019-09-17 23:59:51 +0200744 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100745 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200746 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100747 }
748
Victor Stinnerd3b90412019-09-17 23:59:51 +0200749 /* Note: preinitialized remains 1 on error, it is only set to 0
750 at exit on success. */
751 runtime->preinitializing = 1;
752
Victor Stinner331a6a52019-05-27 16:39:22 +0200753 PyPreConfig config;
Victor Stinner441b10c2019-09-28 04:28:35 +0200754
755 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
756 if (_PyStatus_EXCEPTION(status)) {
757 return status;
758 }
Victor Stinnerf72346c2019-03-25 17:54:58 +0100759
Victor Stinner331a6a52019-05-27 16:39:22 +0200760 status = _PyPreConfig_Read(&config, args);
761 if (_PyStatus_EXCEPTION(status)) {
762 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100763 }
764
Victor Stinner331a6a52019-05-27 16:39:22 +0200765 status = _PyPreConfig_Write(&config);
766 if (_PyStatus_EXCEPTION(status)) {
767 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100768 }
769
Victor Stinnerd3b90412019-09-17 23:59:51 +0200770 runtime->preinitializing = 0;
771 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200772 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100773}
774
Victor Stinner70005ac2019-05-02 15:25:34 -0400775
Victor Stinner331a6a52019-05-27 16:39:22 +0200776PyStatus
777Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100778{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100779 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400780 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100781}
782
783
Victor Stinner331a6a52019-05-27 16:39:22 +0200784PyStatus
785Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100786{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100787 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400788 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100789}
790
791
Victor Stinner331a6a52019-05-27 16:39:22 +0200792PyStatus
793Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100794{
Victor Stinner70005ac2019-05-02 15:25:34 -0400795 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100796}
797
798
Victor Stinner331a6a52019-05-27 16:39:22 +0200799PyStatus
800_Py_PreInitializeFromConfig(const PyConfig *config,
801 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100802{
Victor Stinner331a6a52019-05-27 16:39:22 +0200803 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200804
Victor Stinner331a6a52019-05-27 16:39:22 +0200805 PyStatus status = _PyRuntime_Initialize();
806 if (_PyStatus_EXCEPTION(status)) {
807 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200808 }
809 _PyRuntimeState *runtime = &_PyRuntime;
810
Victor Stinnerd3b90412019-09-17 23:59:51 +0200811 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200812 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200813 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400814 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200815
Victor Stinner331a6a52019-05-27 16:39:22 +0200816 PyPreConfig preconfig;
Victor Stinner441b10c2019-09-28 04:28:35 +0200817
Victor Stinner3c30a762019-10-01 10:56:37 +0200818 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200819
Victor Stinner331a6a52019-05-27 16:39:22 +0200820 if (!config->parse_argv) {
821 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200822 }
823 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200824 _PyArgv config_args = {
825 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200826 .argc = config->argv.length,
827 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200828 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200829 }
830 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200831 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200832 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100833}
834
835
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100836/* Begin interpreter initialization
837 *
838 * On return, the first thread and interpreter state have been created,
839 * but the compiler, signal handling, multithreading and
840 * multiple interpreter support, and codec infrastructure are not yet
841 * available.
842 *
843 * The import system will support builtin and frozen modules only.
844 * The only supported io is writing to sys.stderr
845 *
846 * If any operation invoked by this function fails, a fatal error is
847 * issued and the function does not return.
848 *
849 * Any code invoked from this function should *not* assume it has access
850 * to the Python C API (unless the API is explicitly listed as being
851 * safe to call without calling Py_Initialize first)
852 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200853static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200854pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200855 const PyConfig *src_config,
Victor Stinnerb45d2592019-06-20 00:05:23 +0200856 PyThreadState **tstate_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200857{
Victor Stinner331a6a52019-05-27 16:39:22 +0200858 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200859
Victor Stinner331a6a52019-05-27 16:39:22 +0200860 status = _Py_PreInitializeFromConfig(src_config, NULL);
861 if (_PyStatus_EXCEPTION(status)) {
862 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200863 }
864
Victor Stinner331a6a52019-05-27 16:39:22 +0200865 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +0200866 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200867
Victor Stinner331a6a52019-05-27 16:39:22 +0200868 status = _PyConfig_Copy(&config, src_config);
869 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200870 goto done;
871 }
872
Victor Stinner331a6a52019-05-27 16:39:22 +0200873 status = PyConfig_Read(&config);
874 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200875 goto done;
876 }
877
878 if (!runtime->core_initialized) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200879 status = pyinit_config(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200880 }
881 else {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200882 status = pyinit_core_reconfigure(runtime, tstate_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200883 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200884 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200885 goto done;
886 }
887
888done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200889 PyConfig_Clear(&config);
890 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200891}
892
Victor Stinner5ac27a52019-03-27 13:40:14 +0100893
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200894/* Py_Initialize() has already been called: update the main interpreter
895 configuration. Example of bpo-34008: Py_Main() called after
896 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200897static PyStatus
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100898_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200899{
Victor Stinner331a6a52019-05-27 16:39:22 +0200900 PyConfig *config = &interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100901
Victor Stinner331a6a52019-05-27 16:39:22 +0200902 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100903 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200904 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100905 }
906
907 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
908 Py_DECREF(argv);
909 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200910 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200911 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200912 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200913}
914
Eric Snowc7ec9982017-05-23 23:00:52 -0700915/* Update interpreter state based on supplied configuration settings
916 *
917 * After calling this function, most of the restrictions on the interpreter
918 * are lifted. The only remaining incomplete settings are those related
919 * to the main module (sys.argv[0], __main__ metadata)
920 *
921 * Calling this when the interpreter is not initializing, is already
922 * initialized or without a valid current thread state is a fatal error.
923 * Other errors should be reported as normal Python exceptions with a
924 * non-zero return code.
925 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200926static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +0100927pyinit_main(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700928{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100929 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner43125222019-04-24 18:23:53 +0200930 if (!runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200931 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700932 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700933
Victor Stinner1dc6e392018-07-25 02:49:17 +0200934 /* Configure the main interpreter */
Victor Stinnerb45d2592019-06-20 00:05:23 +0200935 PyInterpreterState *interp = tstate->interp;
Victor Stinner331a6a52019-05-27 16:39:22 +0200936 PyConfig *config = &interp->config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700937
Victor Stinner43125222019-04-24 18:23:53 +0200938 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100939 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200940 }
941
Victor Stinner331a6a52019-05-27 16:39:22 +0200942 if (!config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700943 /* Special mode for freeze_importlib: run with no import system
944 *
945 * This means anything which needs support from extension modules
946 * or pure Python code in the standard library won't work.
947 */
Victor Stinner43125222019-04-24 18:23:53 +0200948 runtime->initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200949 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700950 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100951
Victor Stinner33c377e2017-12-05 15:12:41 +0100952 if (_PyTime_Init() < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200953 return _PyStatus_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100954 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200955
Victor Stinner01b1cc12019-11-20 02:27:56 +0100956 if (_PySys_InitMain(tstate) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200957 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100958 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800959
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200960 PyStatus status = init_importlib_external(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200961 if (_PyStatus_EXCEPTION(status)) {
962 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800963 }
Nick Coghland6009512014-11-20 21:39:37 +1000964
965 /* initialize the faulthandler module */
Victor Stinner331a6a52019-05-27 16:39:22 +0200966 status = _PyFaulthandler_Init(config->faulthandler);
967 if (_PyStatus_EXCEPTION(status)) {
968 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800969 }
Nick Coghland6009512014-11-20 21:39:37 +1000970
Victor Stinnerb45d2592019-06-20 00:05:23 +0200971 status = _PyUnicode_InitEncodings(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200972 if (_PyStatus_EXCEPTION(status)) {
973 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800974 }
Nick Coghland6009512014-11-20 21:39:37 +1000975
Victor Stinner331a6a52019-05-27 16:39:22 +0200976 if (config->install_signal_handlers) {
Victor Stinnerb45d2592019-06-20 00:05:23 +0200977 status = init_signals(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200978 if (_PyStatus_EXCEPTION(status)) {
979 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800980 }
981 }
Nick Coghland6009512014-11-20 21:39:37 +1000982
Victor Stinner331a6a52019-05-27 16:39:22 +0200983 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
984 return _PyStatus_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200985 }
Nick Coghland6009512014-11-20 21:39:37 +1000986
Victor Stinner331a6a52019-05-27 16:39:22 +0200987 status = add_main_module(interp);
988 if (_PyStatus_EXCEPTION(status)) {
989 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800990 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800991
Victor Stinnerb45d2592019-06-20 00:05:23 +0200992 status = init_sys_streams(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200993 if (_PyStatus_EXCEPTION(status)) {
994 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800995 }
Nick Coghland6009512014-11-20 21:39:37 +1000996
997 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100998 PyObject *warnoptions = PySys_GetObject("warnoptions");
999 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +01001000 {
Nick Coghland6009512014-11-20 21:39:37 +10001001 PyObject *warnings_module = PyImport_ImportModule("warnings");
1002 if (warnings_module == NULL) {
1003 fprintf(stderr, "'import warnings' failed; traceback:\n");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001004 _PyErr_Print(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001005 }
1006 Py_XDECREF(warnings_module);
1007 }
1008
Victor Stinner43125222019-04-24 18:23:53 +02001009 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -07001010
Victor Stinner331a6a52019-05-27 16:39:22 +02001011 if (config->site_import) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02001012 status = init_import_site();
Victor Stinner331a6a52019-05-27 16:39:22 +02001013 if (_PyStatus_EXCEPTION(status)) {
1014 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001015 }
1016 }
Victor Stinnercf215042018-08-29 22:56:06 +02001017
1018#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +02001019 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +02001020#endif
1021
Victor Stinner331a6a52019-05-27 16:39:22 +02001022 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001023}
1024
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001025
Victor Stinner331a6a52019-05-27 16:39:22 +02001026PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001027_Py_InitializeMain(void)
1028{
Victor Stinner331a6a52019-05-27 16:39:22 +02001029 PyStatus status = _PyRuntime_Initialize();
1030 if (_PyStatus_EXCEPTION(status)) {
1031 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001032 }
1033 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinnerb45d2592019-06-20 00:05:23 +02001034 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001035 return pyinit_main(tstate);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001036}
1037
1038
Victor Stinner331a6a52019-05-27 16:39:22 +02001039PyStatus
1040Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001041{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001042 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001043 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001044 }
1045
Victor Stinner331a6a52019-05-27 16:39:22 +02001046 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001047
Victor Stinner331a6a52019-05-27 16:39:22 +02001048 status = _PyRuntime_Initialize();
1049 if (_PyStatus_EXCEPTION(status)) {
1050 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001051 }
1052 _PyRuntimeState *runtime = &_PyRuntime;
1053
Victor Stinnerb45d2592019-06-20 00:05:23 +02001054 PyThreadState *tstate = NULL;
1055 status = pyinit_core(runtime, config, &tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001056 if (_PyStatus_EXCEPTION(status)) {
1057 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001058 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001059 config = &tstate->interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001060
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001061 if (config->_init_main) {
Victor Stinner01b1cc12019-11-20 02:27:56 +01001062 status = pyinit_main(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001063 if (_PyStatus_EXCEPTION(status)) {
1064 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001065 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001066 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001067
Victor Stinner331a6a52019-05-27 16:39:22 +02001068 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001069}
1070
1071
Eric Snow1abcf672017-05-23 21:46:51 -07001072void
Nick Coghland6009512014-11-20 21:39:37 +10001073Py_InitializeEx(int install_sigs)
1074{
Victor Stinner331a6a52019-05-27 16:39:22 +02001075 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001076
Victor Stinner331a6a52019-05-27 16:39:22 +02001077 status = _PyRuntime_Initialize();
1078 if (_PyStatus_EXCEPTION(status)) {
1079 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001080 }
1081 _PyRuntimeState *runtime = &_PyRuntime;
1082
1083 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001084 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1085 return;
1086 }
1087
Victor Stinner331a6a52019-05-27 16:39:22 +02001088 PyConfig config;
Victor Stinner8462a492019-10-01 12:06:16 +02001089 _PyConfig_InitCompatConfig(&config);
Victor Stinner441b10c2019-09-28 04:28:35 +02001090
Victor Stinner1dc6e392018-07-25 02:49:17 +02001091 config.install_signal_handlers = install_sigs;
1092
Victor Stinner331a6a52019-05-27 16:39:22 +02001093 status = Py_InitializeFromConfig(&config);
1094 if (_PyStatus_EXCEPTION(status)) {
1095 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001096 }
Nick Coghland6009512014-11-20 21:39:37 +10001097}
1098
1099void
1100Py_Initialize(void)
1101{
1102 Py_InitializeEx(1);
1103}
1104
1105
1106#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001107extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001108#endif
1109
1110/* Flush stdout and stderr */
1111
1112static int
1113file_is_closed(PyObject *fobj)
1114{
1115 int r;
1116 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1117 if (tmp == NULL) {
1118 PyErr_Clear();
1119 return 0;
1120 }
1121 r = PyObject_IsTrue(tmp);
1122 Py_DECREF(tmp);
1123 if (r < 0)
1124 PyErr_Clear();
1125 return r > 0;
1126}
1127
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001128static int
Nick Coghland6009512014-11-20 21:39:37 +10001129flush_std_files(void)
1130{
1131 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1132 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1133 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001134 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001135
1136 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001137 tmp = _PyObject_CallMethodIdNoArgs(fout, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001138 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001139 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001140 status = -1;
1141 }
Nick Coghland6009512014-11-20 21:39:37 +10001142 else
1143 Py_DECREF(tmp);
1144 }
1145
1146 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001147 tmp = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001148 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001149 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001150 status = -1;
1151 }
Nick Coghland6009512014-11-20 21:39:37 +10001152 else
1153 Py_DECREF(tmp);
1154 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001155
1156 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001157}
1158
1159/* Undo the effect of Py_Initialize().
1160
1161 Beware: if multiple interpreter and/or thread states exist, these
1162 are not wiped out; only the current thread and interpreter state
1163 are deleted. But since everything else is deleted, those other
1164 interpreter and thread states should no longer be used.
1165
1166 (XXX We should do better, e.g. wipe out all interpreters and
1167 threads.)
1168
1169 Locking: as above.
1170
1171*/
1172
Victor Stinner7eee5be2019-11-20 10:38:34 +01001173
1174static void
1175finalize_interp_types(PyThreadState *tstate, int is_main_interp)
1176{
1177 if (is_main_interp) {
1178 /* Sundry finalizers */
Victor Stinner7eee5be2019-11-20 10:38:34 +01001179 _PyFrame_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001180 _PyTuple_Fini();
1181 _PyList_Fini();
1182 _PySet_Fini();
1183 _PyBytes_Fini();
1184 _PyLong_Fini();
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001185 }
1186
1187 if (is_main_interp) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001188 _PyFloat_Fini();
1189 _PyDict_Fini();
1190 _PySlice_Fini();
1191 }
1192
1193 _PyWarnings_Fini(tstate->interp);
1194
1195 if (is_main_interp) {
1196 _Py_HashRandomization_Fini();
1197 _PyArg_Fini();
1198 _PyAsyncGen_Fini();
1199 _PyContext_Fini();
1200
1201 /* Cleanup Unicode implementation */
1202 _PyUnicode_Fini();
1203 _Py_ClearFileSystemEncoding();
1204 }
1205}
1206
1207
1208static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001209finalize_interp_clear(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001210{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001211 int is_main_interp = _Py_IsMainInterpreter(tstate);
1212
Victor Stinner7eee5be2019-11-20 10:38:34 +01001213 /* Clear interpreter state and all thread states */
1214 PyInterpreterState_Clear(tstate->interp);
1215
1216 finalize_interp_types(tstate, is_main_interp);
1217
1218 if (is_main_interp) {
1219 /* XXX Still allocated:
1220 - various static ad-hoc pointers to interned strings
1221 - int and float free list blocks
1222 - whatever various modules and libraries allocate
1223 */
1224
1225 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1226
1227 _PyExc_Fini();
Victor Stinner7eee5be2019-11-20 10:38:34 +01001228 }
Victor Stinner72474072019-11-20 12:25:50 +01001229
1230 _PyGC_Fini(tstate);
Victor Stinner7eee5be2019-11-20 10:38:34 +01001231}
1232
1233
1234static void
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001235finalize_interp_delete(PyThreadState *tstate)
Victor Stinner7eee5be2019-11-20 10:38:34 +01001236{
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001237 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinner7eee5be2019-11-20 10:38:34 +01001238 /* Cleanup auto-thread-state */
1239 _PyGILState_Fini(tstate);
1240 }
1241
Victor Stinner7eee5be2019-11-20 10:38:34 +01001242 PyInterpreterState_Delete(tstate->interp);
1243}
1244
1245
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001246int
1247Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001248{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001249 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001250
Victor Stinner8e91c242019-04-24 17:24:01 +02001251 _PyRuntimeState *runtime = &_PyRuntime;
1252 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001253 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001254 }
Nick Coghland6009512014-11-20 21:39:37 +10001255
Victor Stinnere225beb2019-06-03 18:14:24 +02001256 /* Get current thread state and interpreter pointer */
1257 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1258 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001259
Victor Stinnerb45d2592019-06-20 00:05:23 +02001260 // Wrap up existing "threading"-module-created, non-daemon threads.
1261 wait_for_thread_shutdown(tstate);
1262
1263 // Make any remaining pending calls.
1264 _Py_FinishPendingCalls(runtime);
1265
Nick Coghland6009512014-11-20 21:39:37 +10001266 /* The interpreter is still entirely intact at this point, and the
1267 * exit funcs may be relying on that. In particular, if some thread
1268 * or exit func is still waiting to do an import, the import machinery
1269 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001270 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001271 * Note that Threading.py uses an exit func to do a join on all the
1272 * threads created thru it, so this also protects pending imports in
1273 * the threads created via Threading.
1274 */
Nick Coghland6009512014-11-20 21:39:37 +10001275
Victor Stinnerb45d2592019-06-20 00:05:23 +02001276 call_py_exitfuncs(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001277
Victor Stinnerda273412017-12-15 01:46:02 +01001278 /* Copy the core config, PyInterpreterState_Delete() free
1279 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001280#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001281 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001282#endif
1283#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001284 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001285#endif
1286#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001287 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001288#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001289
Nick Coghland6009512014-11-20 21:39:37 +10001290 /* Remaining threads (e.g. daemon threads) will automatically exit
1291 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001292 runtime->finalizing = tstate;
1293 runtime->initialized = 0;
1294 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001295
Victor Stinnere0deff32015-03-24 13:46:18 +01001296 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001297 if (flush_std_files() < 0) {
1298 status = -1;
1299 }
Nick Coghland6009512014-11-20 21:39:37 +10001300
1301 /* Disable signal handling */
1302 PyOS_FiniInterrupts();
1303
1304 /* Collect garbage. This may call finalizers; it's nice to call these
1305 * before all modules are destroyed.
1306 * XXX If a __del__ or weakref callback is triggered here, and tries to
1307 * XXX import a module, bad things can happen, because Python no
1308 * XXX longer believes it's initialized.
1309 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1310 * XXX is easy to provoke that way. I've also seen, e.g.,
1311 * XXX Exception exceptions.ImportError: 'No module named sha'
1312 * XXX in <function callback at 0x008F5718> ignored
1313 * XXX but I'm unclear on exactly how that one happens. In any case,
1314 * XXX I haven't seen a real-life report of either of these.
1315 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001316 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001317#ifdef COUNT_ALLOCS
1318 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1319 each collection might release some types from the type
1320 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001321 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001322 /* nothing */;
1323#endif
Eric Snowdae02762017-09-14 00:35:58 -07001324
Steve Dowerb82e17e2019-05-23 08:45:22 -07001325 /* Clear all loghooks */
1326 /* We want minimal exposure of this function, so define the extern
1327 * here. The linker should discover the correct function without
1328 * exporting a symbol. */
1329 extern void _PySys_ClearAuditHooks(void);
1330 _PySys_ClearAuditHooks();
1331
Nick Coghland6009512014-11-20 21:39:37 +10001332 /* Destroy all modules */
Victor Stinner987a0dc2019-06-19 10:36:10 +02001333 _PyImport_Cleanup(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001334
Inada Naoki91234a12019-06-03 21:30:58 +09001335 /* Print debug stats if any */
1336 _PyEval_Fini();
1337
Victor Stinnere0deff32015-03-24 13:46:18 +01001338 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001339 if (flush_std_files() < 0) {
1340 status = -1;
1341 }
Nick Coghland6009512014-11-20 21:39:37 +10001342
1343 /* Collect final garbage. This disposes of cycles created by
1344 * class definitions, for example.
1345 * XXX This is disabled because it caused too many problems. If
1346 * XXX a __del__ or weakref callback triggers here, Python code has
1347 * XXX a hard time running, because even the sys module has been
1348 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1349 * XXX One symptom is a sequence of information-free messages
1350 * XXX coming from threads (if a __del__ or callback is invoked,
1351 * XXX other threads can execute too, and any exception they encounter
1352 * XXX triggers a comedy of errors as subsystem after subsystem
1353 * XXX fails to find what it *expects* to find in sys to help report
1354 * XXX the exception and consequent unexpected failures). I've also
1355 * XXX seen segfaults then, after adding print statements to the
1356 * XXX Python code getting called.
1357 */
1358#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001359 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001360#endif
1361
1362 /* Disable tracemalloc after all Python objects have been destroyed,
1363 so it is possible to use tracemalloc in objects destructor. */
1364 _PyTraceMalloc_Fini();
1365
1366 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1367 _PyImport_Fini();
1368
1369 /* Cleanup typeobject.c's internal caches. */
1370 _PyType_Fini();
1371
1372 /* unload faulthandler module */
1373 _PyFaulthandler_Fini();
1374
1375 /* Debugging stuff */
1376#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001377 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001378#endif
1379 /* dump hash stats */
1380 _PyHash_Fini();
1381
Eric Snowdae02762017-09-14 00:35:58 -07001382#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001383 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001384 _PyDebug_PrintTotalRefs();
1385 }
Eric Snowdae02762017-09-14 00:35:58 -07001386#endif
Nick Coghland6009512014-11-20 21:39:37 +10001387
1388#ifdef Py_TRACE_REFS
1389 /* Display all objects still alive -- this can invoke arbitrary
1390 * __repr__ overrides, so requires a mostly-intact interpreter.
1391 * Alas, a lot of stuff may still be alive now that will be cleaned
1392 * up later.
1393 */
Victor Stinnerda273412017-12-15 01:46:02 +01001394 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001395 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001396 }
Nick Coghland6009512014-11-20 21:39:37 +10001397#endif /* Py_TRACE_REFS */
1398
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001399 finalize_interp_clear(tstate);
1400 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001401
1402#ifdef Py_TRACE_REFS
1403 /* Display addresses (& refcnts) of all objects still alive.
1404 * An address can be used to find the repr of the object, printed
1405 * above by _Py_PrintReferences.
1406 */
Victor Stinnerda273412017-12-15 01:46:02 +01001407 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001408 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001409 }
Nick Coghland6009512014-11-20 21:39:37 +10001410#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001411#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001412 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001413 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001414 }
Nick Coghland6009512014-11-20 21:39:37 +10001415#endif
1416
Victor Stinner8e91c242019-04-24 17:24:01 +02001417 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001418
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001419 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001420 return status;
1421}
1422
1423void
1424Py_Finalize(void)
1425{
1426 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001427}
1428
1429/* Create and initialize a new interpreter and thread, and return the
1430 new thread. This requires that Py_Initialize() has been called
1431 first.
1432
1433 Unsuccessful initialization yields a NULL pointer. Note that *no*
1434 exception information is available even in this case -- the
1435 exception information is held in the thread, and there is no
1436 thread.
1437
1438 Locking: as above.
1439
1440*/
1441
Victor Stinner331a6a52019-05-27 16:39:22 +02001442static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001443new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001444{
Victor Stinner331a6a52019-05-27 16:39:22 +02001445 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001446
Victor Stinner331a6a52019-05-27 16:39:22 +02001447 status = _PyRuntime_Initialize();
1448 if (_PyStatus_EXCEPTION(status)) {
1449 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001450 }
1451 _PyRuntimeState *runtime = &_PyRuntime;
1452
1453 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001454 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001455 }
Nick Coghland6009512014-11-20 21:39:37 +10001456
Victor Stinner8a1be612016-03-14 22:07:55 +01001457 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1458 interpreters: disable PyGILState_Check(). */
1459 _PyGILState_check_enabled = 0;
1460
Victor Stinner43125222019-04-24 18:23:53 +02001461 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001462 if (interp == NULL) {
1463 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001464 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001465 }
Nick Coghland6009512014-11-20 21:39:37 +10001466
Victor Stinner43125222019-04-24 18:23:53 +02001467 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001468 if (tstate == NULL) {
1469 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001470 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001471 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001472 }
1473
Victor Stinner43125222019-04-24 18:23:53 +02001474 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001475
Eric Snow1abcf672017-05-23 21:46:51 -07001476 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001477 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001478 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001479 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001480 } else {
1481 /* No current thread state, copy from the main interpreter */
1482 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001483 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001484 }
1485
Victor Stinner331a6a52019-05-27 16:39:22 +02001486 status = _PyConfig_Copy(&interp->config, config);
1487 if (_PyStatus_EXCEPTION(status)) {
1488 return status;
Victor Stinnerda273412017-12-15 01:46:02 +01001489 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001490 config = &interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001491
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001492 status = pycore_init_types(tstate);
Victor Stinneref9d9b62019-05-22 11:28:22 +02001493
Nick Coghland6009512014-11-20 21:39:37 +10001494 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001495 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001496 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001497 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001498 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001499 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001500
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001501 PyObject *sysmod = _PyImport_FindBuiltin(tstate, "sys");
Eric Snowd393c1b2017-09-14 12:18:12 -06001502 if (sysmod != NULL) {
1503 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001504 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001505 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001506 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001507 Py_INCREF(interp->sysdict);
1508 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner01b1cc12019-11-20 02:27:56 +01001509 if (_PySys_InitMain(tstate) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001510 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerab672812019-01-23 15:04:40 +01001511 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001512 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001513 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001514 goto handle_error;
1515 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001516
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001517 PyObject *bimod = _PyImport_FindBuiltin(tstate, "builtins");
Nick Coghland6009512014-11-20 21:39:37 +10001518 if (bimod != NULL) {
1519 interp->builtins = PyModule_GetDict(bimod);
1520 if (interp->builtins == NULL)
1521 goto handle_error;
1522 Py_INCREF(interp->builtins);
1523 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001524 else if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001525 goto handle_error;
1526 }
Nick Coghland6009512014-11-20 21:39:37 +10001527
Nick Coghland6009512014-11-20 21:39:37 +10001528 if (bimod != NULL && sysmod != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001529 status = _PyBuiltins_AddExceptions(bimod);
1530 if (_PyStatus_EXCEPTION(status)) {
1531 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001532 }
Nick Coghland6009512014-11-20 21:39:37 +10001533
Victor Stinner331a6a52019-05-27 16:39:22 +02001534 status = _PySys_SetPreliminaryStderr(interp->sysdict);
1535 if (_PyStatus_EXCEPTION(status)) {
1536 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001537 }
Nick Coghland6009512014-11-20 21:39:37 +10001538
Victor Stinnerb45d2592019-06-20 00:05:23 +02001539 status = _PyImportHooks_Init(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001540 if (_PyStatus_EXCEPTION(status)) {
1541 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001542 }
Nick Coghland6009512014-11-20 21:39:37 +10001543
Victor Stinnerb45d2592019-06-20 00:05:23 +02001544 status = init_importlib(tstate, sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +02001545 if (_PyStatus_EXCEPTION(status)) {
1546 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001547 }
Nick Coghland6009512014-11-20 21:39:37 +10001548
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001549 status = init_importlib_external(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001550 if (_PyStatus_EXCEPTION(status)) {
1551 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001552 }
Nick Coghland6009512014-11-20 21:39:37 +10001553
Victor Stinnerb45d2592019-06-20 00:05:23 +02001554 status = _PyUnicode_InitEncodings(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001555 if (_PyStatus_EXCEPTION(status)) {
1556 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001557 }
1558
Victor Stinnerb45d2592019-06-20 00:05:23 +02001559 status = init_sys_streams(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001560 if (_PyStatus_EXCEPTION(status)) {
1561 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001562 }
1563
Victor Stinner331a6a52019-05-27 16:39:22 +02001564 status = add_main_module(interp);
1565 if (_PyStatus_EXCEPTION(status)) {
1566 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001567 }
1568
Victor Stinner331a6a52019-05-27 16:39:22 +02001569 if (config->site_import) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02001570 status = init_import_site();
Victor Stinner331a6a52019-05-27 16:39:22 +02001571 if (_PyStatus_EXCEPTION(status)) {
1572 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001573 }
1574 }
Nick Coghland6009512014-11-20 21:39:37 +10001575 }
1576
Victor Stinnerb45d2592019-06-20 00:05:23 +02001577 if (_PyErr_Occurred(tstate)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001578 goto handle_error;
1579 }
Nick Coghland6009512014-11-20 21:39:37 +10001580
Victor Stinnera7368ac2017-11-15 18:11:45 -08001581 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001582 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001583
Nick Coghland6009512014-11-20 21:39:37 +10001584handle_error:
1585 /* Oops, it didn't work. Undo it all. */
1586
1587 PyErr_PrintEx(0);
1588 PyThreadState_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001589 PyThreadState_Delete(tstate);
1590 PyInterpreterState_Delete(interp);
Victor Stinner9da74302019-11-20 11:17:17 +01001591 PyThreadState_Swap(save_tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001592
Victor Stinnera7368ac2017-11-15 18:11:45 -08001593 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001594 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001595}
1596
1597PyThreadState *
1598Py_NewInterpreter(void)
1599{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001600 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001601 PyStatus status = new_interpreter(&tstate);
1602 if (_PyStatus_EXCEPTION(status)) {
1603 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001604 }
1605 return tstate;
1606
Nick Coghland6009512014-11-20 21:39:37 +10001607}
1608
1609/* Delete an interpreter and its last thread. This requires that the
1610 given thread state is current, that the thread has no remaining
1611 frames, and that it is its interpreter's only remaining thread.
1612 It is a fatal error to violate these constraints.
1613
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001614 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001615 everything, regardless.)
1616
1617 Locking: as above.
1618
1619*/
1620
1621void
1622Py_EndInterpreter(PyThreadState *tstate)
1623{
1624 PyInterpreterState *interp = tstate->interp;
1625
Victor Stinnerb45d2592019-06-20 00:05:23 +02001626 if (tstate != _PyThreadState_GET()) {
Nick Coghland6009512014-11-20 21:39:37 +10001627 Py_FatalError("Py_EndInterpreter: thread is not current");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001628 }
1629 if (tstate->frame != NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001630 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001631 }
Eric Snow5be45a62019-03-08 22:47:07 -07001632 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001633
Eric Snow842a2f02019-03-15 15:47:51 -06001634 // Wrap up existing "threading"-module-created, non-daemon threads.
Victor Stinnerb45d2592019-06-20 00:05:23 +02001635 wait_for_thread_shutdown(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001636
Victor Stinnerb45d2592019-06-20 00:05:23 +02001637 call_py_exitfuncs(tstate);
Marcel Plch776407f2017-12-20 11:17:58 +01001638
Victor Stinnerb45d2592019-06-20 00:05:23 +02001639 if (tstate != interp->tstate_head || tstate->next != NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001640 Py_FatalError("Py_EndInterpreter: not the last thread");
Victor Stinnerb45d2592019-06-20 00:05:23 +02001641 }
Nick Coghland6009512014-11-20 21:39:37 +10001642
Victor Stinner987a0dc2019-06-19 10:36:10 +02001643 _PyImport_Cleanup(tstate);
Victor Stinnerb93f31f2019-11-20 18:39:12 +01001644 finalize_interp_clear(tstate);
1645 finalize_interp_delete(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001646}
1647
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001648/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001649
Victor Stinner331a6a52019-05-27 16:39:22 +02001650static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001651add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001652{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001653 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001654 m = PyImport_AddModule("__main__");
1655 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001656 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001657
Nick Coghland6009512014-11-20 21:39:37 +10001658 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001659 ann_dict = PyDict_New();
1660 if ((ann_dict == NULL) ||
1661 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001662 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001663 }
1664 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001665
Nick Coghland6009512014-11-20 21:39:37 +10001666 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1667 PyObject *bimod = PyImport_ImportModule("builtins");
1668 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001669 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001670 }
1671 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001672 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001673 }
1674 Py_DECREF(bimod);
1675 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001676
Nick Coghland6009512014-11-20 21:39:37 +10001677 /* Main is a little special - imp.is_builtin("__main__") will return
1678 * False, but BuiltinImporter is still the most appropriate initial
1679 * setting for its __loader__ attribute. A more suitable value will
1680 * be set if __main__ gets further initialized later in the startup
1681 * process.
1682 */
1683 loader = PyDict_GetItemString(d, "__loader__");
1684 if (loader == NULL || loader == Py_None) {
1685 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1686 "BuiltinImporter");
1687 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001688 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001689 }
1690 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001691 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001692 }
1693 Py_DECREF(loader);
1694 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001695 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001696}
1697
Nick Coghland6009512014-11-20 21:39:37 +10001698/* Import the site module (not into __main__ though) */
1699
Victor Stinner331a6a52019-05-27 16:39:22 +02001700static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001701init_import_site(void)
Nick Coghland6009512014-11-20 21:39:37 +10001702{
1703 PyObject *m;
1704 m = PyImport_ImportModule("site");
1705 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001706 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001707 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001708 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001709 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001710}
1711
Victor Stinner874dbe82015-09-04 17:29:57 +02001712/* Check if a file descriptor is valid or not.
1713 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1714static int
1715is_valid_fd(int fd)
1716{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001717/* dup() is faster than fstat(): fstat() can require input/output operations,
1718 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1719 startup. Problem: dup() doesn't check if the file descriptor is valid on
1720 some platforms.
1721
1722 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1723 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1724 EBADF. FreeBSD has similar issue (bpo-32849).
1725
1726 Only use dup() on platforms where dup() is enough to detect invalid FD in
1727 corner cases: on Linux and Windows (bpo-32849). */
1728#if defined(__linux__) || defined(MS_WINDOWS)
1729 if (fd < 0) {
1730 return 0;
1731 }
1732 int fd2;
1733
1734 _Py_BEGIN_SUPPRESS_IPH
1735 fd2 = dup(fd);
1736 if (fd2 >= 0) {
1737 close(fd2);
1738 }
1739 _Py_END_SUPPRESS_IPH
1740
1741 return (fd2 >= 0);
1742#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001743 struct stat st;
1744 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001745#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001746}
1747
1748/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001749static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001750create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001751 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001752 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001753{
1754 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1755 const char* mode;
1756 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001757 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001758 int buffering, isatty;
1759 _Py_IDENTIFIER(open);
1760 _Py_IDENTIFIER(isatty);
1761 _Py_IDENTIFIER(TextIOWrapper);
1762 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001763 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001764
Victor Stinner874dbe82015-09-04 17:29:57 +02001765 if (!is_valid_fd(fd))
1766 Py_RETURN_NONE;
1767
Nick Coghland6009512014-11-20 21:39:37 +10001768 /* stdin is always opened in buffered mode, first because it shouldn't
1769 make a difference in common use cases, second because TextIOWrapper
1770 depends on the presence of a read1() method which only exists on
1771 buffered streams.
1772 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001773 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001774 buffering = 0;
1775 else
1776 buffering = -1;
1777 if (write_mode)
1778 mode = "wb";
1779 else
1780 mode = "rb";
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001781 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOO",
Nick Coghland6009512014-11-20 21:39:37 +10001782 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001783 Py_None, Py_None, /* encoding, errors */
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03001784 Py_None, Py_False); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001785 if (buf == NULL)
1786 goto error;
1787
1788 if (buffering) {
1789 _Py_IDENTIFIER(raw);
1790 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1791 if (raw == NULL)
1792 goto error;
1793 }
1794 else {
1795 raw = buf;
1796 Py_INCREF(raw);
1797 }
1798
Steve Dower39294992016-08-30 21:22:36 -07001799#ifdef MS_WINDOWS
1800 /* Windows console IO is always UTF-8 encoded */
1801 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001802 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001803#endif
1804
Nick Coghland6009512014-11-20 21:39:37 +10001805 text = PyUnicode_FromString(name);
1806 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1807 goto error;
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02001808 res = _PyObject_CallMethodIdNoArgs(raw, &PyId_isatty);
Nick Coghland6009512014-11-20 21:39:37 +10001809 if (res == NULL)
1810 goto error;
1811 isatty = PyObject_IsTrue(res);
1812 Py_DECREF(res);
1813 if (isatty == -1)
1814 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001815 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001816 write_through = Py_True;
1817 else
1818 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001819 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001820 line_buffering = Py_True;
1821 else
1822 line_buffering = Py_False;
1823
1824 Py_CLEAR(raw);
1825 Py_CLEAR(text);
1826
1827#ifdef MS_WINDOWS
1828 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1829 newlines to "\n".
1830 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1831 newline = NULL;
1832#else
1833 /* sys.stdin: split lines at "\n".
1834 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1835 newline = "\n";
1836#endif
1837
Victor Stinner709d23d2019-05-02 14:56:30 -04001838 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1839 if (encoding_str == NULL) {
1840 Py_CLEAR(buf);
1841 goto error;
1842 }
1843
1844 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1845 if (errors_str == NULL) {
1846 Py_CLEAR(buf);
1847 Py_CLEAR(encoding_str);
1848 goto error;
1849 }
1850
1851 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1852 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001853 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001854 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001855 Py_CLEAR(encoding_str);
1856 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001857 if (stream == NULL)
1858 goto error;
1859
1860 if (write_mode)
1861 mode = "w";
1862 else
1863 mode = "r";
1864 text = PyUnicode_FromString(mode);
1865 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1866 goto error;
1867 Py_CLEAR(text);
1868 return stream;
1869
1870error:
1871 Py_XDECREF(buf);
1872 Py_XDECREF(stream);
1873 Py_XDECREF(text);
1874 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001875
Victor Stinner874dbe82015-09-04 17:29:57 +02001876 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1877 /* Issue #24891: the file descriptor was closed after the first
1878 is_valid_fd() check was called. Ignore the OSError and set the
1879 stream to None. */
1880 PyErr_Clear();
1881 Py_RETURN_NONE;
1882 }
1883 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001884}
1885
1886/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001887static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02001888init_sys_streams(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10001889{
1890 PyObject *iomod = NULL, *wrapper;
1891 PyObject *bimod = NULL;
1892 PyObject *m;
1893 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001894 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001895 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001896 PyStatus res = _PyStatus_OK();
Victor Stinnerb45d2592019-06-20 00:05:23 +02001897 const PyConfig *config = &tstate->interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001898
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001899 /* Check that stdin is not a directory
1900 Using shell redirection, you can redirect stdin to a directory,
1901 crashing the Python interpreter. Catch this common mistake here
1902 and output a useful error message. Note that under MS Windows,
1903 the shell already prevents that. */
1904#ifndef MS_WINDOWS
1905 struct _Py_stat_struct sb;
1906 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1907 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001908 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001909 }
1910#endif
1911
Nick Coghland6009512014-11-20 21:39:37 +10001912 /* Hack to avoid a nasty recursion issue when Python is invoked
1913 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1914 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1915 goto error;
1916 }
1917 Py_DECREF(m);
1918
1919 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1920 goto error;
1921 }
1922 Py_DECREF(m);
1923
1924 if (!(bimod = PyImport_ImportModule("builtins"))) {
1925 goto error;
1926 }
1927
1928 if (!(iomod = PyImport_ImportModule("io"))) {
1929 goto error;
1930 }
1931 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1932 goto error;
1933 }
1934
1935 /* Set builtins.open */
1936 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1937 Py_DECREF(wrapper);
1938 goto error;
1939 }
1940 Py_DECREF(wrapper);
1941
Nick Coghland6009512014-11-20 21:39:37 +10001942 /* Set sys.stdin */
1943 fd = fileno(stdin);
1944 /* Under some conditions stdin, stdout and stderr may not be connected
1945 * and fileno() may point to an invalid file descriptor. For example
1946 * GUI apps don't have valid standard streams by default.
1947 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001948 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001949 config->stdio_encoding,
1950 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001951 if (std == NULL)
1952 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001953 PySys_SetObject("__stdin__", std);
1954 _PySys_SetObjectId(&PyId_stdin, std);
1955 Py_DECREF(std);
1956
1957 /* Set sys.stdout */
1958 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001959 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001960 config->stdio_encoding,
1961 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001962 if (std == NULL)
1963 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001964 PySys_SetObject("__stdout__", std);
1965 _PySys_SetObjectId(&PyId_stdout, std);
1966 Py_DECREF(std);
1967
1968#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1969 /* Set sys.stderr, replaces the preliminary stderr */
1970 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001971 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001972 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001973 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001974 if (std == NULL)
1975 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001976
1977 /* Same as hack above, pre-import stderr's codec to avoid recursion
1978 when import.c tries to write to stderr in verbose mode. */
1979 encoding_attr = PyObject_GetAttrString(std, "encoding");
1980 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001981 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001982 if (std_encoding != NULL) {
1983 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1984 Py_XDECREF(codec_info);
1985 }
1986 Py_DECREF(encoding_attr);
1987 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001988 _PyErr_Clear(tstate); /* Not a fatal error if codec isn't available */
Nick Coghland6009512014-11-20 21:39:37 +10001989
1990 if (PySys_SetObject("__stderr__", std) < 0) {
1991 Py_DECREF(std);
1992 goto error;
1993 }
1994 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1995 Py_DECREF(std);
1996 goto error;
1997 }
1998 Py_DECREF(std);
1999#endif
2000
Victor Stinnera7368ac2017-11-15 18:11:45 -08002001 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10002002
Victor Stinnera7368ac2017-11-15 18:11:45 -08002003error:
Victor Stinner331a6a52019-05-27 16:39:22 +02002004 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08002005
2006done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02002007 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01002008
Nick Coghland6009512014-11-20 21:39:37 +10002009 Py_XDECREF(bimod);
2010 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08002011 return res;
Nick Coghland6009512014-11-20 21:39:37 +10002012}
2013
2014
Victor Stinner10dc4842015-03-24 12:01:30 +01002015static void
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002016_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
2017 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01002018{
Victor Stinner10dc4842015-03-24 12:01:30 +01002019 fputc('\n', stderr);
2020 fflush(stderr);
2021
2022 /* display the current Python stack */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002023 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01002024}
Victor Stinner791da1c2016-03-14 16:53:12 +01002025
2026/* Print the current exception (if an exception is set) with its traceback,
2027 or display the current Python stack.
2028
2029 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2030 called on catastrophic cases.
2031
2032 Return 1 if the traceback was displayed, 0 otherwise. */
2033
2034static int
2035_Py_FatalError_PrintExc(int fd)
2036{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002037 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner791da1c2016-03-14 16:53:12 +01002038 PyObject *ferr, *res;
2039 PyObject *exception, *v, *tb;
2040 int has_tb;
2041
Victor Stinnerb45d2592019-06-20 00:05:23 +02002042 _PyErr_Fetch(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002043 if (exception == NULL) {
2044 /* No current exception */
2045 return 0;
2046 }
2047
2048 ferr = _PySys_GetObjectId(&PyId_stderr);
2049 if (ferr == NULL || ferr == Py_None) {
2050 /* sys.stderr is not set yet or set to None,
2051 no need to try to display the exception */
2052 return 0;
2053 }
2054
Victor Stinnerb45d2592019-06-20 00:05:23 +02002055 _PyErr_NormalizeException(tstate, &exception, &v, &tb);
Victor Stinner791da1c2016-03-14 16:53:12 +01002056 if (tb == NULL) {
2057 tb = Py_None;
2058 Py_INCREF(tb);
2059 }
2060 PyException_SetTraceback(v, tb);
2061 if (exception == NULL) {
2062 /* PyErr_NormalizeException() failed */
2063 return 0;
2064 }
2065
2066 has_tb = (tb != Py_None);
2067 PyErr_Display(exception, v, tb);
2068 Py_XDECREF(exception);
2069 Py_XDECREF(v);
2070 Py_XDECREF(tb);
2071
2072 /* sys.stderr may be buffered: call sys.stderr.flush() */
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002073 res = _PyObject_CallMethodIdNoArgs(ferr, &PyId_flush);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002074 if (res == NULL) {
2075 _PyErr_Clear(tstate);
2076 }
2077 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002078 Py_DECREF(res);
Victor Stinnerb45d2592019-06-20 00:05:23 +02002079 }
Victor Stinner791da1c2016-03-14 16:53:12 +01002080
2081 return has_tb;
2082}
2083
Nick Coghland6009512014-11-20 21:39:37 +10002084/* Print fatal error message and abort */
2085
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002086#ifdef MS_WINDOWS
2087static void
2088fatal_output_debug(const char *msg)
2089{
2090 /* buffer of 256 bytes allocated on the stack */
2091 WCHAR buffer[256 / sizeof(WCHAR)];
2092 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2093 size_t msglen;
2094
2095 OutputDebugStringW(L"Fatal Python error: ");
2096
2097 msglen = strlen(msg);
2098 while (msglen) {
2099 size_t i;
2100
2101 if (buflen > msglen) {
2102 buflen = msglen;
2103 }
2104
2105 /* Convert the message to wchar_t. This uses a simple one-to-one
2106 conversion, assuming that the this error message actually uses
2107 ASCII only. If this ceases to be true, we will have to convert. */
2108 for (i=0; i < buflen; ++i) {
2109 buffer[i] = msg[i];
2110 }
2111 buffer[i] = L'\0';
2112 OutputDebugStringW(buffer);
2113
2114 msg += buflen;
2115 msglen -= buflen;
2116 }
2117 OutputDebugStringW(L"\n");
2118}
2119#endif
2120
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002121
2122static void
2123fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2124{
2125 fprintf(stream, "Python runtime state: ");
2126 if (runtime->finalizing) {
2127 fprintf(stream, "finalizing (tstate=%p)", runtime->finalizing);
2128 }
2129 else if (runtime->initialized) {
2130 fprintf(stream, "initialized");
2131 }
2132 else if (runtime->core_initialized) {
2133 fprintf(stream, "core initialized");
2134 }
2135 else if (runtime->preinitialized) {
2136 fprintf(stream, "preinitialized");
2137 }
2138 else if (runtime->preinitializing) {
2139 fprintf(stream, "preinitializing");
2140 }
2141 else {
2142 fprintf(stream, "unknown");
2143 }
2144 fprintf(stream, "\n");
2145 fflush(stream);
2146}
2147
2148
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002149static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002150fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002151{
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002152 FILE *stream = stderr;
2153 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002154 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002155
2156 if (reentrant) {
2157 /* Py_FatalError() caused a second fatal error.
2158 Example: flush_std_files() raises a recursion error. */
2159 goto exit;
2160 }
2161 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002162
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002163 fprintf(stream, "Fatal Python error: ");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002164 if (prefix) {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002165 fputs(prefix, stream);
2166 fputs(": ", stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002167 }
2168 if (msg) {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002169 fputs(msg, stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002170 }
2171 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002172 fprintf(stream, "<message not set>");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002173 }
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002174 fputs("\n", stream);
2175 fflush(stream); /* it helps in Windows debug build */
2176
2177 _PyRuntimeState *runtime = &_PyRuntime;
2178 fatal_error_dump_runtime(stream, runtime);
2179
2180 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2181 PyInterpreterState *interp = NULL;
2182 if (tstate != NULL) {
2183 interp = tstate->interp;
2184 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002185
Victor Stinner3a228ab2018-11-01 00:26:41 +01002186 /* Check if the current thread has a Python thread state
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002187 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002188
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002189 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2190 has no Python thread state.
2191
2192 tss_tstate != tstate if the current Python thread does not hold the GIL.
2193 */
2194 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2195 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002196 if (has_tstate_and_gil) {
2197 /* If an exception is set, print the exception with its traceback */
2198 if (!_Py_FatalError_PrintExc(fd)) {
2199 /* No exception is set, or an exception is set without traceback */
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002200 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002201 }
2202 }
2203 else {
Victor Stinner1ce16fb2019-09-18 01:35:33 +02002204 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002205 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002206
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002207 /* The main purpose of faulthandler is to display the traceback.
2208 This function already did its best to display a traceback.
2209 Disable faulthandler to prevent writing a second traceback
2210 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002211 _PyFaulthandler_Fini();
2212
Victor Stinner791da1c2016-03-14 16:53:12 +01002213 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002214 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002215 /* Flush sys.stdout and sys.stderr */
2216 flush_std_files();
2217 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002218
Nick Coghland6009512014-11-20 21:39:37 +10002219#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002220 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002221#endif /* MS_WINDOWS */
2222
2223exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002224 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002225#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002226 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002227#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002228 abort();
2229 }
2230 else {
2231 exit(status);
2232 }
2233}
2234
Victor Stinner19760862017-12-20 01:41:59 +01002235void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002236Py_FatalError(const char *msg)
2237{
2238 fatal_error(NULL, msg, -1);
2239}
2240
Victor Stinner19760862017-12-20 01:41:59 +01002241void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002242Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002243{
Victor Stinner331a6a52019-05-27 16:39:22 +02002244 if (_PyStatus_IS_EXIT(status)) {
2245 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002246 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002247 else if (_PyStatus_IS_ERROR(status)) {
2248 fatal_error(status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002249 }
2250 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002251 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002252 }
Nick Coghland6009512014-11-20 21:39:37 +10002253}
2254
2255/* Clean up and exit */
2256
Victor Stinnerd7292b52016-06-17 12:29:00 +02002257# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002258
Nick Coghland6009512014-11-20 21:39:37 +10002259/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002260void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002261{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002262 PyInterpreterState *is = _PyInterpreterState_GET_UNSAFE();
Marcel Plch776407f2017-12-20 11:17:58 +01002263
Antoine Pitroufc5db952017-12-13 02:29:07 +01002264 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002265 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2266
2267 is->pyexitfunc = func;
2268 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002269}
2270
2271static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002272call_py_exitfuncs(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002273{
Victor Stinnerb45d2592019-06-20 00:05:23 +02002274 PyInterpreterState *interp = tstate->interp;
2275 if (interp->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002276 return;
2277
Victor Stinnerb45d2592019-06-20 00:05:23 +02002278 (*interp->pyexitfunc)(interp->pyexitmodule);
2279 _PyErr_Clear(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10002280}
2281
2282/* Wait until threading._shutdown completes, provided
2283 the threading module was imported in the first place.
2284 The shutdown routine will wait until all non-daemon
2285 "threading" threads have completed. */
2286static void
Victor Stinnerb45d2592019-06-20 00:05:23 +02002287wait_for_thread_shutdown(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002288{
Nick Coghland6009512014-11-20 21:39:37 +10002289 _Py_IDENTIFIER(_shutdown);
2290 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002291 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002292 if (threading == NULL) {
Victor Stinnerb45d2592019-06-20 00:05:23 +02002293 if (_PyErr_Occurred(tstate)) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002294 PyErr_WriteUnraisable(NULL);
2295 }
2296 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002297 return;
2298 }
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002299 result = _PyObject_CallMethodIdNoArgs(threading, &PyId__shutdown);
Nick Coghland6009512014-11-20 21:39:37 +10002300 if (result == NULL) {
2301 PyErr_WriteUnraisable(threading);
2302 }
2303 else {
2304 Py_DECREF(result);
2305 }
2306 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002307}
2308
2309#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002310int Py_AtExit(void (*func)(void))
2311{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002312 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002313 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002314 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002315 return 0;
2316}
2317
2318static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002319call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002320{
Victor Stinner8e91c242019-04-24 17:24:01 +02002321 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002322 /* pop last function from the list */
2323 runtime->nexitfuncs--;
2324 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2325 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2326
2327 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002328 }
Nick Coghland6009512014-11-20 21:39:37 +10002329
2330 fflush(stdout);
2331 fflush(stderr);
2332}
2333
Victor Stinnercfc88312018-08-01 16:41:25 +02002334void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002335Py_Exit(int sts)
2336{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002337 if (Py_FinalizeEx() < 0) {
2338 sts = 120;
2339 }
Nick Coghland6009512014-11-20 21:39:37 +10002340
2341 exit(sts);
2342}
2343
Victor Stinner331a6a52019-05-27 16:39:22 +02002344static PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +02002345init_signals(PyThreadState *tstate)
Nick Coghland6009512014-11-20 21:39:37 +10002346{
2347#ifdef SIGPIPE
2348 PyOS_setsig(SIGPIPE, SIG_IGN);
2349#endif
2350#ifdef SIGXFZ
2351 PyOS_setsig(SIGXFZ, SIG_IGN);
2352#endif
2353#ifdef SIGXFSZ
2354 PyOS_setsig(SIGXFSZ, SIG_IGN);
2355#endif
2356 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerb45d2592019-06-20 00:05:23 +02002357 if (_PyErr_Occurred(tstate)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002358 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002359 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002360 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002361}
2362
2363
2364/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2365 *
2366 * All of the code in this function must only use async-signal-safe functions,
2367 * listed at `man 7 signal` or
2368 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2369 */
2370void
2371_Py_RestoreSignals(void)
2372{
2373#ifdef SIGPIPE
2374 PyOS_setsig(SIGPIPE, SIG_DFL);
2375#endif
2376#ifdef SIGXFZ
2377 PyOS_setsig(SIGXFZ, SIG_DFL);
2378#endif
2379#ifdef SIGXFSZ
2380 PyOS_setsig(SIGXFSZ, SIG_DFL);
2381#endif
2382}
2383
2384
2385/*
2386 * The file descriptor fd is considered ``interactive'' if either
2387 * a) isatty(fd) is TRUE, or
2388 * b) the -i flag was given, and the filename associated with
2389 * the descriptor is NULL or "<stdin>" or "???".
2390 */
2391int
2392Py_FdIsInteractive(FILE *fp, const char *filename)
2393{
2394 if (isatty((int)fileno(fp)))
2395 return 1;
2396 if (!Py_InteractiveFlag)
2397 return 0;
2398 return (filename == NULL) ||
2399 (strcmp(filename, "<stdin>") == 0) ||
2400 (strcmp(filename, "???") == 0);
2401}
2402
2403
Nick Coghland6009512014-11-20 21:39:37 +10002404/* Wrappers around sigaction() or signal(). */
2405
2406PyOS_sighandler_t
2407PyOS_getsig(int sig)
2408{
2409#ifdef HAVE_SIGACTION
2410 struct sigaction context;
2411 if (sigaction(sig, NULL, &context) == -1)
2412 return SIG_ERR;
2413 return context.sa_handler;
2414#else
2415 PyOS_sighandler_t handler;
2416/* Special signal handling for the secure CRT in Visual Studio 2005 */
2417#if defined(_MSC_VER) && _MSC_VER >= 1400
2418 switch (sig) {
2419 /* Only these signals are valid */
2420 case SIGINT:
2421 case SIGILL:
2422 case SIGFPE:
2423 case SIGSEGV:
2424 case SIGTERM:
2425 case SIGBREAK:
2426 case SIGABRT:
2427 break;
2428 /* Don't call signal() with other values or it will assert */
2429 default:
2430 return SIG_ERR;
2431 }
2432#endif /* _MSC_VER && _MSC_VER >= 1400 */
2433 handler = signal(sig, SIG_IGN);
2434 if (handler != SIG_ERR)
2435 signal(sig, handler);
2436 return handler;
2437#endif
2438}
2439
2440/*
2441 * All of the code in this function must only use async-signal-safe functions,
2442 * listed at `man 7 signal` or
2443 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2444 */
2445PyOS_sighandler_t
2446PyOS_setsig(int sig, PyOS_sighandler_t handler)
2447{
2448#ifdef HAVE_SIGACTION
2449 /* Some code in Modules/signalmodule.c depends on sigaction() being
2450 * used here if HAVE_SIGACTION is defined. Fix that if this code
2451 * changes to invalidate that assumption.
2452 */
2453 struct sigaction context, ocontext;
2454 context.sa_handler = handler;
2455 sigemptyset(&context.sa_mask);
2456 context.sa_flags = 0;
2457 if (sigaction(sig, &context, &ocontext) == -1)
2458 return SIG_ERR;
2459 return ocontext.sa_handler;
2460#else
2461 PyOS_sighandler_t oldhandler;
2462 oldhandler = signal(sig, handler);
2463#ifdef HAVE_SIGINTERRUPT
2464 siginterrupt(sig, 1);
2465#endif
2466 return oldhandler;
2467#endif
2468}
2469
2470#ifdef __cplusplus
2471}
2472#endif