blob: 6dc684bfcebb84ce67516504ebe110f2a7ffd1be [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 Stinner09532fe2019-05-10 23:39:09 +02009#include "pycore_coreconfig.h"
Victor Stinner353933e2018-11-23 13:08:26 +010010#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010011#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010012#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010013#include "pycore_pylifecycle.h"
14#include "pycore_pymem.h"
15#include "pycore_pystate.h"
Victor Stinnered488662019-05-20 00:14:57 +020016#include "pycore_traceback.h"
Nick Coghland6009512014-11-20 21:39:37 +100017#include "grammar.h"
18#include "node.h"
19#include "token.h"
20#include "parsetok.h"
21#include "errcode.h"
22#include "code.h"
23#include "symtable.h"
24#include "ast.h"
25#include "marshal.h"
26#include "osdefs.h"
27#include <locale.h>
28
29#ifdef HAVE_SIGNAL_H
30#include <signal.h>
31#endif
32
33#ifdef MS_WINDOWS
34#include "malloc.h" /* for alloca */
35#endif
36
37#ifdef HAVE_LANGINFO_H
38#include <langinfo.h>
39#endif
40
41#ifdef MS_WINDOWS
42#undef BYTE
43#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070044
45extern PyTypeObject PyWindowsConsoleIO_Type;
46#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100047#endif
48
49_Py_IDENTIFIER(flush);
50_Py_IDENTIFIER(name);
51_Py_IDENTIFIER(stdin);
52_Py_IDENTIFIER(stdout);
53_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060054_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100055
56#ifdef __cplusplus
57extern "C" {
58#endif
59
Nick Coghland6009512014-11-20 21:39:37 +100060extern grammar _PyParser_Grammar; /* From graminit.c */
61
62/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080063static _PyInitError add_main_module(PyInterpreterState *interp);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040064static _PyInitError init_import_size(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010065static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040066static _PyInitError init_signals(void);
Marcel Plch776407f2017-12-20 11:17:58 +010067static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100068static void wait_for_thread_shutdown(void);
Victor Stinner8e91c242019-04-24 17:24:01 +020069static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100070
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080071int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080072_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010073static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060074
Victor Stinnerf7e5b562017-11-15 15:48:08 -080075_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076_PyRuntime_Initialize(void)
77{
78 /* XXX We only initialize once in the process, which aligns with
79 the static initialization of the former globals now found in
80 _PyRuntime. However, _PyRuntime *should* be initialized with
81 every Py_Initialize() call, but doing so breaks the runtime.
82 This is because the runtime state is not properly finalized
83 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010084 if (runtime_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080085 return _Py_INIT_OK();
86 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010087 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080088
89 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060090}
91
92void
93_PyRuntime_Finalize(void)
94{
95 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010096 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99int
100_Py_IsFinalizing(void)
101{
102 return _PyRuntime.finalizing != NULL;
103}
104
Nick Coghland6009512014-11-20 21:39:37 +1000105/* Hack to force loading of object files */
106int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
107 PyOS_mystrnicmp; /* Python/pystrcmp.o */
108
109/* PyModule_GetWarningsModule is no longer necessary as of 2.6
110since _warnings is builtin. This API should not be used. */
111PyObject *
112PyModule_GetWarningsModule(void)
113{
114 return PyImport_ImportModule("warnings");
115}
116
Eric Snowc7ec9982017-05-23 23:00:52 -0700117
Eric Snow1abcf672017-05-23 21:46:51 -0700118/* APIs to access the initialization flags
119 *
120 * Can be called prior to Py_Initialize.
121 */
Nick Coghland6009512014-11-20 21:39:37 +1000122
Eric Snow1abcf672017-05-23 21:46:51 -0700123int
124_Py_IsCoreInitialized(void)
125{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600126 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700127}
Nick Coghland6009512014-11-20 21:39:37 +1000128
129int
130Py_IsInitialized(void)
131{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600132 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000133}
134
Nick Coghlan6ea41862017-06-11 13:16:15 +1000135
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000136/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
137 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000138 initializations fail, a fatal error is issued and the function does
139 not return. On return, the first thread and interpreter state have
140 been created.
141
142 Locking: you must hold the interpreter lock while calling this.
143 (If the lock has not yet been initialized, that's equivalent to
144 having the lock, but you cannot use multiple threads.)
145
146*/
147
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800148static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400149init_importlib(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000150{
151 PyObject *importlib;
152 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000153 PyObject *value;
Victor Stinnerc96be812019-05-14 17:34:56 +0200154 int verbose = interp->core_config.verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000155
156 /* Import _importlib through its frozen version, _frozen_importlib. */
157 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800158 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000159 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200160 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000161 PySys_FormatStderr("import _frozen_importlib # frozen\n");
162 }
163 importlib = PyImport_AddModule("_frozen_importlib");
164 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800165 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000166 }
167 interp->importlib = importlib;
168 Py_INCREF(interp->importlib);
169
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300170 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
171 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800172 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300173 Py_INCREF(interp->import_func);
174
Victor Stinnercd6e6942015-09-18 09:11:57 +0200175 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800176 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000177 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800178 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000179 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200180 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200181 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000182 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600183 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800184 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000185 }
186
Victor Stinnercd6e6942015-09-18 09:11:57 +0200187 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000188 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
189 if (value == NULL) {
190 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800191 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000192 }
193 Py_DECREF(value);
194 Py_DECREF(impmod);
195
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800196 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000197}
198
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800199static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400200init_importlib_external(PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700201{
202 PyObject *value;
203 value = PyObject_CallMethod(interp->importlib,
204 "_install_external_importers", "");
205 if (value == NULL) {
206 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800207 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700208 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200209 Py_DECREF(value);
Victor Stinner410b85a2019-05-13 17:12:45 +0200210 return _PyImportZip_Init(interp);
Eric Snow1abcf672017-05-23 21:46:51 -0700211}
Nick Coghland6009512014-11-20 21:39:37 +1000212
Nick Coghlan6ea41862017-06-11 13:16:15 +1000213/* Helper functions to better handle the legacy C locale
214 *
215 * The legacy C locale assumes ASCII as the default text encoding, which
216 * causes problems not only for the CPython runtime, but also other
217 * components like GNU readline.
218 *
219 * Accordingly, when the CLI detects it, it attempts to coerce it to a
220 * more capable UTF-8 based alternative as follows:
221 *
222 * if (_Py_LegacyLocaleDetected()) {
223 * _Py_CoerceLegacyLocale();
224 * }
225 *
226 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
227 *
228 * Locale coercion also impacts the default error handler for the standard
229 * streams: while the usual default is "strict", the default for the legacy
230 * C locale and for any of the coercion target locales is "surrogateescape".
231 */
232
233int
Victor Stinner0f721472019-05-20 17:16:38 +0200234_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000235{
236#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200237 if (!warn) {
238 const char *locale_override = getenv("LC_ALL");
239 if (locale_override != NULL && *locale_override != '\0') {
240 /* Don't coerce C locale if the LC_ALL environment variable
241 is set */
242 return 0;
243 }
244 }
245
Nick Coghlan6ea41862017-06-11 13:16:15 +1000246 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000247 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
248 * the POSIX locale as a simple alias for the C locale, so
249 * we may also want to check for that explicitly.
250 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000251 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
252 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
253#else
254 /* Windows uses code pages instead of locales, so no locale is legacy */
255 return 0;
256#endif
257}
258
Nick Coghlaneb817952017-06-18 12:29:42 +1000259static const char *_C_LOCALE_WARNING =
260 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
261 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
262 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
263 "locales is recommended.\n";
264
Nick Coghlaneb817952017-06-18 12:29:42 +1000265static void
Victor Stinner43125222019-04-24 18:23:53 +0200266emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000267{
Victor Stinner43125222019-04-24 18:23:53 +0200268 const _PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200269 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200270 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000271 }
272}
273
Nick Coghlan6ea41862017-06-11 13:16:15 +1000274typedef struct _CandidateLocale {
275 const char *locale_name; /* The locale to try as a coercion target */
276} _LocaleCoercionTarget;
277
278static _LocaleCoercionTarget _TARGET_LOCALES[] = {
279 {"C.UTF-8"},
280 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000281 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282 {NULL}
283};
284
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200285
286int
287_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000288{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200289 const _LocaleCoercionTarget *target = NULL;
290 for (target = _TARGET_LOCALES; target->locale_name; target++) {
291 if (strcmp(ctype_loc, target->locale_name) == 0) {
292 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000293 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200294 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200295 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000296}
297
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200298
Nick Coghlan6ea41862017-06-11 13:16:15 +1000299#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100300static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
302 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
303
Victor Stinner0f721472019-05-20 17:16:38 +0200304static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200305_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000306{
307 const char *newloc = target->locale_name;
308
309 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100310 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311
312 /* Set the relevant locale environment variable */
313 if (setenv("LC_CTYPE", newloc, 1)) {
314 fprintf(stderr,
315 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200316 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200318 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100319 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000320 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000321
322 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100323 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200324 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000325}
326#endif
327
Victor Stinner0f721472019-05-20 17:16:38 +0200328int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200329_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000330{
Victor Stinner0f721472019-05-20 17:16:38 +0200331 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000332#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200333 char *oldloc = NULL;
334
335 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
336 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200337 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200338 }
339
Victor Stinner94540602017-12-16 04:54:22 +0100340 const char *locale_override = getenv("LC_ALL");
341 if (locale_override == NULL || *locale_override == '\0') {
342 /* LC_ALL is also not set (or is set to an empty string) */
343 const _LocaleCoercionTarget *target = NULL;
344 for (target = _TARGET_LOCALES; target->locale_name; target++) {
345 const char *new_locale = setlocale(LC_CTYPE,
346 target->locale_name);
347 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400348#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100349 /* Also ensure that nl_langinfo works in this locale */
350 char *codeset = nl_langinfo(CODESET);
351 if (!codeset || *codeset == '\0') {
352 /* CODESET is not set or empty, so skip coercion */
353 new_locale = NULL;
354 _Py_SetLocaleFromEnv(LC_CTYPE);
355 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000356 }
Victor Stinner94540602017-12-16 04:54:22 +0100357#endif
358 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200359 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200360 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000361 }
362 }
363 }
364 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200365
366 setlocale(LC_CTYPE, oldloc);
367
368done:
369 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000370#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200371 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000372}
373
xdegaye1588be62017-11-12 12:45:59 +0100374/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
375 * isolate the idiosyncrasies of different libc implementations. It reads the
376 * appropriate environment variable and uses its value to select the locale for
377 * 'category'. */
378char *
379_Py_SetLocaleFromEnv(int category)
380{
Victor Stinner353933e2018-11-23 13:08:26 +0100381 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100382#ifdef __ANDROID__
383 const char *locale;
384 const char **pvar;
385#ifdef PY_COERCE_C_LOCALE
386 const char *coerce_c_locale;
387#endif
388 const char *utf8_locale = "C.UTF-8";
389 const char *env_var_set[] = {
390 "LC_ALL",
391 "LC_CTYPE",
392 "LANG",
393 NULL,
394 };
395
396 /* Android setlocale(category, "") doesn't check the environment variables
397 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
398 * check the environment variables listed in env_var_set. */
399 for (pvar=env_var_set; *pvar; pvar++) {
400 locale = getenv(*pvar);
401 if (locale != NULL && *locale != '\0') {
402 if (strcmp(locale, utf8_locale) == 0 ||
403 strcmp(locale, "en_US.UTF-8") == 0) {
404 return setlocale(category, utf8_locale);
405 }
406 return setlocale(category, "C");
407 }
408 }
409
410 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
411 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
412 * Quote from POSIX section "8.2 Internationalization Variables":
413 * "4. If the LANG environment variable is not set or is set to the empty
414 * string, the implementation-defined default locale shall be used." */
415
416#ifdef PY_COERCE_C_LOCALE
417 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
418 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
419 /* Some other ported code may check the environment variables (e.g. in
420 * extension modules), so we make sure that they match the locale
421 * configuration */
422 if (setenv("LC_CTYPE", utf8_locale, 1)) {
423 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
424 "environment variable to %s\n", utf8_locale);
425 }
426 }
427#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100428 res = setlocale(category, utf8_locale);
429#else /* !defined(__ANDROID__) */
430 res = setlocale(category, "");
431#endif
432 _Py_ResetForceASCII();
433 return res;
xdegaye1588be62017-11-12 12:45:59 +0100434}
435
Nick Coghlan6ea41862017-06-11 13:16:15 +1000436
Eric Snow1abcf672017-05-23 21:46:51 -0700437/* Global initializations. Can be undone by Py_Finalize(). Don't
438 call this twice without an intervening Py_Finalize() call.
439
Victor Stinner484f20d2019-03-27 02:04:16 +0100440 Every call to _Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700441 must have a corresponding call to Py_Finalize.
442
443 Locking: you must hold the interpreter lock while calling these APIs.
444 (If the lock has not yet been initialized, that's equivalent to
445 having the lock, but you cannot use multiple threads.)
446
447*/
448
Victor Stinner1dc6e392018-07-25 02:49:17 +0200449static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200450_Py_Initialize_ReconfigureCore(_PyRuntimeState *runtime,
451 PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200452 const _PyCoreConfig *core_config)
453{
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200454 _PyInitError err;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100455 PyThreadState *tstate = _PyThreadState_GET();
456 if (!tstate) {
457 return _Py_INIT_ERR("failed to read thread state");
458 }
459
460 PyInterpreterState *interp = tstate->interp;
461 if (interp == NULL) {
462 return _Py_INIT_ERR("can't make main interpreter");
463 }
464 *interp_p = interp;
465
Victor Stinner43125222019-04-24 18:23:53 +0200466 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200467
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200468 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
469 if (_Py_INIT_FAILED(err)) {
470 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200471 }
472 core_config = &interp->core_config;
473
474 if (core_config->_install_importlib) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200475 err = _PyCoreConfig_SetPathConfig(core_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200476 if (_Py_INIT_FAILED(err)) {
477 return err;
478 }
479 }
480 return _Py_INIT_OK();
481}
482
483
Victor Stinner1dc6e392018-07-25 02:49:17 +0200484static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200485pycore_init_runtime(_PyRuntimeState *runtime,
486 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000487{
Victor Stinner43125222019-04-24 18:23:53 +0200488 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200489 return _Py_INIT_ERR("main interpreter already initialized");
490 }
Victor Stinnerda273412017-12-15 01:46:02 +0100491
Victor Stinner43125222019-04-24 18:23:53 +0200492 _PyCoreConfig_Write(core_config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600493
Eric Snow1abcf672017-05-23 21:46:51 -0700494 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
495 * threads behave a little more gracefully at interpreter shutdown.
496 * We clobber it here so the new interpreter can start with a clean
497 * slate.
498 *
499 * However, this may still lead to misbehaviour if there are daemon
500 * threads still hanging around from a previous Py_Initialize/Finalize
501 * pair :(
502 */
Victor Stinner43125222019-04-24 18:23:53 +0200503 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600504
Victor Stinner43125222019-04-24 18:23:53 +0200505 _PyInitError err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800506 if (_Py_INIT_FAILED(err)) {
507 return err;
508 }
509
Victor Stinner43125222019-04-24 18:23:53 +0200510 err = _PyInterpreterState_Enable(runtime);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800511 if (_Py_INIT_FAILED(err)) {
512 return err;
513 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100514 return _Py_INIT_OK();
515}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800516
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517
518static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200519pycore_create_interpreter(_PyRuntimeState *runtime,
520 const _PyCoreConfig *core_config,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100521 PyInterpreterState **interp_p)
522{
523 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100524 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800525 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100526 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200527 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100528
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200529 _PyInitError err = _PyCoreConfig_Copy(&interp->core_config, core_config);
530 if (_Py_INIT_FAILED(err)) {
531 return err;
Victor Stinnerda273412017-12-15 01:46:02 +0100532 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200533 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000534
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200535 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000536 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800537 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000538 (void) PyThreadState_Swap(tstate);
539
Victor Stinner99fcc612019-04-29 13:04:07 +0200540 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
541 destroying the GIL might fail when it is being referenced from
542 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000543 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000544 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner09532fe2019-05-10 23:39:09 +0200545 _PyEval_FiniThreads(&runtime->ceval);
Victor Stinner2914bb32018-01-29 11:57:45 +0100546
Nick Coghland6009512014-11-20 21:39:37 +1000547 /* Auto-thread-state API */
Victor Stinner43125222019-04-24 18:23:53 +0200548 _PyGILState_Init(runtime, interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000549
Victor Stinner2914bb32018-01-29 11:57:45 +0100550 /* Create the GIL */
551 PyEval_InitThreads();
552
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100553 return _Py_INIT_OK();
554}
Nick Coghland6009512014-11-20 21:39:37 +1000555
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100556
557static _PyInitError
558pycore_init_types(void)
559{
Victor Stinnerab672812019-01-23 15:04:40 +0100560 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100561 if (_Py_INIT_FAILED(err)) {
562 return err;
563 }
564
565 err = _PyUnicode_Init();
566 if (_Py_INIT_FAILED(err)) {
567 return err;
568 }
569
570 if (_PyStructSequence_Init() < 0) {
571 return _Py_INIT_ERR("can't initialize structseq");
572 }
573
574 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800575 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100576 }
Nick Coghland6009512014-11-20 21:39:37 +1000577
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100578 err = _PyExc_Init();
579 if (_Py_INIT_FAILED(err)) {
580 return err;
581 }
582
583 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800584 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100585 }
Nick Coghland6009512014-11-20 21:39:37 +1000586
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100587 if (!_PyContext_Init()) {
588 return _Py_INIT_ERR("can't init context");
589 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200590
591 err = _PyErr_Init();
592 if (_Py_INIT_FAILED(err)) {
593 return err;
594 }
595
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100596 return _Py_INIT_OK();
597}
598
599
600static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100601pycore_init_builtins(PyInterpreterState *interp)
602{
603 PyObject *bimod = _PyBuiltin_Init();
604 if (bimod == NULL) {
605 return _Py_INIT_ERR("can't initialize builtins modules");
606 }
607 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
608
609 interp->builtins = PyModule_GetDict(bimod);
610 if (interp->builtins == NULL) {
611 return _Py_INIT_ERR("can't initialize builtins dict");
612 }
613 Py_INCREF(interp->builtins);
614
615 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
616 if (_Py_INIT_FAILED(err)) {
617 return err;
618 }
619 return _Py_INIT_OK();
620}
621
622
623static _PyInitError
624pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
625{
626 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800627 if (_Py_INIT_FAILED(err)) {
628 return err;
629 }
Nick Coghland6009512014-11-20 21:39:37 +1000630
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800631 err = _PyImportHooks_Init();
632 if (_Py_INIT_FAILED(err)) {
633 return err;
634 }
Nick Coghland6009512014-11-20 21:39:37 +1000635
636 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100637 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100638 return _Py_INIT_ERR("can't initialize warnings");
639 }
Nick Coghland6009512014-11-20 21:39:37 +1000640
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100641 if (interp->core_config._install_importlib) {
642 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200643 if (_Py_INIT_FAILED(err)) {
644 return err;
645 }
646 }
647
Eric Snow1abcf672017-05-23 21:46:51 -0700648 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100649 if (interp->core_config._install_importlib) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400650 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800651 if (_Py_INIT_FAILED(err)) {
652 return err;
653 }
Eric Snow1abcf672017-05-23 21:46:51 -0700654 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100655 return _Py_INIT_OK();
656}
657
658
659static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200660_Py_InitializeCore_impl(_PyRuntimeState *runtime,
661 PyInterpreterState **interp_p,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100662 const _PyCoreConfig *core_config)
663{
664 PyInterpreterState *interp;
665
Victor Stinner43125222019-04-24 18:23:53 +0200666 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100667
Victor Stinner43125222019-04-24 18:23:53 +0200668 _PyInitError err = pycore_init_runtime(runtime, core_config);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100669 if (_Py_INIT_FAILED(err)) {
670 return err;
671 }
672
Victor Stinner43125222019-04-24 18:23:53 +0200673 err = pycore_create_interpreter(runtime, core_config, &interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100674 if (_Py_INIT_FAILED(err)) {
675 return err;
676 }
677 core_config = &interp->core_config;
678 *interp_p = interp;
679
680 err = pycore_init_types();
681 if (_Py_INIT_FAILED(err)) {
682 return err;
683 }
684
685 PyObject *sysmod;
Victor Stinner43125222019-04-24 18:23:53 +0200686 err = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100687 if (_Py_INIT_FAILED(err)) {
688 return err;
689 }
690
691 err = pycore_init_builtins(interp);
692 if (_Py_INIT_FAILED(err)) {
693 return err;
694 }
695
696 err = pycore_init_import_warnings(interp, sysmod);
697 if (_Py_INIT_FAILED(err)) {
698 return err;
699 }
Eric Snow1abcf672017-05-23 21:46:51 -0700700
701 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200702 runtime->core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800703 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700704}
705
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100706
Victor Stinner70005ac2019-05-02 15:25:34 -0400707_PyInitError
708_Py_PreInitializeFromPyArgv(const _PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100709{
710 _PyInitError err;
711
Victor Stinner6d1c4672019-05-20 11:02:00 +0200712 if (src_config == NULL) {
713 return _Py_INIT_ERR("preinitialization config is NULL");
714 }
715
Victor Stinnerf29084d2019-03-20 02:20:13 +0100716 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100717 if (_Py_INIT_FAILED(err)) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100718 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100719 }
Victor Stinner43125222019-04-24 18:23:53 +0200720 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100721
Victor Stinner43125222019-04-24 18:23:53 +0200722 if (runtime->pre_initialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100723 /* If it's already configured: ignored the new configuration */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100724 return _Py_INIT_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100725 }
726
Victor Stinnercab5d072019-05-17 19:01:14 +0200727 _PyPreConfig config;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200728 _PyPreConfig_InitFromPreConfig(&config, src_config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100729
Victor Stinner5ac27a52019-03-27 13:40:14 +0100730 err = _PyPreConfig_Read(&config, args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100731 if (_Py_INIT_FAILED(err)) {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200732 return err;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100733 }
734
Victor Stinner5ac27a52019-03-27 13:40:14 +0100735 err = _PyPreConfig_Write(&config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100736 if (_Py_INIT_FAILED(err)) {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200737 return err;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100738 }
739
Victor Stinner43125222019-04-24 18:23:53 +0200740 runtime->pre_initialized = 1;
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200741 return _Py_INIT_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100742}
743
Victor Stinner70005ac2019-05-02 15:25:34 -0400744
Victor Stinnerf72346c2019-03-25 17:54:58 +0100745_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +0200746_Py_PreInitializeFromArgs(const _PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100747{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100748 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400749 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100750}
751
752
753_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +0200754_Py_PreInitializeFromWideArgs(const _PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100755{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100756 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400757 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100758}
759
760
761_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100762_Py_PreInitialize(const _PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100763{
Victor Stinner70005ac2019-05-02 15:25:34 -0400764 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100765}
766
767
768_PyInitError
Victor Stinner70005ac2019-05-02 15:25:34 -0400769_Py_PreInitializeFromCoreConfig(const _PyCoreConfig *coreconfig,
770 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100771{
Victor Stinner6d1c4672019-05-20 11:02:00 +0200772 assert(coreconfig != NULL);
773
774 _PyInitError err = _PyRuntime_Initialize();
775 if (_Py_INIT_FAILED(err)) {
776 return err;
777 }
778 _PyRuntimeState *runtime = &_PyRuntime;
779
780 if (runtime->pre_initialized) {
781 /* Already initialized: do nothing */
782 return _Py_INIT_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400783 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200784
Victor Stinner6d1c4672019-05-20 11:02:00 +0200785 _PyPreConfig preconfig;
786 _PyPreConfig_InitFromCoreConfig(&preconfig, coreconfig);
787
788 if (!coreconfig->parse_argv) {
789 return _Py_PreInitialize(&preconfig);
790 }
791 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200792 _PyArgv config_args = {
793 .use_bytes_argv = 0,
794 .argc = coreconfig->argv.length,
795 .wchar_argv = coreconfig->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200796 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200797 }
798 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200799 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200800 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100801}
802
803
804static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200805pyinit_coreconfig(_PyRuntimeState *runtime,
806 _PyCoreConfig *config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100807 const _PyCoreConfig *src_config,
808 const _PyArgv *args,
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100809 PyInterpreterState **interp_p)
810{
Victor Stinner6d1c4672019-05-20 11:02:00 +0200811 assert(src_config != NULL);
Victor Stinner5f38b842019-05-01 02:30:12 +0200812
Victor Stinner6d1c4672019-05-20 11:02:00 +0200813 _PyInitError err = _PyCoreConfig_Copy(config, src_config);
814 if (_Py_INIT_FAILED(err)) {
815 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100816 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100817
Victor Stinner5f38b842019-05-01 02:30:12 +0200818 if (args) {
819 err = _PyCoreConfig_SetPyArgv(config, args);
820 if (_Py_INIT_FAILED(err)) {
821 return err;
822 }
823 }
824
825 err = _PyCoreConfig_Read(config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100826 if (_Py_INIT_FAILED(err)) {
827 return err;
828 }
829
Victor Stinner43125222019-04-24 18:23:53 +0200830 if (!runtime->core_initialized) {
831 return _Py_InitializeCore_impl(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100832 }
833 else {
Victor Stinner43125222019-04-24 18:23:53 +0200834 return _Py_Initialize_ReconfigureCore(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100835 }
836}
837
838
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100839/* Begin interpreter initialization
840 *
841 * On return, the first thread and interpreter state have been created,
842 * but the compiler, signal handling, multithreading and
843 * multiple interpreter support, and codec infrastructure are not yet
844 * available.
845 *
846 * The import system will support builtin and frozen modules only.
847 * The only supported io is writing to sys.stderr
848 *
849 * If any operation invoked by this function fails, a fatal error is
850 * issued and the function does not return.
851 *
852 * Any code invoked from this function should *not* assume it has access
853 * to the Python C API (unless the API is explicitly listed as being
854 * safe to call without calling Py_Initialize first)
855 */
Victor Stinner484f20d2019-03-27 02:04:16 +0100856static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200857_Py_InitializeCore(_PyRuntimeState *runtime,
858 const _PyCoreConfig *src_config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100859 const _PyArgv *args,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100860 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200861{
Victor Stinnerd929f182019-03-27 18:28:46 +0100862 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200863
Victor Stinner70005ac2019-05-02 15:25:34 -0400864 err = _Py_PreInitializeFromCoreConfig(src_config, args);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200865 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100866 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200867 }
868
Victor Stinnercab5d072019-05-17 19:01:14 +0200869 _PyCoreConfig local_config;
870 _PyCoreConfig_Init(&local_config);
Victor Stinner43125222019-04-24 18:23:53 +0200871 err = pyinit_coreconfig(runtime, &local_config, src_config, args, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100872 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200873 return err;
874}
875
Victor Stinner5ac27a52019-03-27 13:40:14 +0100876
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200877/* Py_Initialize() has already been called: update the main interpreter
878 configuration. Example of bpo-34008: Py_Main() called after
879 Py_Initialize(). */
880static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100881_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200882{
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100883 _PyCoreConfig *core_config = &interp->core_config;
884
885 PyObject *argv = _PyWstrList_AsList(&core_config->argv);
886 if (argv == NULL) {
887 return _Py_INIT_NO_MEMORY(); \
888 }
889
890 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
891 Py_DECREF(argv);
892 if (res < 0) {
893 return _Py_INIT_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200894 }
895 return _Py_INIT_OK();
896}
897
Eric Snowc7ec9982017-05-23 23:00:52 -0700898/* Update interpreter state based on supplied configuration settings
899 *
900 * After calling this function, most of the restrictions on the interpreter
901 * are lifted. The only remaining incomplete settings are those related
902 * to the main module (sys.argv[0], __main__ metadata)
903 *
904 * Calling this when the interpreter is not initializing, is already
905 * initialized or without a valid current thread state is a fatal error.
906 * Other errors should be reported as normal Python exceptions with a
907 * non-zero return code.
908 */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100909static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200910_Py_InitializeMainInterpreter(_PyRuntimeState *runtime,
911 PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700912{
Victor Stinner43125222019-04-24 18:23:53 +0200913 if (!runtime->core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800914 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700915 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700916
Victor Stinner1dc6e392018-07-25 02:49:17 +0200917 /* Configure the main interpreter */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200918 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700919
Victor Stinner43125222019-04-24 18:23:53 +0200920 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100921 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200922 }
923
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200924 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700925 /* Special mode for freeze_importlib: run with no import system
926 *
927 * This means anything which needs support from extension modules
928 * or pure Python code in the standard library won't work.
929 */
Victor Stinner43125222019-04-24 18:23:53 +0200930 runtime->initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700932 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100933
Victor Stinner33c377e2017-12-05 15:12:41 +0100934 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800935 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100936 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200937
Victor Stinner43125222019-04-24 18:23:53 +0200938 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800939 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100940 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800941
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400942 _PyInitError err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800943 if (_Py_INIT_FAILED(err)) {
944 return err;
945 }
Nick Coghland6009512014-11-20 21:39:37 +1000946
947 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200948 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800949 if (_Py_INIT_FAILED(err)) {
950 return err;
951 }
Nick Coghland6009512014-11-20 21:39:37 +1000952
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400953 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800954 if (_Py_INIT_FAILED(err)) {
955 return err;
956 }
Nick Coghland6009512014-11-20 21:39:37 +1000957
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100958 if (core_config->install_signal_handlers) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400959 err = init_signals();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800960 if (_Py_INIT_FAILED(err)) {
961 return err;
962 }
963 }
Nick Coghland6009512014-11-20 21:39:37 +1000964
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200965 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800966 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200967 }
Nick Coghland6009512014-11-20 21:39:37 +1000968
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800969 err = add_main_module(interp);
970 if (_Py_INIT_FAILED(err)) {
971 return err;
972 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800973
Victor Stinner91106cd2017-12-13 12:29:09 +0100974 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800975 if (_Py_INIT_FAILED(err)) {
976 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800977 }
Nick Coghland6009512014-11-20 21:39:37 +1000978
979 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100980 PyObject *warnoptions = PySys_GetObject("warnoptions");
981 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100982 {
Nick Coghland6009512014-11-20 21:39:37 +1000983 PyObject *warnings_module = PyImport_ImportModule("warnings");
984 if (warnings_module == NULL) {
985 fprintf(stderr, "'import warnings' failed; traceback:\n");
986 PyErr_Print();
987 }
988 Py_XDECREF(warnings_module);
989 }
990
Victor Stinner43125222019-04-24 18:23:53 +0200991 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700992
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200993 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400994 err = init_import_size(); /* Module site */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800995 if (_Py_INIT_FAILED(err)) {
996 return err;
997 }
998 }
Victor Stinnercf215042018-08-29 22:56:06 +0200999
1000#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +02001001 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +02001002#endif
1003
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001004 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001005}
1006
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001007
1008_PyInitError
1009_Py_InitializeMain(void)
1010{
1011 _PyInitError err = _PyRuntime_Initialize();
1012 if (_Py_INIT_FAILED(err)) {
1013 return err;
1014 }
1015 _PyRuntimeState *runtime = &_PyRuntime;
1016 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
1017
1018 return _Py_InitializeMainInterpreter(runtime, interp);
1019}
1020
1021
Eric Snowc7ec9982017-05-23 23:00:52 -07001022#undef _INIT_DEBUG_PRINT
1023
Victor Stinner5ac27a52019-03-27 13:40:14 +01001024static _PyInitError
1025init_python(const _PyCoreConfig *config, const _PyArgv *args)
Eric Snow1abcf672017-05-23 21:46:51 -07001026{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001027 if (config == NULL) {
1028 return _Py_INIT_ERR("initialization config is NULL");
1029 }
1030
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001031 _PyInitError err;
Victor Stinner43125222019-04-24 18:23:53 +02001032
1033 err = _PyRuntime_Initialize();
1034 if (_Py_INIT_FAILED(err)) {
1035 return err;
1036 }
1037 _PyRuntimeState *runtime = &_PyRuntime;
1038
1039 PyInterpreterState *interp = NULL;
1040 err = _Py_InitializeCore(runtime, config, args, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001041 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001042 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001043 }
Victor Stinner1dc6e392018-07-25 02:49:17 +02001044 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001045
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001046 if (config->_init_main) {
Victor Stinner43125222019-04-24 18:23:53 +02001047 err = _Py_InitializeMainInterpreter(runtime, interp);
Victor Stinner484f20d2019-03-27 02:04:16 +01001048 if (_Py_INIT_FAILED(err)) {
1049 return err;
1050 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001051 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001052
Victor Stinner1dc6e392018-07-25 02:49:17 +02001053 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001054}
1055
1056
Victor Stinner5ac27a52019-03-27 13:40:14 +01001057_PyInitError
Victor Stinner6d1c4672019-05-20 11:02:00 +02001058_Py_InitializeFromArgs(const _PyCoreConfig *config,
1059 Py_ssize_t argc, char * const *argv)
Victor Stinner5ac27a52019-03-27 13:40:14 +01001060{
1061 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1062 return init_python(config, &args);
1063}
1064
1065
1066_PyInitError
Victor Stinner6d1c4672019-05-20 11:02:00 +02001067_Py_InitializeFromWideArgs(const _PyCoreConfig *config,
1068 Py_ssize_t argc, wchar_t * const *argv)
Victor Stinner5ac27a52019-03-27 13:40:14 +01001069{
1070 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1071 return init_python(config, &args);
1072}
1073
1074
1075_PyInitError
1076_Py_InitializeFromConfig(const _PyCoreConfig *config)
1077{
1078 return init_python(config, NULL);
1079}
1080
1081
Eric Snow1abcf672017-05-23 21:46:51 -07001082void
Nick Coghland6009512014-11-20 21:39:37 +10001083Py_InitializeEx(int install_sigs)
1084{
Victor Stinner43125222019-04-24 18:23:53 +02001085 _PyInitError err;
1086
1087 err = _PyRuntime_Initialize();
1088 if (_Py_INIT_FAILED(err)) {
1089 _Py_ExitInitError(err);
1090 }
1091 _PyRuntimeState *runtime = &_PyRuntime;
1092
1093 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001094 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1095 return;
1096 }
1097
Victor Stinnercab5d072019-05-17 19:01:14 +02001098 _PyCoreConfig config;
1099 _PyCoreConfig_Init(&config);
Victor Stinner1dc6e392018-07-25 02:49:17 +02001100 config.install_signal_handlers = install_sigs;
1101
Victor Stinner43125222019-04-24 18:23:53 +02001102 err = _Py_InitializeFromConfig(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001103 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001104 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001105 }
Nick Coghland6009512014-11-20 21:39:37 +10001106}
1107
1108void
1109Py_Initialize(void)
1110{
1111 Py_InitializeEx(1);
1112}
1113
1114
1115#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001116extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001117#endif
1118
1119/* Flush stdout and stderr */
1120
1121static int
1122file_is_closed(PyObject *fobj)
1123{
1124 int r;
1125 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1126 if (tmp == NULL) {
1127 PyErr_Clear();
1128 return 0;
1129 }
1130 r = PyObject_IsTrue(tmp);
1131 Py_DECREF(tmp);
1132 if (r < 0)
1133 PyErr_Clear();
1134 return r > 0;
1135}
1136
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001137static int
Nick Coghland6009512014-11-20 21:39:37 +10001138flush_std_files(void)
1139{
1140 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1141 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1142 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001143 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001144
1145 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001146 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001147 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001148 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001149 status = -1;
1150 }
Nick Coghland6009512014-11-20 21:39:37 +10001151 else
1152 Py_DECREF(tmp);
1153 }
1154
1155 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001156 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001157 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001158 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001159 status = -1;
1160 }
Nick Coghland6009512014-11-20 21:39:37 +10001161 else
1162 Py_DECREF(tmp);
1163 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001164
1165 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001166}
1167
1168/* Undo the effect of Py_Initialize().
1169
1170 Beware: if multiple interpreter and/or thread states exist, these
1171 are not wiped out; only the current thread and interpreter state
1172 are deleted. But since everything else is deleted, those other
1173 interpreter and thread states should no longer be used.
1174
1175 (XXX We should do better, e.g. wipe out all interpreters and
1176 threads.)
1177
1178 Locking: as above.
1179
1180*/
1181
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001182int
1183Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001184{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001185 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001186
Victor Stinner8e91c242019-04-24 17:24:01 +02001187 _PyRuntimeState *runtime = &_PyRuntime;
1188 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001189 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001190 }
Nick Coghland6009512014-11-20 21:39:37 +10001191
Eric Snow842a2f02019-03-15 15:47:51 -06001192 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001193 wait_for_thread_shutdown();
1194
Eric Snow842a2f02019-03-15 15:47:51 -06001195 // Make any remaining pending calls.
Victor Stinner09532fe2019-05-10 23:39:09 +02001196 _Py_FinishPendingCalls(runtime);
Eric Snow842a2f02019-03-15 15:47:51 -06001197
Victor Stinner8e91c242019-04-24 17:24:01 +02001198 /* Get current thread state and interpreter pointer */
Victor Stinner09532fe2019-05-10 23:39:09 +02001199 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001200 PyInterpreterState *interp = tstate->interp;
1201
Nick Coghland6009512014-11-20 21:39:37 +10001202 /* The interpreter is still entirely intact at this point, and the
1203 * exit funcs may be relying on that. In particular, if some thread
1204 * or exit func is still waiting to do an import, the import machinery
1205 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001206 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001207 * Note that Threading.py uses an exit func to do a join on all the
1208 * threads created thru it, so this also protects pending imports in
1209 * the threads created via Threading.
1210 */
Nick Coghland6009512014-11-20 21:39:37 +10001211
Marcel Plch776407f2017-12-20 11:17:58 +01001212 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001213
Victor Stinnerda273412017-12-15 01:46:02 +01001214 /* Copy the core config, PyInterpreterState_Delete() free
1215 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001216#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001217 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001218#endif
1219#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001220 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001221#endif
1222#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001223 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001224#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001225
Nick Coghland6009512014-11-20 21:39:37 +10001226 /* Remaining threads (e.g. daemon threads) will automatically exit
1227 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001228 runtime->finalizing = tstate;
1229 runtime->initialized = 0;
1230 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001231
Victor Stinnere0deff32015-03-24 13:46:18 +01001232 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001233 if (flush_std_files() < 0) {
1234 status = -1;
1235 }
Nick Coghland6009512014-11-20 21:39:37 +10001236
1237 /* Disable signal handling */
1238 PyOS_FiniInterrupts();
1239
1240 /* Collect garbage. This may call finalizers; it's nice to call these
1241 * before all modules are destroyed.
1242 * XXX If a __del__ or weakref callback is triggered here, and tries to
1243 * XXX import a module, bad things can happen, because Python no
1244 * XXX longer believes it's initialized.
1245 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1246 * XXX is easy to provoke that way. I've also seen, e.g.,
1247 * XXX Exception exceptions.ImportError: 'No module named sha'
1248 * XXX in <function callback at 0x008F5718> ignored
1249 * XXX but I'm unclear on exactly how that one happens. In any case,
1250 * XXX I haven't seen a real-life report of either of these.
1251 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001252 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001253#ifdef COUNT_ALLOCS
1254 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1255 each collection might release some types from the type
1256 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001257 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001258 /* nothing */;
1259#endif
Eric Snowdae02762017-09-14 00:35:58 -07001260
Nick Coghland6009512014-11-20 21:39:37 +10001261 /* Destroy all modules */
1262 PyImport_Cleanup();
1263
Victor Stinnere0deff32015-03-24 13:46:18 +01001264 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001265 if (flush_std_files() < 0) {
1266 status = -1;
1267 }
Nick Coghland6009512014-11-20 21:39:37 +10001268
1269 /* Collect final garbage. This disposes of cycles created by
1270 * class definitions, for example.
1271 * XXX This is disabled because it caused too many problems. If
1272 * XXX a __del__ or weakref callback triggers here, Python code has
1273 * XXX a hard time running, because even the sys module has been
1274 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1275 * XXX One symptom is a sequence of information-free messages
1276 * XXX coming from threads (if a __del__ or callback is invoked,
1277 * XXX other threads can execute too, and any exception they encounter
1278 * XXX triggers a comedy of errors as subsystem after subsystem
1279 * XXX fails to find what it *expects* to find in sys to help report
1280 * XXX the exception and consequent unexpected failures). I've also
1281 * XXX seen segfaults then, after adding print statements to the
1282 * XXX Python code getting called.
1283 */
1284#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001285 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001286#endif
1287
1288 /* Disable tracemalloc after all Python objects have been destroyed,
1289 so it is possible to use tracemalloc in objects destructor. */
1290 _PyTraceMalloc_Fini();
1291
1292 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1293 _PyImport_Fini();
1294
1295 /* Cleanup typeobject.c's internal caches. */
1296 _PyType_Fini();
1297
1298 /* unload faulthandler module */
1299 _PyFaulthandler_Fini();
1300
1301 /* Debugging stuff */
1302#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001303 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001304#endif
1305 /* dump hash stats */
1306 _PyHash_Fini();
1307
Eric Snowdae02762017-09-14 00:35:58 -07001308#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001309 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001310 _PyDebug_PrintTotalRefs();
1311 }
Eric Snowdae02762017-09-14 00:35:58 -07001312#endif
Nick Coghland6009512014-11-20 21:39:37 +10001313
1314#ifdef Py_TRACE_REFS
1315 /* Display all objects still alive -- this can invoke arbitrary
1316 * __repr__ overrides, so requires a mostly-intact interpreter.
1317 * Alas, a lot of stuff may still be alive now that will be cleaned
1318 * up later.
1319 */
Victor Stinnerda273412017-12-15 01:46:02 +01001320 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001321 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001322 }
Nick Coghland6009512014-11-20 21:39:37 +10001323#endif /* Py_TRACE_REFS */
1324
1325 /* Clear interpreter state and all thread states. */
1326 PyInterpreterState_Clear(interp);
1327
1328 /* Now we decref the exception classes. After this point nothing
1329 can raise an exception. That's okay, because each Fini() method
1330 below has been checked to make sure no exceptions are ever
1331 raised.
1332 */
1333
1334 _PyExc_Fini();
1335
1336 /* Sundry finalizers */
1337 PyMethod_Fini();
1338 PyFrame_Fini();
1339 PyCFunction_Fini();
1340 PyTuple_Fini();
1341 PyList_Fini();
1342 PySet_Fini();
1343 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001344 PyLong_Fini();
1345 PyFloat_Fini();
1346 PyDict_Fini();
1347 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001348 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001349 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001350 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001351 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001352 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001353 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001354
1355 /* Cleanup Unicode implementation */
1356 _PyUnicode_Fini();
1357
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001358 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001359
1360 /* XXX Still allocated:
1361 - various static ad-hoc pointers to interned strings
1362 - int and float free list blocks
1363 - whatever various modules and libraries allocate
1364 */
1365
1366 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1367
1368 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001369 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001370
1371 /* Delete current thread. After this, many C API calls become crashy. */
1372 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001373
Nick Coghland6009512014-11-20 21:39:37 +10001374 PyInterpreterState_Delete(interp);
1375
1376#ifdef Py_TRACE_REFS
1377 /* Display addresses (& refcnts) of all objects still alive.
1378 * An address can be used to find the repr of the object, printed
1379 * above by _Py_PrintReferences.
1380 */
Victor Stinnerda273412017-12-15 01:46:02 +01001381 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001382 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001383 }
Nick Coghland6009512014-11-20 21:39:37 +10001384#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001385#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001386 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001387 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001388 }
Nick Coghland6009512014-11-20 21:39:37 +10001389#endif
1390
Victor Stinner8e91c242019-04-24 17:24:01 +02001391 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001392
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001393 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001394 return status;
1395}
1396
1397void
1398Py_Finalize(void)
1399{
1400 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001401}
1402
1403/* Create and initialize a new interpreter and thread, and return the
1404 new thread. This requires that Py_Initialize() has been called
1405 first.
1406
1407 Unsuccessful initialization yields a NULL pointer. Note that *no*
1408 exception information is available even in this case -- the
1409 exception information is held in the thread, and there is no
1410 thread.
1411
1412 Locking: as above.
1413
1414*/
1415
Victor Stinnera7368ac2017-11-15 18:11:45 -08001416static _PyInitError
1417new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001418{
Victor Stinner9316ee42017-11-25 03:17:57 +01001419 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001420
Victor Stinner43125222019-04-24 18:23:53 +02001421 err = _PyRuntime_Initialize();
1422 if (_Py_INIT_FAILED(err)) {
1423 return err;
1424 }
1425 _PyRuntimeState *runtime = &_PyRuntime;
1426
1427 if (!runtime->initialized) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001428 return _Py_INIT_ERR("Py_Initialize must be called first");
1429 }
Nick Coghland6009512014-11-20 21:39:37 +10001430
Victor Stinner8a1be612016-03-14 22:07:55 +01001431 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1432 interpreters: disable PyGILState_Check(). */
1433 _PyGILState_check_enabled = 0;
1434
Victor Stinner43125222019-04-24 18:23:53 +02001435 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001436 if (interp == NULL) {
1437 *tstate_p = NULL;
1438 return _Py_INIT_OK();
1439 }
Nick Coghland6009512014-11-20 21:39:37 +10001440
Victor Stinner43125222019-04-24 18:23:53 +02001441 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001442 if (tstate == NULL) {
1443 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001444 *tstate_p = NULL;
1445 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001446 }
1447
Victor Stinner43125222019-04-24 18:23:53 +02001448 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001449
Eric Snow1abcf672017-05-23 21:46:51 -07001450 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001451 _PyCoreConfig *core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001452 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001453 core_config = &save_tstate->interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001454 } else {
1455 /* No current thread state, copy from the main interpreter */
1456 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001457 core_config = &main_interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001458 }
1459
Victor Stinner1a9f0d82019-05-01 15:22:52 +02001460 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
1461 if (_Py_INIT_FAILED(err)) {
1462 return err;
Victor Stinnerda273412017-12-15 01:46:02 +01001463 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001464 core_config = &interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001465
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001466 err = _PyExc_Init();
1467 if (_Py_INIT_FAILED(err)) {
1468 return err;
1469 }
1470
Victor Stinneref9d9b62019-05-22 11:28:22 +02001471 err = _PyErr_Init();
1472 if (_Py_INIT_FAILED(err)) {
1473 return err;
1474 }
1475
1476
Nick Coghland6009512014-11-20 21:39:37 +10001477 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001478 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001479 if (modules == NULL) {
1480 return _Py_INIT_ERR("can't make modules dictionary");
1481 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001482 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001483
Victor Stinner43125222019-04-24 18:23:53 +02001484 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001485 if (sysmod != NULL) {
1486 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001487 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001488 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001489 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001490 Py_INCREF(interp->sysdict);
1491 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner43125222019-04-24 18:23:53 +02001492 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerab672812019-01-23 15:04:40 +01001493 return _Py_INIT_ERR("can't finish initializing sys");
1494 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001495 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001496 else if (PyErr_Occurred()) {
1497 goto handle_error;
1498 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001499
Victor Stinner43125222019-04-24 18:23:53 +02001500 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001501 if (bimod != NULL) {
1502 interp->builtins = PyModule_GetDict(bimod);
1503 if (interp->builtins == NULL)
1504 goto handle_error;
1505 Py_INCREF(interp->builtins);
1506 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001507 else if (PyErr_Occurred()) {
1508 goto handle_error;
1509 }
Nick Coghland6009512014-11-20 21:39:37 +10001510
Nick Coghland6009512014-11-20 21:39:37 +10001511 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001512 err = _PyBuiltins_AddExceptions(bimod);
1513 if (_Py_INIT_FAILED(err)) {
1514 return err;
1515 }
Nick Coghland6009512014-11-20 21:39:37 +10001516
Victor Stinnerab672812019-01-23 15:04:40 +01001517 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1518 if (_Py_INIT_FAILED(err)) {
1519 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001520 }
Nick Coghland6009512014-11-20 21:39:37 +10001521
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001522 err = _PyImportHooks_Init();
1523 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001524 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001525 }
Nick Coghland6009512014-11-20 21:39:37 +10001526
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001527 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001528 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001529 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001530 }
Nick Coghland6009512014-11-20 21:39:37 +10001531
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001532 err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001533 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001534 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001535 }
Nick Coghland6009512014-11-20 21:39:37 +10001536
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001537 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001538 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001539 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001540 }
1541
Victor Stinner91106cd2017-12-13 12:29:09 +01001542 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001543 if (_Py_INIT_FAILED(err)) {
1544 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001545 }
1546
1547 err = add_main_module(interp);
1548 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001549 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001550 }
1551
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001552 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001553 err = init_import_size();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001554 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001555 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001556 }
1557 }
Nick Coghland6009512014-11-20 21:39:37 +10001558 }
1559
Victor Stinnera7368ac2017-11-15 18:11:45 -08001560 if (PyErr_Occurred()) {
1561 goto handle_error;
1562 }
Nick Coghland6009512014-11-20 21:39:37 +10001563
Victor Stinnera7368ac2017-11-15 18:11:45 -08001564 *tstate_p = tstate;
1565 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001566
Nick Coghland6009512014-11-20 21:39:37 +10001567handle_error:
1568 /* Oops, it didn't work. Undo it all. */
1569
1570 PyErr_PrintEx(0);
1571 PyThreadState_Clear(tstate);
1572 PyThreadState_Swap(save_tstate);
1573 PyThreadState_Delete(tstate);
1574 PyInterpreterState_Delete(interp);
1575
Victor Stinnera7368ac2017-11-15 18:11:45 -08001576 *tstate_p = NULL;
1577 return _Py_INIT_OK();
1578}
1579
1580PyThreadState *
1581Py_NewInterpreter(void)
1582{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001583 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001584 _PyInitError err = new_interpreter(&tstate);
1585 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001586 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001587 }
1588 return tstate;
1589
Nick Coghland6009512014-11-20 21:39:37 +10001590}
1591
1592/* Delete an interpreter and its last thread. This requires that the
1593 given thread state is current, that the thread has no remaining
1594 frames, and that it is its interpreter's only remaining thread.
1595 It is a fatal error to violate these constraints.
1596
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001597 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001598 everything, regardless.)
1599
1600 Locking: as above.
1601
1602*/
1603
1604void
1605Py_EndInterpreter(PyThreadState *tstate)
1606{
1607 PyInterpreterState *interp = tstate->interp;
1608
Victor Stinner50b48572018-11-01 01:51:40 +01001609 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001610 Py_FatalError("Py_EndInterpreter: thread is not current");
1611 if (tstate->frame != NULL)
1612 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001613 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001614
Eric Snow842a2f02019-03-15 15:47:51 -06001615 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001616 wait_for_thread_shutdown();
1617
Marcel Plch776407f2017-12-20 11:17:58 +01001618 call_py_exitfuncs(interp);
1619
Nick Coghland6009512014-11-20 21:39:37 +10001620 if (tstate != interp->tstate_head || tstate->next != NULL)
1621 Py_FatalError("Py_EndInterpreter: not the last thread");
1622
1623 PyImport_Cleanup();
1624 PyInterpreterState_Clear(interp);
1625 PyThreadState_Swap(NULL);
1626 PyInterpreterState_Delete(interp);
1627}
1628
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001629/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001630
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001631static _PyInitError
1632add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001633{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001634 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001635 m = PyImport_AddModule("__main__");
1636 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001637 return _Py_INIT_ERR("can't create __main__ module");
1638
Nick Coghland6009512014-11-20 21:39:37 +10001639 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001640 ann_dict = PyDict_New();
1641 if ((ann_dict == NULL) ||
1642 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001643 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001644 }
1645 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001646
Nick Coghland6009512014-11-20 21:39:37 +10001647 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1648 PyObject *bimod = PyImport_ImportModule("builtins");
1649 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001650 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001651 }
1652 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001653 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001654 }
1655 Py_DECREF(bimod);
1656 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001657
Nick Coghland6009512014-11-20 21:39:37 +10001658 /* Main is a little special - imp.is_builtin("__main__") will return
1659 * False, but BuiltinImporter is still the most appropriate initial
1660 * setting for its __loader__ attribute. A more suitable value will
1661 * be set if __main__ gets further initialized later in the startup
1662 * process.
1663 */
1664 loader = PyDict_GetItemString(d, "__loader__");
1665 if (loader == NULL || loader == Py_None) {
1666 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1667 "BuiltinImporter");
1668 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001669 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001670 }
1671 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001672 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001673 }
1674 Py_DECREF(loader);
1675 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001676 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001677}
1678
Nick Coghland6009512014-11-20 21:39:37 +10001679/* Import the site module (not into __main__ though) */
1680
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001681static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001682init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001683{
1684 PyObject *m;
1685 m = PyImport_ImportModule("site");
1686 if (m == NULL) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001687 return _Py_INIT_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001688 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001689 Py_DECREF(m);
1690 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001691}
1692
Victor Stinner874dbe82015-09-04 17:29:57 +02001693/* Check if a file descriptor is valid or not.
1694 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1695static int
1696is_valid_fd(int fd)
1697{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001698/* dup() is faster than fstat(): fstat() can require input/output operations,
1699 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1700 startup. Problem: dup() doesn't check if the file descriptor is valid on
1701 some platforms.
1702
1703 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1704 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1705 EBADF. FreeBSD has similar issue (bpo-32849).
1706
1707 Only use dup() on platforms where dup() is enough to detect invalid FD in
1708 corner cases: on Linux and Windows (bpo-32849). */
1709#if defined(__linux__) || defined(MS_WINDOWS)
1710 if (fd < 0) {
1711 return 0;
1712 }
1713 int fd2;
1714
1715 _Py_BEGIN_SUPPRESS_IPH
1716 fd2 = dup(fd);
1717 if (fd2 >= 0) {
1718 close(fd2);
1719 }
1720 _Py_END_SUPPRESS_IPH
1721
1722 return (fd2 >= 0);
1723#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001724 struct stat st;
1725 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001726#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001727}
1728
1729/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001730static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001731create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001732 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001733 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001734{
1735 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1736 const char* mode;
1737 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001738 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001739 int buffering, isatty;
1740 _Py_IDENTIFIER(open);
1741 _Py_IDENTIFIER(isatty);
1742 _Py_IDENTIFIER(TextIOWrapper);
1743 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001744 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001745
Victor Stinner874dbe82015-09-04 17:29:57 +02001746 if (!is_valid_fd(fd))
1747 Py_RETURN_NONE;
1748
Nick Coghland6009512014-11-20 21:39:37 +10001749 /* stdin is always opened in buffered mode, first because it shouldn't
1750 make a difference in common use cases, second because TextIOWrapper
1751 depends on the presence of a read1() method which only exists on
1752 buffered streams.
1753 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001754 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001755 buffering = 0;
1756 else
1757 buffering = -1;
1758 if (write_mode)
1759 mode = "wb";
1760 else
1761 mode = "rb";
1762 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1763 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001764 Py_None, Py_None, /* encoding, errors */
1765 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001766 if (buf == NULL)
1767 goto error;
1768
1769 if (buffering) {
1770 _Py_IDENTIFIER(raw);
1771 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1772 if (raw == NULL)
1773 goto error;
1774 }
1775 else {
1776 raw = buf;
1777 Py_INCREF(raw);
1778 }
1779
Steve Dower39294992016-08-30 21:22:36 -07001780#ifdef MS_WINDOWS
1781 /* Windows console IO is always UTF-8 encoded */
1782 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001783 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001784#endif
1785
Nick Coghland6009512014-11-20 21:39:37 +10001786 text = PyUnicode_FromString(name);
1787 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1788 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001789 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001790 if (res == NULL)
1791 goto error;
1792 isatty = PyObject_IsTrue(res);
1793 Py_DECREF(res);
1794 if (isatty == -1)
1795 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001796 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001797 write_through = Py_True;
1798 else
1799 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001800 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001801 line_buffering = Py_True;
1802 else
1803 line_buffering = Py_False;
1804
1805 Py_CLEAR(raw);
1806 Py_CLEAR(text);
1807
1808#ifdef MS_WINDOWS
1809 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1810 newlines to "\n".
1811 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1812 newline = NULL;
1813#else
1814 /* sys.stdin: split lines at "\n".
1815 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1816 newline = "\n";
1817#endif
1818
Victor Stinner709d23d2019-05-02 14:56:30 -04001819 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1820 if (encoding_str == NULL) {
1821 Py_CLEAR(buf);
1822 goto error;
1823 }
1824
1825 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1826 if (errors_str == NULL) {
1827 Py_CLEAR(buf);
1828 Py_CLEAR(encoding_str);
1829 goto error;
1830 }
1831
1832 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1833 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001834 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001835 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001836 Py_CLEAR(encoding_str);
1837 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001838 if (stream == NULL)
1839 goto error;
1840
1841 if (write_mode)
1842 mode = "w";
1843 else
1844 mode = "r";
1845 text = PyUnicode_FromString(mode);
1846 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1847 goto error;
1848 Py_CLEAR(text);
1849 return stream;
1850
1851error:
1852 Py_XDECREF(buf);
1853 Py_XDECREF(stream);
1854 Py_XDECREF(text);
1855 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001856
Victor Stinner874dbe82015-09-04 17:29:57 +02001857 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1858 /* Issue #24891: the file descriptor was closed after the first
1859 is_valid_fd() check was called. Ignore the OSError and set the
1860 stream to None. */
1861 PyErr_Clear();
1862 Py_RETURN_NONE;
1863 }
1864 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001865}
1866
1867/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001868static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001869init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001870{
1871 PyObject *iomod = NULL, *wrapper;
1872 PyObject *bimod = NULL;
1873 PyObject *m;
1874 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001875 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001876 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001877 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001878 _PyCoreConfig *config = &interp->core_config;
1879
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001880 /* Check that stdin is not a directory
1881 Using shell redirection, you can redirect stdin to a directory,
1882 crashing the Python interpreter. Catch this common mistake here
1883 and output a useful error message. Note that under MS Windows,
1884 the shell already prevents that. */
1885#ifndef MS_WINDOWS
1886 struct _Py_stat_struct sb;
1887 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1888 S_ISDIR(sb.st_mode)) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001889 return _Py_INIT_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001890 }
1891#endif
1892
Nick Coghland6009512014-11-20 21:39:37 +10001893 /* Hack to avoid a nasty recursion issue when Python is invoked
1894 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1895 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1896 goto error;
1897 }
1898 Py_DECREF(m);
1899
1900 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1901 goto error;
1902 }
1903 Py_DECREF(m);
1904
1905 if (!(bimod = PyImport_ImportModule("builtins"))) {
1906 goto error;
1907 }
1908
1909 if (!(iomod = PyImport_ImportModule("io"))) {
1910 goto error;
1911 }
1912 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1913 goto error;
1914 }
1915
1916 /* Set builtins.open */
1917 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1918 Py_DECREF(wrapper);
1919 goto error;
1920 }
1921 Py_DECREF(wrapper);
1922
Nick Coghland6009512014-11-20 21:39:37 +10001923 /* Set sys.stdin */
1924 fd = fileno(stdin);
1925 /* Under some conditions stdin, stdout and stderr may not be connected
1926 * and fileno() may point to an invalid file descriptor. For example
1927 * GUI apps don't have valid standard streams by default.
1928 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001929 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001930 config->stdio_encoding,
1931 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001932 if (std == NULL)
1933 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001934 PySys_SetObject("__stdin__", std);
1935 _PySys_SetObjectId(&PyId_stdin, std);
1936 Py_DECREF(std);
1937
1938 /* Set sys.stdout */
1939 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001940 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001941 config->stdio_encoding,
1942 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001943 if (std == NULL)
1944 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001945 PySys_SetObject("__stdout__", std);
1946 _PySys_SetObjectId(&PyId_stdout, std);
1947 Py_DECREF(std);
1948
1949#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1950 /* Set sys.stderr, replaces the preliminary stderr */
1951 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001952 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001953 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001954 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001955 if (std == NULL)
1956 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001957
1958 /* Same as hack above, pre-import stderr's codec to avoid recursion
1959 when import.c tries to write to stderr in verbose mode. */
1960 encoding_attr = PyObject_GetAttrString(std, "encoding");
1961 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001962 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001963 if (std_encoding != NULL) {
1964 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1965 Py_XDECREF(codec_info);
1966 }
1967 Py_DECREF(encoding_attr);
1968 }
1969 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1970
1971 if (PySys_SetObject("__stderr__", std) < 0) {
1972 Py_DECREF(std);
1973 goto error;
1974 }
1975 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1976 Py_DECREF(std);
1977 goto error;
1978 }
1979 Py_DECREF(std);
1980#endif
1981
Victor Stinnera7368ac2017-11-15 18:11:45 -08001982 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001983
Victor Stinnera7368ac2017-11-15 18:11:45 -08001984error:
1985 res = _Py_INIT_ERR("can't initialize sys standard streams");
1986
1987done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001988 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001989
Nick Coghland6009512014-11-20 21:39:37 +10001990 Py_XDECREF(bimod);
1991 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001992 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001993}
1994
1995
Victor Stinner10dc4842015-03-24 12:01:30 +01001996static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001997_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001998{
Victor Stinner10dc4842015-03-24 12:01:30 +01001999 fputc('\n', stderr);
2000 fflush(stderr);
2001
2002 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01002003 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01002004}
Victor Stinner791da1c2016-03-14 16:53:12 +01002005
2006/* Print the current exception (if an exception is set) with its traceback,
2007 or display the current Python stack.
2008
2009 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2010 called on catastrophic cases.
2011
2012 Return 1 if the traceback was displayed, 0 otherwise. */
2013
2014static int
2015_Py_FatalError_PrintExc(int fd)
2016{
2017 PyObject *ferr, *res;
2018 PyObject *exception, *v, *tb;
2019 int has_tb;
2020
Victor Stinner791da1c2016-03-14 16:53:12 +01002021 PyErr_Fetch(&exception, &v, &tb);
2022 if (exception == NULL) {
2023 /* No current exception */
2024 return 0;
2025 }
2026
2027 ferr = _PySys_GetObjectId(&PyId_stderr);
2028 if (ferr == NULL || ferr == Py_None) {
2029 /* sys.stderr is not set yet or set to None,
2030 no need to try to display the exception */
2031 return 0;
2032 }
2033
2034 PyErr_NormalizeException(&exception, &v, &tb);
2035 if (tb == NULL) {
2036 tb = Py_None;
2037 Py_INCREF(tb);
2038 }
2039 PyException_SetTraceback(v, tb);
2040 if (exception == NULL) {
2041 /* PyErr_NormalizeException() failed */
2042 return 0;
2043 }
2044
2045 has_tb = (tb != Py_None);
2046 PyErr_Display(exception, v, tb);
2047 Py_XDECREF(exception);
2048 Py_XDECREF(v);
2049 Py_XDECREF(tb);
2050
2051 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002052 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002053 if (res == NULL)
2054 PyErr_Clear();
2055 else
2056 Py_DECREF(res);
2057
2058 return has_tb;
2059}
2060
Nick Coghland6009512014-11-20 21:39:37 +10002061/* Print fatal error message and abort */
2062
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002063#ifdef MS_WINDOWS
2064static void
2065fatal_output_debug(const char *msg)
2066{
2067 /* buffer of 256 bytes allocated on the stack */
2068 WCHAR buffer[256 / sizeof(WCHAR)];
2069 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2070 size_t msglen;
2071
2072 OutputDebugStringW(L"Fatal Python error: ");
2073
2074 msglen = strlen(msg);
2075 while (msglen) {
2076 size_t i;
2077
2078 if (buflen > msglen) {
2079 buflen = msglen;
2080 }
2081
2082 /* Convert the message to wchar_t. This uses a simple one-to-one
2083 conversion, assuming that the this error message actually uses
2084 ASCII only. If this ceases to be true, we will have to convert. */
2085 for (i=0; i < buflen; ++i) {
2086 buffer[i] = msg[i];
2087 }
2088 buffer[i] = L'\0';
2089 OutputDebugStringW(buffer);
2090
2091 msg += buflen;
2092 msglen -= buflen;
2093 }
2094 OutputDebugStringW(L"\n");
2095}
2096#endif
2097
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002098static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002099fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002100{
2101 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002102 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002103
2104 if (reentrant) {
2105 /* Py_FatalError() caused a second fatal error.
2106 Example: flush_std_files() raises a recursion error. */
2107 goto exit;
2108 }
2109 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002110
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002111 fprintf(stderr, "Fatal Python error: ");
2112 if (prefix) {
2113 fputs(prefix, stderr);
2114 fputs(": ", stderr);
2115 }
2116 if (msg) {
2117 fputs(msg, stderr);
2118 }
2119 else {
2120 fprintf(stderr, "<message not set>");
2121 }
2122 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002123 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002124
Victor Stinner3a228ab2018-11-01 00:26:41 +01002125 /* Check if the current thread has a Python thread state
2126 and holds the GIL */
2127 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2128 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002129 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002130 if (tss_tstate != tstate) {
2131 /* The Python thread does not hold the GIL */
2132 tss_tstate = NULL;
2133 }
2134 }
2135 else {
2136 /* Py_FatalError() has been called from a C thread
2137 which has no Python thread state. */
2138 }
2139 int has_tstate_and_gil = (tss_tstate != NULL);
2140
2141 if (has_tstate_and_gil) {
2142 /* If an exception is set, print the exception with its traceback */
2143 if (!_Py_FatalError_PrintExc(fd)) {
2144 /* No exception is set, or an exception is set without traceback */
2145 _Py_FatalError_DumpTracebacks(fd);
2146 }
2147 }
2148 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002149 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002150 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002151
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002152 /* The main purpose of faulthandler is to display the traceback.
2153 This function already did its best to display a traceback.
2154 Disable faulthandler to prevent writing a second traceback
2155 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002156 _PyFaulthandler_Fini();
2157
Victor Stinner791da1c2016-03-14 16:53:12 +01002158 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002159 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002160 /* Flush sys.stdout and sys.stderr */
2161 flush_std_files();
2162 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002163
Nick Coghland6009512014-11-20 21:39:37 +10002164#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002165 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002166#endif /* MS_WINDOWS */
2167
2168exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002169 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002170#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002171 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002172#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002173 abort();
2174 }
2175 else {
2176 exit(status);
2177 }
2178}
2179
Victor Stinner19760862017-12-20 01:41:59 +01002180void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002181Py_FatalError(const char *msg)
2182{
2183 fatal_error(NULL, msg, -1);
2184}
2185
Victor Stinner19760862017-12-20 01:41:59 +01002186void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002187_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002188{
Victor Stinnerdb719752019-05-01 05:35:33 +02002189 if (_Py_INIT_IS_EXIT(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01002190 exit(err.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002191 }
2192 else if (_Py_INIT_IS_ERROR(err)) {
2193 fatal_error(err._func, err.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002194 }
2195 else {
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002196 Py_FatalError("_Py_ExitInitError() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002197 }
Nick Coghland6009512014-11-20 21:39:37 +10002198}
2199
2200/* Clean up and exit */
2201
Victor Stinnerd7292b52016-06-17 12:29:00 +02002202# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002203
Nick Coghland6009512014-11-20 21:39:37 +10002204/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002205void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002206{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002207 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002208
Antoine Pitroufc5db952017-12-13 02:29:07 +01002209 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002210 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2211
2212 is->pyexitfunc = func;
2213 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002214}
2215
2216static void
Marcel Plch776407f2017-12-20 11:17:58 +01002217call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002218{
Marcel Plch776407f2017-12-20 11:17:58 +01002219 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002220 return;
2221
Marcel Plch776407f2017-12-20 11:17:58 +01002222 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002223 PyErr_Clear();
2224}
2225
2226/* Wait until threading._shutdown completes, provided
2227 the threading module was imported in the first place.
2228 The shutdown routine will wait until all non-daemon
2229 "threading" threads have completed. */
2230static void
2231wait_for_thread_shutdown(void)
2232{
Nick Coghland6009512014-11-20 21:39:37 +10002233 _Py_IDENTIFIER(_shutdown);
2234 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002235 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002236 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002237 if (PyErr_Occurred()) {
2238 PyErr_WriteUnraisable(NULL);
2239 }
2240 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002241 return;
2242 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002243 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002244 if (result == NULL) {
2245 PyErr_WriteUnraisable(threading);
2246 }
2247 else {
2248 Py_DECREF(result);
2249 }
2250 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002251}
2252
2253#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002254int Py_AtExit(void (*func)(void))
2255{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002256 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002257 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002258 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002259 return 0;
2260}
2261
2262static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002263call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002264{
Victor Stinner8e91c242019-04-24 17:24:01 +02002265 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002266 /* pop last function from the list */
2267 runtime->nexitfuncs--;
2268 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2269 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2270
2271 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002272 }
Nick Coghland6009512014-11-20 21:39:37 +10002273
2274 fflush(stdout);
2275 fflush(stderr);
2276}
2277
Victor Stinnercfc88312018-08-01 16:41:25 +02002278void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002279Py_Exit(int sts)
2280{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002281 if (Py_FinalizeEx() < 0) {
2282 sts = 120;
2283 }
Nick Coghland6009512014-11-20 21:39:37 +10002284
2285 exit(sts);
2286}
2287
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002288static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002289init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002290{
2291#ifdef SIGPIPE
2292 PyOS_setsig(SIGPIPE, SIG_IGN);
2293#endif
2294#ifdef SIGXFZ
2295 PyOS_setsig(SIGXFZ, SIG_IGN);
2296#endif
2297#ifdef SIGXFSZ
2298 PyOS_setsig(SIGXFSZ, SIG_IGN);
2299#endif
2300 PyOS_InitInterrupts(); /* May imply initsignal() */
2301 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002302 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002303 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002304 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002305}
2306
2307
2308/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2309 *
2310 * All of the code in this function must only use async-signal-safe functions,
2311 * listed at `man 7 signal` or
2312 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2313 */
2314void
2315_Py_RestoreSignals(void)
2316{
2317#ifdef SIGPIPE
2318 PyOS_setsig(SIGPIPE, SIG_DFL);
2319#endif
2320#ifdef SIGXFZ
2321 PyOS_setsig(SIGXFZ, SIG_DFL);
2322#endif
2323#ifdef SIGXFSZ
2324 PyOS_setsig(SIGXFSZ, SIG_DFL);
2325#endif
2326}
2327
2328
2329/*
2330 * The file descriptor fd is considered ``interactive'' if either
2331 * a) isatty(fd) is TRUE, or
2332 * b) the -i flag was given, and the filename associated with
2333 * the descriptor is NULL or "<stdin>" or "???".
2334 */
2335int
2336Py_FdIsInteractive(FILE *fp, const char *filename)
2337{
2338 if (isatty((int)fileno(fp)))
2339 return 1;
2340 if (!Py_InteractiveFlag)
2341 return 0;
2342 return (filename == NULL) ||
2343 (strcmp(filename, "<stdin>") == 0) ||
2344 (strcmp(filename, "???") == 0);
2345}
2346
2347
Nick Coghland6009512014-11-20 21:39:37 +10002348/* Wrappers around sigaction() or signal(). */
2349
2350PyOS_sighandler_t
2351PyOS_getsig(int sig)
2352{
2353#ifdef HAVE_SIGACTION
2354 struct sigaction context;
2355 if (sigaction(sig, NULL, &context) == -1)
2356 return SIG_ERR;
2357 return context.sa_handler;
2358#else
2359 PyOS_sighandler_t handler;
2360/* Special signal handling for the secure CRT in Visual Studio 2005 */
2361#if defined(_MSC_VER) && _MSC_VER >= 1400
2362 switch (sig) {
2363 /* Only these signals are valid */
2364 case SIGINT:
2365 case SIGILL:
2366 case SIGFPE:
2367 case SIGSEGV:
2368 case SIGTERM:
2369 case SIGBREAK:
2370 case SIGABRT:
2371 break;
2372 /* Don't call signal() with other values or it will assert */
2373 default:
2374 return SIG_ERR;
2375 }
2376#endif /* _MSC_VER && _MSC_VER >= 1400 */
2377 handler = signal(sig, SIG_IGN);
2378 if (handler != SIG_ERR)
2379 signal(sig, handler);
2380 return handler;
2381#endif
2382}
2383
2384/*
2385 * All of the code in this function must only use async-signal-safe functions,
2386 * listed at `man 7 signal` or
2387 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2388 */
2389PyOS_sighandler_t
2390PyOS_setsig(int sig, PyOS_sighandler_t handler)
2391{
2392#ifdef HAVE_SIGACTION
2393 /* Some code in Modules/signalmodule.c depends on sigaction() being
2394 * used here if HAVE_SIGACTION is defined. Fix that if this code
2395 * changes to invalidate that assumption.
2396 */
2397 struct sigaction context, ocontext;
2398 context.sa_handler = handler;
2399 sigemptyset(&context.sa_mask);
2400 context.sa_flags = 0;
2401 if (sigaction(sig, &context, &ocontext) == -1)
2402 return SIG_ERR;
2403 return ocontext.sa_handler;
2404#else
2405 PyOS_sighandler_t oldhandler;
2406 oldhandler = signal(sig, handler);
2407#ifdef HAVE_SIGINTERRUPT
2408 siginterrupt(sig, 1);
2409#endif
2410 return oldhandler;
2411#endif
2412}
2413
2414#ifdef __cplusplus
2415}
2416#endif