blob: 54e8ce2b1557af0a98e91ba588a56771a4a23a14 [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 Stinner331a6a52019-05-27 16:39:22 +02009#include "pycore_initconfig.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 Stinner331a6a52019-05-27 16:39:22 +020063static PyStatus add_main_module(PyInterpreterState *interp);
64static PyStatus init_import_size(void);
65static PyStatus init_sys_streams(PyInterpreterState *interp);
66static PyStatus 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 Stinner331a6a52019-05-27 16:39:22 +020075PyStatus
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 Stinner331a6a52019-05-27 16:39:22 +020085 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080086 }
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 Stinner331a6a52019-05-27 16:39:22 +0200148static PyStatus
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 Stinner331a6a52019-05-27 16:39:22 +0200154 int verbose = interp->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 Stinner331a6a52019-05-27 16:39:22 +0200158 return _PyStatus_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 Stinner331a6a52019-05-27 16:39:22 +0200165 return _PyStatus_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 Stinner331a6a52019-05-27 16:39:22 +0200172 return _PyStatus_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 Stinner331a6a52019-05-27 16:39:22 +0200178 return _PyStatus_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 Stinner331a6a52019-05-27 16:39:22 +0200184 return _PyStatus_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 Stinner331a6a52019-05-27 16:39:22 +0200191 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000192 }
193 Py_DECREF(value);
194 Py_DECREF(impmod);
195
Victor Stinner331a6a52019-05-27 16:39:22 +0200196 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000197}
198
Victor Stinner331a6a52019-05-27 16:39:22 +0200199static PyStatus
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 Stinner331a6a52019-05-27 16:39:22 +0200207 return _PyStatus_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 Stinner331a6a52019-05-27 16:39:22 +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 Stinner331a6a52019-05-27 16:39:22 +0200440 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 Stinner331a6a52019-05-27 16:39:22 +0200449static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200450pyinit_core_reconfigure(_PyRuntimeState *runtime,
451 PyInterpreterState **interp_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200452 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200453{
Victor Stinner331a6a52019-05-27 16:39:22 +0200454 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100455 PyThreadState *tstate = _PyThreadState_GET();
456 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200457 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100458 }
459
460 PyInterpreterState *interp = tstate->interp;
461 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200462 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100463 }
464 *interp_p = interp;
465
Victor Stinner331a6a52019-05-27 16:39:22 +0200466 _PyConfig_Write(config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200467
Victor Stinner331a6a52019-05-27 16:39:22 +0200468 status = _PyConfig_Copy(&interp->config, config);
469 if (_PyStatus_EXCEPTION(status)) {
470 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200471 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200472 config = &interp->config;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200473
Victor Stinner331a6a52019-05-27 16:39:22 +0200474 if (config->_install_importlib) {
475 status = _PyConfig_SetPathConfig(config);
476 if (_PyStatus_EXCEPTION(status)) {
477 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200478 }
479 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200480 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200481}
482
483
Victor Stinner331a6a52019-05-27 16:39:22 +0200484static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200485pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200486 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000487{
Victor Stinner43125222019-04-24 18:23:53 +0200488 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200489 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200490 }
Victor Stinnerda273412017-12-15 01:46:02 +0100491
Victor Stinner331a6a52019-05-27 16:39:22 +0200492 _PyConfig_Write(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 Stinner331a6a52019-05-27 16:39:22 +0200505 PyStatus status = _Py_HashRandomization_Init(config);
506 if (_PyStatus_EXCEPTION(status)) {
507 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800508 }
509
Victor Stinner331a6a52019-05-27 16:39:22 +0200510 status = _PyInterpreterState_Enable(runtime);
511 if (_PyStatus_EXCEPTION(status)) {
512 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800513 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200514 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100515}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800516
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517
Victor Stinner331a6a52019-05-27 16:39:22 +0200518static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200519pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200520 const PyConfig *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 Stinner331a6a52019-05-27 16:39:22 +0200525 return _PyStatus_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 Stinner331a6a52019-05-27 16:39:22 +0200529 PyStatus status = _PyConfig_Copy(&interp->config, config);
530 if (_PyStatus_EXCEPTION(status)) {
531 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100532 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200533 config = &interp->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 Stinner331a6a52019-05-27 16:39:22 +0200537 return _PyStatus_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 Stinner0fd2c302019-06-04 03:15:09 +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 Stinner331a6a52019-05-27 16:39:22 +0200553 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100554}
Nick Coghland6009512014-11-20 21:39:37 +1000555
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100556
Victor Stinner331a6a52019-05-27 16:39:22 +0200557static PyStatus
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100558pycore_init_types(void)
559{
Victor Stinner331a6a52019-05-27 16:39:22 +0200560 PyStatus status = _PyTypes_Init();
561 if (_PyStatus_EXCEPTION(status)) {
562 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100563 }
564
Victor Stinner331a6a52019-05-27 16:39:22 +0200565 status = _PyUnicode_Init();
566 if (_PyStatus_EXCEPTION(status)) {
567 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100568 }
569
570 if (_PyStructSequence_Init() < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200571 return _PyStatus_ERR("can't initialize structseq");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100572 }
573
574 if (!_PyLong_Init()) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200575 return _PyStatus_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100576 }
Nick Coghland6009512014-11-20 21:39:37 +1000577
Victor Stinner331a6a52019-05-27 16:39:22 +0200578 status = _PyExc_Init();
579 if (_PyStatus_EXCEPTION(status)) {
580 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100581 }
582
583 if (!_PyFloat_Init()) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200584 return _PyStatus_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()) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200588 return _PyStatus_ERR("can't init context");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100589 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200590
Victor Stinner331a6a52019-05-27 16:39:22 +0200591 status = _PyErr_Init();
592 if (_PyStatus_EXCEPTION(status)) {
593 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200594 }
595
Victor Stinner331a6a52019-05-27 16:39:22 +0200596 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100597}
598
599
Victor Stinner331a6a52019-05-27 16:39:22 +0200600static PyStatus
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100601pycore_init_builtins(PyInterpreterState *interp)
602{
603 PyObject *bimod = _PyBuiltin_Init();
604 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200605 return _PyStatus_ERR("can't initialize builtins modules");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100606 }
607 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
608
609 interp->builtins = PyModule_GetDict(bimod);
610 if (interp->builtins == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200611 return _PyStatus_ERR("can't initialize builtins dict");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100612 }
613 Py_INCREF(interp->builtins);
614
Victor Stinner331a6a52019-05-27 16:39:22 +0200615 PyStatus status = _PyBuiltins_AddExceptions(bimod);
616 if (_PyStatus_EXCEPTION(status)) {
617 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100618 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200619 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100620}
621
622
Victor Stinner331a6a52019-05-27 16:39:22 +0200623static PyStatus
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100624pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
625{
Victor Stinner331a6a52019-05-27 16:39:22 +0200626 PyStatus status = _PyImport_Init(interp);
627 if (_PyStatus_EXCEPTION(status)) {
628 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800629 }
Nick Coghland6009512014-11-20 21:39:37 +1000630
Victor Stinner331a6a52019-05-27 16:39:22 +0200631 status = _PyImportHooks_Init();
632 if (_PyStatus_EXCEPTION(status)) {
633 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800634 }
Nick Coghland6009512014-11-20 21:39:37 +1000635
636 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100637 if (_PyWarnings_Init() == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200638 return _PyStatus_ERR("can't initialize warnings");
Victor Stinner1f151112017-11-23 10:43:14 +0100639 }
Nick Coghland6009512014-11-20 21:39:37 +1000640
Victor Stinner331a6a52019-05-27 16:39:22 +0200641 if (interp->config._install_importlib) {
642 status = _PyConfig_SetPathConfig(&interp->config);
643 if (_PyStatus_EXCEPTION(status)) {
644 return status;
Victor Stinnerb1147e42018-07-21 02:06:16 +0200645 }
646 }
647
Eric Snow1abcf672017-05-23 21:46:51 -0700648 /* This call sets up builtin and frozen import support */
Victor Stinner331a6a52019-05-27 16:39:22 +0200649 if (interp->config._install_importlib) {
650 status = init_importlib(interp, sysmod);
651 if (_PyStatus_EXCEPTION(status)) {
652 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800653 }
Eric Snow1abcf672017-05-23 21:46:51 -0700654 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200655 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100656}
657
658
Victor Stinner331a6a52019-05-27 16:39:22 +0200659static PyStatus
660pyinit_config(_PyRuntimeState *runtime,
661 PyInterpreterState **interp_p,
662 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100663{
664 PyInterpreterState *interp;
665
Victor Stinner331a6a52019-05-27 16:39:22 +0200666 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100667
Victor Stinner331a6a52019-05-27 16:39:22 +0200668 PyStatus status = pycore_init_runtime(runtime, config);
669 if (_PyStatus_EXCEPTION(status)) {
670 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100671 }
672
Victor Stinner331a6a52019-05-27 16:39:22 +0200673 status = pycore_create_interpreter(runtime, config, &interp);
674 if (_PyStatus_EXCEPTION(status)) {
675 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100676 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200677 config = &interp->config;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100678 *interp_p = interp;
679
Victor Stinner331a6a52019-05-27 16:39:22 +0200680 status = pycore_init_types();
681 if (_PyStatus_EXCEPTION(status)) {
682 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100683 }
684
685 PyObject *sysmod;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200686 status = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200687 if (_PyStatus_EXCEPTION(status)) {
688 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100689 }
690
Victor Stinner331a6a52019-05-27 16:39:22 +0200691 status = pycore_init_builtins(interp);
692 if (_PyStatus_EXCEPTION(status)) {
693 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100694 }
695
Victor Stinner331a6a52019-05-27 16:39:22 +0200696 status = pycore_init_import_warnings(interp, sysmod);
697 if (_PyStatus_EXCEPTION(status)) {
698 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100699 }
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 Stinner331a6a52019-05-27 16:39:22 +0200703 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700704}
705
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100706
Victor Stinner331a6a52019-05-27 16:39:22 +0200707PyStatus
708_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100709{
Victor Stinner331a6a52019-05-27 16:39:22 +0200710 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100711
Victor Stinner6d1c4672019-05-20 11:02:00 +0200712 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200713 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200714 }
715
Victor Stinner331a6a52019-05-27 16:39:22 +0200716 status = _PyRuntime_Initialize();
717 if (_PyStatus_EXCEPTION(status)) {
718 return status;
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 Stinner331a6a52019-05-27 16:39:22 +0200724 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100725 }
726
Victor Stinner331a6a52019-05-27 16:39:22 +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 Stinner331a6a52019-05-27 16:39:22 +0200730 status = _PyPreConfig_Read(&config, args);
731 if (_PyStatus_EXCEPTION(status)) {
732 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100733 }
734
Victor Stinner331a6a52019-05-27 16:39:22 +0200735 status = _PyPreConfig_Write(&config);
736 if (_PyStatus_EXCEPTION(status)) {
737 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100738 }
739
Victor Stinner43125222019-04-24 18:23:53 +0200740 runtime->pre_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200741 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100742}
743
Victor Stinner70005ac2019-05-02 15:25:34 -0400744
Victor Stinner331a6a52019-05-27 16:39:22 +0200745PyStatus
746Py_PreInitializeFromBytesArgs(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
Victor Stinner331a6a52019-05-27 16:39:22 +0200753PyStatus
754Py_PreInitializeFromArgs(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
Victor Stinner331a6a52019-05-27 16:39:22 +0200761PyStatus
762Py_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
Victor Stinner331a6a52019-05-27 16:39:22 +0200768PyStatus
769_Py_PreInitializeFromConfig(const PyConfig *config,
770 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100771{
Victor Stinner331a6a52019-05-27 16:39:22 +0200772 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200773
Victor Stinner331a6a52019-05-27 16:39:22 +0200774 PyStatus status = _PyRuntime_Initialize();
775 if (_PyStatus_EXCEPTION(status)) {
776 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200777 }
778 _PyRuntimeState *runtime = &_PyRuntime;
779
780 if (runtime->pre_initialized) {
781 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200782 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400783 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200784
Victor Stinner331a6a52019-05-27 16:39:22 +0200785 PyPreConfig preconfig;
786 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200787
Victor Stinner331a6a52019-05-27 16:39:22 +0200788 if (!config->parse_argv) {
789 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200790 }
791 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200792 _PyArgv config_args = {
793 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200794 .argc = config->argv.length,
795 .wchar_argv = config->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
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100804/* Begin interpreter initialization
805 *
806 * On return, the first thread and interpreter state have been created,
807 * but the compiler, signal handling, multithreading and
808 * multiple interpreter support, and codec infrastructure are not yet
809 * available.
810 *
811 * The import system will support builtin and frozen modules only.
812 * The only supported io is writing to sys.stderr
813 *
814 * If any operation invoked by this function fails, a fatal error is
815 * issued and the function does not return.
816 *
817 * Any code invoked from this function should *not* assume it has access
818 * to the Python C API (unless the API is explicitly listed as being
819 * safe to call without calling Py_Initialize first)
820 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200821static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200822pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200823 const PyConfig *src_config,
Victor Stinner5edcf262019-05-23 00:57:57 +0200824 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200825{
Victor Stinner331a6a52019-05-27 16:39:22 +0200826 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200827
Victor Stinner331a6a52019-05-27 16:39:22 +0200828 status = _Py_PreInitializeFromConfig(src_config, NULL);
829 if (_PyStatus_EXCEPTION(status)) {
830 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200831 }
832
Victor Stinner331a6a52019-05-27 16:39:22 +0200833 PyConfig config;
834 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200835
Victor Stinner331a6a52019-05-27 16:39:22 +0200836 status = _PyConfig_Copy(&config, src_config);
837 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200838 goto done;
839 }
840
Victor Stinner331a6a52019-05-27 16:39:22 +0200841 status = PyConfig_Read(&config);
842 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200843 goto done;
844 }
845
846 if (!runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200847 status = pyinit_config(runtime, interp_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200848 }
849 else {
Victor Stinner331a6a52019-05-27 16:39:22 +0200850 status = pyinit_core_reconfigure(runtime, interp_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200851 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200852 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200853 goto done;
854 }
855
856done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 PyConfig_Clear(&config);
858 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200859}
860
Victor Stinner5ac27a52019-03-27 13:40:14 +0100861
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200862/* Py_Initialize() has already been called: update the main interpreter
863 configuration. Example of bpo-34008: Py_Main() called after
864 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200865static PyStatus
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100866_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200867{
Victor Stinner331a6a52019-05-27 16:39:22 +0200868 PyConfig *config = &interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100869
Victor Stinner331a6a52019-05-27 16:39:22 +0200870 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100871 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200872 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100873 }
874
875 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
876 Py_DECREF(argv);
877 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200878 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200879 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200880 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200881}
882
Eric Snowc7ec9982017-05-23 23:00:52 -0700883/* Update interpreter state based on supplied configuration settings
884 *
885 * After calling this function, most of the restrictions on the interpreter
886 * are lifted. The only remaining incomplete settings are those related
887 * to the main module (sys.argv[0], __main__ metadata)
888 *
889 * Calling this when the interpreter is not initializing, is already
890 * initialized or without a valid current thread state is a fatal error.
891 * Other errors should be reported as normal Python exceptions with a
892 * non-zero return code.
893 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200894static PyStatus
Victor Stinner0fd2c302019-06-04 03:15:09 +0200895pyinit_main(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700896{
Victor Stinner43125222019-04-24 18:23:53 +0200897 if (!runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200898 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700899 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700900
Victor Stinner1dc6e392018-07-25 02:49:17 +0200901 /* Configure the main interpreter */
Victor Stinner838f2642019-06-13 22:41:23 +0200902 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner331a6a52019-05-27 16:39:22 +0200903 PyConfig *config = &interp->config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700904
Victor Stinner43125222019-04-24 18:23:53 +0200905 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100906 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200907 }
908
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 if (!config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700910 /* Special mode for freeze_importlib: run with no import system
911 *
912 * This means anything which needs support from extension modules
913 * or pure Python code in the standard library won't work.
914 */
Victor Stinner43125222019-04-24 18:23:53 +0200915 runtime->initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200916 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700917 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100918
Victor Stinner33c377e2017-12-05 15:12:41 +0100919 if (_PyTime_Init() < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200920 return _PyStatus_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100921 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200922
Victor Stinner838f2642019-06-13 22:41:23 +0200923 if (_PySys_InitMain(runtime, tstate) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200924 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100925 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800926
Victor Stinner331a6a52019-05-27 16:39:22 +0200927 PyStatus status = init_importlib_external(interp);
928 if (_PyStatus_EXCEPTION(status)) {
929 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800930 }
Nick Coghland6009512014-11-20 21:39:37 +1000931
932 /* initialize the faulthandler module */
Victor Stinner331a6a52019-05-27 16:39:22 +0200933 status = _PyFaulthandler_Init(config->faulthandler);
934 if (_PyStatus_EXCEPTION(status)) {
935 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800936 }
Nick Coghland6009512014-11-20 21:39:37 +1000937
Victor Stinner331a6a52019-05-27 16:39:22 +0200938 status = _PyUnicode_InitEncodings(interp);
939 if (_PyStatus_EXCEPTION(status)) {
940 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800941 }
Nick Coghland6009512014-11-20 21:39:37 +1000942
Victor Stinner331a6a52019-05-27 16:39:22 +0200943 if (config->install_signal_handlers) {
944 status = init_signals();
945 if (_PyStatus_EXCEPTION(status)) {
946 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800947 }
948 }
Nick Coghland6009512014-11-20 21:39:37 +1000949
Victor Stinner331a6a52019-05-27 16:39:22 +0200950 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
951 return _PyStatus_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200952 }
Nick Coghland6009512014-11-20 21:39:37 +1000953
Victor Stinner331a6a52019-05-27 16:39:22 +0200954 status = add_main_module(interp);
955 if (_PyStatus_EXCEPTION(status)) {
956 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800957 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800958
Victor Stinner331a6a52019-05-27 16:39:22 +0200959 status = init_sys_streams(interp);
960 if (_PyStatus_EXCEPTION(status)) {
961 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800962 }
Nick Coghland6009512014-11-20 21:39:37 +1000963
964 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100965 PyObject *warnoptions = PySys_GetObject("warnoptions");
966 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100967 {
Nick Coghland6009512014-11-20 21:39:37 +1000968 PyObject *warnings_module = PyImport_ImportModule("warnings");
969 if (warnings_module == NULL) {
970 fprintf(stderr, "'import warnings' failed; traceback:\n");
971 PyErr_Print();
972 }
973 Py_XDECREF(warnings_module);
974 }
975
Victor Stinner43125222019-04-24 18:23:53 +0200976 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700977
Victor Stinner331a6a52019-05-27 16:39:22 +0200978 if (config->site_import) {
979 status = init_import_size(); /* Module site */
980 if (_PyStatus_EXCEPTION(status)) {
981 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800982 }
983 }
Victor Stinnercf215042018-08-29 22:56:06 +0200984
985#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200986 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200987#endif
988
Victor Stinner331a6a52019-05-27 16:39:22 +0200989 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000990}
991
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200992
Victor Stinner331a6a52019-05-27 16:39:22 +0200993PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200994_Py_InitializeMain(void)
995{
Victor Stinner331a6a52019-05-27 16:39:22 +0200996 PyStatus status = _PyRuntime_Initialize();
997 if (_PyStatus_EXCEPTION(status)) {
998 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200999 }
1000 _PyRuntimeState *runtime = &_PyRuntime;
1001 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
1002
Victor Stinner0fd2c302019-06-04 03:15:09 +02001003 return pyinit_main(runtime, interp);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001004}
1005
1006
Victor Stinner331a6a52019-05-27 16:39:22 +02001007PyStatus
1008Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001009{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001010 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001011 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001012 }
1013
Victor Stinner331a6a52019-05-27 16:39:22 +02001014 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001015
Victor Stinner331a6a52019-05-27 16:39:22 +02001016 status = _PyRuntime_Initialize();
1017 if (_PyStatus_EXCEPTION(status)) {
1018 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001019 }
1020 _PyRuntimeState *runtime = &_PyRuntime;
1021
1022 PyInterpreterState *interp = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001023 status = pyinit_core(runtime, config, &interp);
1024 if (_PyStatus_EXCEPTION(status)) {
1025 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001026 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001027 config = &interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001028
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001029 if (config->_init_main) {
Victor Stinner0fd2c302019-06-04 03:15:09 +02001030 status = pyinit_main(runtime, interp);
Victor Stinner331a6a52019-05-27 16:39:22 +02001031 if (_PyStatus_EXCEPTION(status)) {
1032 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001033 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001034 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001035
Victor Stinner331a6a52019-05-27 16:39:22 +02001036 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001037}
1038
1039
Eric Snow1abcf672017-05-23 21:46:51 -07001040void
Nick Coghland6009512014-11-20 21:39:37 +10001041Py_InitializeEx(int install_sigs)
1042{
Victor Stinner331a6a52019-05-27 16:39:22 +02001043 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001044
Victor Stinner331a6a52019-05-27 16:39:22 +02001045 status = _PyRuntime_Initialize();
1046 if (_PyStatus_EXCEPTION(status)) {
1047 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001048 }
1049 _PyRuntimeState *runtime = &_PyRuntime;
1050
1051 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001052 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1053 return;
1054 }
1055
Victor Stinner331a6a52019-05-27 16:39:22 +02001056 PyConfig config;
1057 _PyConfig_InitCompatConfig(&config);
Victor Stinner1dc6e392018-07-25 02:49:17 +02001058 config.install_signal_handlers = install_sigs;
1059
Victor Stinner331a6a52019-05-27 16:39:22 +02001060 status = Py_InitializeFromConfig(&config);
1061 if (_PyStatus_EXCEPTION(status)) {
1062 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001063 }
Nick Coghland6009512014-11-20 21:39:37 +10001064}
1065
1066void
1067Py_Initialize(void)
1068{
1069 Py_InitializeEx(1);
1070}
1071
1072
1073#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001074extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001075#endif
1076
1077/* Flush stdout and stderr */
1078
1079static int
1080file_is_closed(PyObject *fobj)
1081{
1082 int r;
1083 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1084 if (tmp == NULL) {
1085 PyErr_Clear();
1086 return 0;
1087 }
1088 r = PyObject_IsTrue(tmp);
1089 Py_DECREF(tmp);
1090 if (r < 0)
1091 PyErr_Clear();
1092 return r > 0;
1093}
1094
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001095static int
Nick Coghland6009512014-11-20 21:39:37 +10001096flush_std_files(void)
1097{
1098 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1099 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1100 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001101 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001102
1103 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001104 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001105 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001106 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001107 status = -1;
1108 }
Nick Coghland6009512014-11-20 21:39:37 +10001109 else
1110 Py_DECREF(tmp);
1111 }
1112
1113 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001114 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001115 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001116 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001117 status = -1;
1118 }
Nick Coghland6009512014-11-20 21:39:37 +10001119 else
1120 Py_DECREF(tmp);
1121 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001122
1123 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001124}
1125
1126/* Undo the effect of Py_Initialize().
1127
1128 Beware: if multiple interpreter and/or thread states exist, these
1129 are not wiped out; only the current thread and interpreter state
1130 are deleted. But since everything else is deleted, those other
1131 interpreter and thread states should no longer be used.
1132
1133 (XXX We should do better, e.g. wipe out all interpreters and
1134 threads.)
1135
1136 Locking: as above.
1137
1138*/
1139
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001140int
1141Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001142{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001143 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001144
Victor Stinner8e91c242019-04-24 17:24:01 +02001145 _PyRuntimeState *runtime = &_PyRuntime;
1146 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001147 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001148 }
Nick Coghland6009512014-11-20 21:39:37 +10001149
Eric Snow842a2f02019-03-15 15:47:51 -06001150 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001151 wait_for_thread_shutdown();
1152
Eric Snow842a2f02019-03-15 15:47:51 -06001153 // Make any remaining pending calls.
Victor Stinnere225beb2019-06-03 18:14:24 +02001154 _Py_FinishPendingCalls(runtime);
1155
1156 /* Get current thread state and interpreter pointer */
1157 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1158 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001159
Nick Coghland6009512014-11-20 21:39:37 +10001160 /* The interpreter is still entirely intact at this point, and the
1161 * exit funcs may be relying on that. In particular, if some thread
1162 * or exit func is still waiting to do an import, the import machinery
1163 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001164 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001165 * Note that Threading.py uses an exit func to do a join on all the
1166 * threads created thru it, so this also protects pending imports in
1167 * the threads created via Threading.
1168 */
Nick Coghland6009512014-11-20 21:39:37 +10001169
Marcel Plch776407f2017-12-20 11:17:58 +01001170 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001171
Victor Stinnerda273412017-12-15 01:46:02 +01001172 /* Copy the core config, PyInterpreterState_Delete() free
1173 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001174#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001175 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001176#endif
1177#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001178 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001179#endif
1180#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001181 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001182#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001183
Nick Coghland6009512014-11-20 21:39:37 +10001184 /* Remaining threads (e.g. daemon threads) will automatically exit
1185 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001186 runtime->finalizing = tstate;
1187 runtime->initialized = 0;
1188 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001189
Victor Stinnere0deff32015-03-24 13:46:18 +01001190 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001191 if (flush_std_files() < 0) {
1192 status = -1;
1193 }
Nick Coghland6009512014-11-20 21:39:37 +10001194
1195 /* Disable signal handling */
1196 PyOS_FiniInterrupts();
1197
1198 /* Collect garbage. This may call finalizers; it's nice to call these
1199 * before all modules are destroyed.
1200 * XXX If a __del__ or weakref callback is triggered here, and tries to
1201 * XXX import a module, bad things can happen, because Python no
1202 * XXX longer believes it's initialized.
1203 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1204 * XXX is easy to provoke that way. I've also seen, e.g.,
1205 * XXX Exception exceptions.ImportError: 'No module named sha'
1206 * XXX in <function callback at 0x008F5718> ignored
1207 * XXX but I'm unclear on exactly how that one happens. In any case,
1208 * XXX I haven't seen a real-life report of either of these.
1209 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001210 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001211#ifdef COUNT_ALLOCS
1212 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1213 each collection might release some types from the type
1214 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001215 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001216 /* nothing */;
1217#endif
Eric Snowdae02762017-09-14 00:35:58 -07001218
Steve Dowerb82e17e2019-05-23 08:45:22 -07001219 /* Clear all loghooks */
1220 /* We want minimal exposure of this function, so define the extern
1221 * here. The linker should discover the correct function without
1222 * exporting a symbol. */
1223 extern void _PySys_ClearAuditHooks(void);
1224 _PySys_ClearAuditHooks();
1225
Nick Coghland6009512014-11-20 21:39:37 +10001226 /* Destroy all modules */
1227 PyImport_Cleanup();
1228
Inada Naoki91234a12019-06-03 21:30:58 +09001229 /* Print debug stats if any */
1230 _PyEval_Fini();
1231
Victor Stinnere0deff32015-03-24 13:46:18 +01001232 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
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 /* Collect final garbage. This disposes of cycles created by
1238 * class definitions, for example.
1239 * XXX This is disabled because it caused too many problems. If
1240 * XXX a __del__ or weakref callback triggers here, Python code has
1241 * XXX a hard time running, because even the sys module has been
1242 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1243 * XXX One symptom is a sequence of information-free messages
1244 * XXX coming from threads (if a __del__ or callback is invoked,
1245 * XXX other threads can execute too, and any exception they encounter
1246 * XXX triggers a comedy of errors as subsystem after subsystem
1247 * XXX fails to find what it *expects* to find in sys to help report
1248 * XXX the exception and consequent unexpected failures). I've also
1249 * XXX seen segfaults then, after adding print statements to the
1250 * XXX Python code getting called.
1251 */
1252#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001253 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001254#endif
1255
1256 /* Disable tracemalloc after all Python objects have been destroyed,
1257 so it is possible to use tracemalloc in objects destructor. */
1258 _PyTraceMalloc_Fini();
1259
1260 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1261 _PyImport_Fini();
1262
1263 /* Cleanup typeobject.c's internal caches. */
1264 _PyType_Fini();
1265
1266 /* unload faulthandler module */
1267 _PyFaulthandler_Fini();
1268
1269 /* Debugging stuff */
1270#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001271 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001272#endif
1273 /* dump hash stats */
1274 _PyHash_Fini();
1275
Eric Snowdae02762017-09-14 00:35:58 -07001276#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001277 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001278 _PyDebug_PrintTotalRefs();
1279 }
Eric Snowdae02762017-09-14 00:35:58 -07001280#endif
Nick Coghland6009512014-11-20 21:39:37 +10001281
1282#ifdef Py_TRACE_REFS
1283 /* Display all objects still alive -- this can invoke arbitrary
1284 * __repr__ overrides, so requires a mostly-intact interpreter.
1285 * Alas, a lot of stuff may still be alive now that will be cleaned
1286 * up later.
1287 */
Victor Stinnerda273412017-12-15 01:46:02 +01001288 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001289 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001290 }
Nick Coghland6009512014-11-20 21:39:37 +10001291#endif /* Py_TRACE_REFS */
1292
1293 /* Clear interpreter state and all thread states. */
1294 PyInterpreterState_Clear(interp);
1295
1296 /* Now we decref the exception classes. After this point nothing
1297 can raise an exception. That's okay, because each Fini() method
1298 below has been checked to make sure no exceptions are ever
1299 raised.
1300 */
1301
1302 _PyExc_Fini();
1303
1304 /* Sundry finalizers */
1305 PyMethod_Fini();
1306 PyFrame_Fini();
1307 PyCFunction_Fini();
1308 PyTuple_Fini();
1309 PyList_Fini();
1310 PySet_Fini();
1311 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001312 PyLong_Fini();
1313 PyFloat_Fini();
1314 PyDict_Fini();
1315 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001316 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001317 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001318 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001319 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001320 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001321 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001322
1323 /* Cleanup Unicode implementation */
1324 _PyUnicode_Fini();
1325
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001326 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001327
1328 /* XXX Still allocated:
1329 - various static ad-hoc pointers to interned strings
1330 - int and float free list blocks
1331 - whatever various modules and libraries allocate
1332 */
1333
1334 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1335
1336 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001337 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001338
1339 /* Delete current thread. After this, many C API calls become crashy. */
1340 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001341
Nick Coghland6009512014-11-20 21:39:37 +10001342 PyInterpreterState_Delete(interp);
1343
1344#ifdef Py_TRACE_REFS
1345 /* Display addresses (& refcnts) of all objects still alive.
1346 * An address can be used to find the repr of the object, printed
1347 * above by _Py_PrintReferences.
1348 */
Victor Stinnerda273412017-12-15 01:46:02 +01001349 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001350 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001351 }
Nick Coghland6009512014-11-20 21:39:37 +10001352#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001353#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001354 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001355 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001356 }
Nick Coghland6009512014-11-20 21:39:37 +10001357#endif
1358
Victor Stinner8e91c242019-04-24 17:24:01 +02001359 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001360
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001361 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001362 return status;
1363}
1364
1365void
1366Py_Finalize(void)
1367{
1368 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001369}
1370
1371/* Create and initialize a new interpreter and thread, and return the
1372 new thread. This requires that Py_Initialize() has been called
1373 first.
1374
1375 Unsuccessful initialization yields a NULL pointer. Note that *no*
1376 exception information is available even in this case -- the
1377 exception information is held in the thread, and there is no
1378 thread.
1379
1380 Locking: as above.
1381
1382*/
1383
Victor Stinner331a6a52019-05-27 16:39:22 +02001384static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001385new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001386{
Victor Stinner331a6a52019-05-27 16:39:22 +02001387 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001388
Victor Stinner331a6a52019-05-27 16:39:22 +02001389 status = _PyRuntime_Initialize();
1390 if (_PyStatus_EXCEPTION(status)) {
1391 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001392 }
1393 _PyRuntimeState *runtime = &_PyRuntime;
1394
1395 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001396 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001397 }
Nick Coghland6009512014-11-20 21:39:37 +10001398
Victor Stinner8a1be612016-03-14 22:07:55 +01001399 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1400 interpreters: disable PyGILState_Check(). */
1401 _PyGILState_check_enabled = 0;
1402
Victor Stinner43125222019-04-24 18:23:53 +02001403 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001404 if (interp == NULL) {
1405 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001406 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001407 }
Nick Coghland6009512014-11-20 21:39:37 +10001408
Victor Stinner43125222019-04-24 18:23:53 +02001409 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001410 if (tstate == NULL) {
1411 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001412 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001413 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001414 }
1415
Victor Stinner43125222019-04-24 18:23:53 +02001416 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001417
Eric Snow1abcf672017-05-23 21:46:51 -07001418 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001419 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001420 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001421 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001422 } else {
1423 /* No current thread state, copy from the main interpreter */
1424 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001425 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001426 }
1427
Victor Stinner331a6a52019-05-27 16:39:22 +02001428 status = _PyConfig_Copy(&interp->config, config);
1429 if (_PyStatus_EXCEPTION(status)) {
1430 return status;
Victor Stinnerda273412017-12-15 01:46:02 +01001431 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001432 config = &interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001433
Victor Stinner331a6a52019-05-27 16:39:22 +02001434 status = _PyExc_Init();
1435 if (_PyStatus_EXCEPTION(status)) {
1436 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001437 }
1438
Victor Stinner331a6a52019-05-27 16:39:22 +02001439 status = _PyErr_Init();
1440 if (_PyStatus_EXCEPTION(status)) {
1441 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +02001442 }
1443
1444
Nick Coghland6009512014-11-20 21:39:37 +10001445 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001446 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001447 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001448 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001449 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001450 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001451
Victor Stinner43125222019-04-24 18:23:53 +02001452 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001453 if (sysmod != NULL) {
1454 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001455 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001456 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001457 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001458 Py_INCREF(interp->sysdict);
1459 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner838f2642019-06-13 22:41:23 +02001460 if (_PySys_InitMain(runtime, tstate) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001461 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerab672812019-01-23 15:04:40 +01001462 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001463 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001464 else if (PyErr_Occurred()) {
1465 goto handle_error;
1466 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001467
Victor Stinner43125222019-04-24 18:23:53 +02001468 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001469 if (bimod != NULL) {
1470 interp->builtins = PyModule_GetDict(bimod);
1471 if (interp->builtins == NULL)
1472 goto handle_error;
1473 Py_INCREF(interp->builtins);
1474 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001475 else if (PyErr_Occurred()) {
1476 goto handle_error;
1477 }
Nick Coghland6009512014-11-20 21:39:37 +10001478
Nick Coghland6009512014-11-20 21:39:37 +10001479 if (bimod != NULL && sysmod != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001480 status = _PyBuiltins_AddExceptions(bimod);
1481 if (_PyStatus_EXCEPTION(status)) {
1482 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001483 }
Nick Coghland6009512014-11-20 21:39:37 +10001484
Victor Stinner331a6a52019-05-27 16:39:22 +02001485 status = _PySys_SetPreliminaryStderr(interp->sysdict);
1486 if (_PyStatus_EXCEPTION(status)) {
1487 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001488 }
Nick Coghland6009512014-11-20 21:39:37 +10001489
Victor Stinner331a6a52019-05-27 16:39:22 +02001490 status = _PyImportHooks_Init();
1491 if (_PyStatus_EXCEPTION(status)) {
1492 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001493 }
Nick Coghland6009512014-11-20 21:39:37 +10001494
Victor Stinner331a6a52019-05-27 16:39:22 +02001495 status = init_importlib(interp, sysmod);
1496 if (_PyStatus_EXCEPTION(status)) {
1497 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498 }
Nick Coghland6009512014-11-20 21:39:37 +10001499
Victor Stinner331a6a52019-05-27 16:39:22 +02001500 status = init_importlib_external(interp);
1501 if (_PyStatus_EXCEPTION(status)) {
1502 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001503 }
Nick Coghland6009512014-11-20 21:39:37 +10001504
Victor Stinner331a6a52019-05-27 16:39:22 +02001505 status = _PyUnicode_InitEncodings(interp);
1506 if (_PyStatus_EXCEPTION(status)) {
1507 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001508 }
1509
Victor Stinner331a6a52019-05-27 16:39:22 +02001510 status = init_sys_streams(interp);
1511 if (_PyStatus_EXCEPTION(status)) {
1512 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001513 }
1514
Victor Stinner331a6a52019-05-27 16:39:22 +02001515 status = add_main_module(interp);
1516 if (_PyStatus_EXCEPTION(status)) {
1517 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001518 }
1519
Victor Stinner331a6a52019-05-27 16:39:22 +02001520 if (config->site_import) {
1521 status = init_import_size();
1522 if (_PyStatus_EXCEPTION(status)) {
1523 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524 }
1525 }
Nick Coghland6009512014-11-20 21:39:37 +10001526 }
1527
Victor Stinnera7368ac2017-11-15 18:11:45 -08001528 if (PyErr_Occurred()) {
1529 goto handle_error;
1530 }
Nick Coghland6009512014-11-20 21:39:37 +10001531
Victor Stinnera7368ac2017-11-15 18:11:45 -08001532 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001533 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001534
Nick Coghland6009512014-11-20 21:39:37 +10001535handle_error:
1536 /* Oops, it didn't work. Undo it all. */
1537
1538 PyErr_PrintEx(0);
1539 PyThreadState_Clear(tstate);
1540 PyThreadState_Swap(save_tstate);
1541 PyThreadState_Delete(tstate);
1542 PyInterpreterState_Delete(interp);
1543
Victor Stinnera7368ac2017-11-15 18:11:45 -08001544 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001545 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001546}
1547
1548PyThreadState *
1549Py_NewInterpreter(void)
1550{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001551 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001552 PyStatus status = new_interpreter(&tstate);
1553 if (_PyStatus_EXCEPTION(status)) {
1554 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001555 }
1556 return tstate;
1557
Nick Coghland6009512014-11-20 21:39:37 +10001558}
1559
1560/* Delete an interpreter and its last thread. This requires that the
1561 given thread state is current, that the thread has no remaining
1562 frames, and that it is its interpreter's only remaining thread.
1563 It is a fatal error to violate these constraints.
1564
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001565 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001566 everything, regardless.)
1567
1568 Locking: as above.
1569
1570*/
1571
1572void
1573Py_EndInterpreter(PyThreadState *tstate)
1574{
1575 PyInterpreterState *interp = tstate->interp;
1576
Victor Stinner50b48572018-11-01 01:51:40 +01001577 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001578 Py_FatalError("Py_EndInterpreter: thread is not current");
1579 if (tstate->frame != NULL)
1580 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001581 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001582
Eric Snow842a2f02019-03-15 15:47:51 -06001583 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001584 wait_for_thread_shutdown();
1585
Marcel Plch776407f2017-12-20 11:17:58 +01001586 call_py_exitfuncs(interp);
1587
Nick Coghland6009512014-11-20 21:39:37 +10001588 if (tstate != interp->tstate_head || tstate->next != NULL)
1589 Py_FatalError("Py_EndInterpreter: not the last thread");
1590
1591 PyImport_Cleanup();
1592 PyInterpreterState_Clear(interp);
1593 PyThreadState_Swap(NULL);
1594 PyInterpreterState_Delete(interp);
1595}
1596
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001597/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001598
Victor Stinner331a6a52019-05-27 16:39:22 +02001599static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001600add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001601{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001602 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001603 m = PyImport_AddModule("__main__");
1604 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001605 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001606
Nick Coghland6009512014-11-20 21:39:37 +10001607 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001608 ann_dict = PyDict_New();
1609 if ((ann_dict == NULL) ||
1610 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001611 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001612 }
1613 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001614
Nick Coghland6009512014-11-20 21:39:37 +10001615 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1616 PyObject *bimod = PyImport_ImportModule("builtins");
1617 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001618 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001619 }
1620 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001621 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001622 }
1623 Py_DECREF(bimod);
1624 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001625
Nick Coghland6009512014-11-20 21:39:37 +10001626 /* Main is a little special - imp.is_builtin("__main__") will return
1627 * False, but BuiltinImporter is still the most appropriate initial
1628 * setting for its __loader__ attribute. A more suitable value will
1629 * be set if __main__ gets further initialized later in the startup
1630 * process.
1631 */
1632 loader = PyDict_GetItemString(d, "__loader__");
1633 if (loader == NULL || loader == Py_None) {
1634 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1635 "BuiltinImporter");
1636 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001637 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001638 }
1639 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001640 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001641 }
1642 Py_DECREF(loader);
1643 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001644 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001645}
1646
Nick Coghland6009512014-11-20 21:39:37 +10001647/* Import the site module (not into __main__ though) */
1648
Victor Stinner331a6a52019-05-27 16:39:22 +02001649static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001650init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001651{
1652 PyObject *m;
1653 m = PyImport_ImportModule("site");
1654 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001655 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001656 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001657 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001658 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001659}
1660
Victor Stinner874dbe82015-09-04 17:29:57 +02001661/* Check if a file descriptor is valid or not.
1662 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1663static int
1664is_valid_fd(int fd)
1665{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001666/* dup() is faster than fstat(): fstat() can require input/output operations,
1667 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1668 startup. Problem: dup() doesn't check if the file descriptor is valid on
1669 some platforms.
1670
1671 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1672 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1673 EBADF. FreeBSD has similar issue (bpo-32849).
1674
1675 Only use dup() on platforms where dup() is enough to detect invalid FD in
1676 corner cases: on Linux and Windows (bpo-32849). */
1677#if defined(__linux__) || defined(MS_WINDOWS)
1678 if (fd < 0) {
1679 return 0;
1680 }
1681 int fd2;
1682
1683 _Py_BEGIN_SUPPRESS_IPH
1684 fd2 = dup(fd);
1685 if (fd2 >= 0) {
1686 close(fd2);
1687 }
1688 _Py_END_SUPPRESS_IPH
1689
1690 return (fd2 >= 0);
1691#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001692 struct stat st;
1693 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001694#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001695}
1696
1697/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001698static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001699create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001700 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001701 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001702{
1703 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1704 const char* mode;
1705 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001706 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001707 int buffering, isatty;
1708 _Py_IDENTIFIER(open);
1709 _Py_IDENTIFIER(isatty);
1710 _Py_IDENTIFIER(TextIOWrapper);
1711 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001712 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001713
Victor Stinner874dbe82015-09-04 17:29:57 +02001714 if (!is_valid_fd(fd))
1715 Py_RETURN_NONE;
1716
Nick Coghland6009512014-11-20 21:39:37 +10001717 /* stdin is always opened in buffered mode, first because it shouldn't
1718 make a difference in common use cases, second because TextIOWrapper
1719 depends on the presence of a read1() method which only exists on
1720 buffered streams.
1721 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001722 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001723 buffering = 0;
1724 else
1725 buffering = -1;
1726 if (write_mode)
1727 mode = "wb";
1728 else
1729 mode = "rb";
1730 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1731 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001732 Py_None, Py_None, /* encoding, errors */
1733 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001734 if (buf == NULL)
1735 goto error;
1736
1737 if (buffering) {
1738 _Py_IDENTIFIER(raw);
1739 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1740 if (raw == NULL)
1741 goto error;
1742 }
1743 else {
1744 raw = buf;
1745 Py_INCREF(raw);
1746 }
1747
Steve Dower39294992016-08-30 21:22:36 -07001748#ifdef MS_WINDOWS
1749 /* Windows console IO is always UTF-8 encoded */
1750 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001751 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001752#endif
1753
Nick Coghland6009512014-11-20 21:39:37 +10001754 text = PyUnicode_FromString(name);
1755 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1756 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001757 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001758 if (res == NULL)
1759 goto error;
1760 isatty = PyObject_IsTrue(res);
1761 Py_DECREF(res);
1762 if (isatty == -1)
1763 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001764 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001765 write_through = Py_True;
1766 else
1767 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001768 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001769 line_buffering = Py_True;
1770 else
1771 line_buffering = Py_False;
1772
1773 Py_CLEAR(raw);
1774 Py_CLEAR(text);
1775
1776#ifdef MS_WINDOWS
1777 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1778 newlines to "\n".
1779 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1780 newline = NULL;
1781#else
1782 /* sys.stdin: split lines at "\n".
1783 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1784 newline = "\n";
1785#endif
1786
Victor Stinner709d23d2019-05-02 14:56:30 -04001787 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1788 if (encoding_str == NULL) {
1789 Py_CLEAR(buf);
1790 goto error;
1791 }
1792
1793 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1794 if (errors_str == NULL) {
1795 Py_CLEAR(buf);
1796 Py_CLEAR(encoding_str);
1797 goto error;
1798 }
1799
1800 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1801 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001802 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001803 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001804 Py_CLEAR(encoding_str);
1805 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001806 if (stream == NULL)
1807 goto error;
1808
1809 if (write_mode)
1810 mode = "w";
1811 else
1812 mode = "r";
1813 text = PyUnicode_FromString(mode);
1814 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1815 goto error;
1816 Py_CLEAR(text);
1817 return stream;
1818
1819error:
1820 Py_XDECREF(buf);
1821 Py_XDECREF(stream);
1822 Py_XDECREF(text);
1823 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001824
Victor Stinner874dbe82015-09-04 17:29:57 +02001825 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1826 /* Issue #24891: the file descriptor was closed after the first
1827 is_valid_fd() check was called. Ignore the OSError and set the
1828 stream to None. */
1829 PyErr_Clear();
1830 Py_RETURN_NONE;
1831 }
1832 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001833}
1834
1835/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001836static PyStatus
Victor Stinner91106cd2017-12-13 12:29:09 +01001837init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001838{
1839 PyObject *iomod = NULL, *wrapper;
1840 PyObject *bimod = NULL;
1841 PyObject *m;
1842 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001843 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001844 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001845 PyStatus res = _PyStatus_OK();
1846 PyConfig *config = &interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001847
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001848 /* Check that stdin is not a directory
1849 Using shell redirection, you can redirect stdin to a directory,
1850 crashing the Python interpreter. Catch this common mistake here
1851 and output a useful error message. Note that under MS Windows,
1852 the shell already prevents that. */
1853#ifndef MS_WINDOWS
1854 struct _Py_stat_struct sb;
1855 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1856 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001857 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001858 }
1859#endif
1860
Nick Coghland6009512014-11-20 21:39:37 +10001861 /* Hack to avoid a nasty recursion issue when Python is invoked
1862 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1863 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1864 goto error;
1865 }
1866 Py_DECREF(m);
1867
1868 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1869 goto error;
1870 }
1871 Py_DECREF(m);
1872
1873 if (!(bimod = PyImport_ImportModule("builtins"))) {
1874 goto error;
1875 }
1876
1877 if (!(iomod = PyImport_ImportModule("io"))) {
1878 goto error;
1879 }
1880 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1881 goto error;
1882 }
1883
1884 /* Set builtins.open */
1885 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1886 Py_DECREF(wrapper);
1887 goto error;
1888 }
1889 Py_DECREF(wrapper);
1890
Nick Coghland6009512014-11-20 21:39:37 +10001891 /* Set sys.stdin */
1892 fd = fileno(stdin);
1893 /* Under some conditions stdin, stdout and stderr may not be connected
1894 * and fileno() may point to an invalid file descriptor. For example
1895 * GUI apps don't have valid standard streams by default.
1896 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001897 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001898 config->stdio_encoding,
1899 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001900 if (std == NULL)
1901 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001902 PySys_SetObject("__stdin__", std);
1903 _PySys_SetObjectId(&PyId_stdin, std);
1904 Py_DECREF(std);
1905
1906 /* Set sys.stdout */
1907 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001908 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001909 config->stdio_encoding,
1910 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001911 if (std == NULL)
1912 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001913 PySys_SetObject("__stdout__", std);
1914 _PySys_SetObjectId(&PyId_stdout, std);
1915 Py_DECREF(std);
1916
1917#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1918 /* Set sys.stderr, replaces the preliminary stderr */
1919 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001920 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001921 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001922 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001923 if (std == NULL)
1924 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001925
1926 /* Same as hack above, pre-import stderr's codec to avoid recursion
1927 when import.c tries to write to stderr in verbose mode. */
1928 encoding_attr = PyObject_GetAttrString(std, "encoding");
1929 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001930 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001931 if (std_encoding != NULL) {
1932 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1933 Py_XDECREF(codec_info);
1934 }
1935 Py_DECREF(encoding_attr);
1936 }
1937 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1938
1939 if (PySys_SetObject("__stderr__", std) < 0) {
1940 Py_DECREF(std);
1941 goto error;
1942 }
1943 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1944 Py_DECREF(std);
1945 goto error;
1946 }
1947 Py_DECREF(std);
1948#endif
1949
Victor Stinnera7368ac2017-11-15 18:11:45 -08001950 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001951
Victor Stinnera7368ac2017-11-15 18:11:45 -08001952error:
Victor Stinner331a6a52019-05-27 16:39:22 +02001953 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001954
1955done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001956 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001957
Nick Coghland6009512014-11-20 21:39:37 +10001958 Py_XDECREF(bimod);
1959 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001960 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001961}
1962
1963
Victor Stinner10dc4842015-03-24 12:01:30 +01001964static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001965_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001966{
Victor Stinner10dc4842015-03-24 12:01:30 +01001967 fputc('\n', stderr);
1968 fflush(stderr);
1969
1970 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001971 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001972}
Victor Stinner791da1c2016-03-14 16:53:12 +01001973
1974/* Print the current exception (if an exception is set) with its traceback,
1975 or display the current Python stack.
1976
1977 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1978 called on catastrophic cases.
1979
1980 Return 1 if the traceback was displayed, 0 otherwise. */
1981
1982static int
1983_Py_FatalError_PrintExc(int fd)
1984{
1985 PyObject *ferr, *res;
1986 PyObject *exception, *v, *tb;
1987 int has_tb;
1988
Victor Stinner791da1c2016-03-14 16:53:12 +01001989 PyErr_Fetch(&exception, &v, &tb);
1990 if (exception == NULL) {
1991 /* No current exception */
1992 return 0;
1993 }
1994
1995 ferr = _PySys_GetObjectId(&PyId_stderr);
1996 if (ferr == NULL || ferr == Py_None) {
1997 /* sys.stderr is not set yet or set to None,
1998 no need to try to display the exception */
1999 return 0;
2000 }
2001
2002 PyErr_NormalizeException(&exception, &v, &tb);
2003 if (tb == NULL) {
2004 tb = Py_None;
2005 Py_INCREF(tb);
2006 }
2007 PyException_SetTraceback(v, tb);
2008 if (exception == NULL) {
2009 /* PyErr_NormalizeException() failed */
2010 return 0;
2011 }
2012
2013 has_tb = (tb != Py_None);
2014 PyErr_Display(exception, v, tb);
2015 Py_XDECREF(exception);
2016 Py_XDECREF(v);
2017 Py_XDECREF(tb);
2018
2019 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002020 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002021 if (res == NULL)
2022 PyErr_Clear();
2023 else
2024 Py_DECREF(res);
2025
2026 return has_tb;
2027}
2028
Nick Coghland6009512014-11-20 21:39:37 +10002029/* Print fatal error message and abort */
2030
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002031#ifdef MS_WINDOWS
2032static void
2033fatal_output_debug(const char *msg)
2034{
2035 /* buffer of 256 bytes allocated on the stack */
2036 WCHAR buffer[256 / sizeof(WCHAR)];
2037 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2038 size_t msglen;
2039
2040 OutputDebugStringW(L"Fatal Python error: ");
2041
2042 msglen = strlen(msg);
2043 while (msglen) {
2044 size_t i;
2045
2046 if (buflen > msglen) {
2047 buflen = msglen;
2048 }
2049
2050 /* Convert the message to wchar_t. This uses a simple one-to-one
2051 conversion, assuming that the this error message actually uses
2052 ASCII only. If this ceases to be true, we will have to convert. */
2053 for (i=0; i < buflen; ++i) {
2054 buffer[i] = msg[i];
2055 }
2056 buffer[i] = L'\0';
2057 OutputDebugStringW(buffer);
2058
2059 msg += buflen;
2060 msglen -= buflen;
2061 }
2062 OutputDebugStringW(L"\n");
2063}
2064#endif
2065
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002066static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002067fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002068{
2069 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002070 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002071
2072 if (reentrant) {
2073 /* Py_FatalError() caused a second fatal error.
2074 Example: flush_std_files() raises a recursion error. */
2075 goto exit;
2076 }
2077 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002078
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002079 fprintf(stderr, "Fatal Python error: ");
2080 if (prefix) {
2081 fputs(prefix, stderr);
2082 fputs(": ", stderr);
2083 }
2084 if (msg) {
2085 fputs(msg, stderr);
2086 }
2087 else {
2088 fprintf(stderr, "<message not set>");
2089 }
2090 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002091 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002092
Victor Stinner3a228ab2018-11-01 00:26:41 +01002093 /* Check if the current thread has a Python thread state
2094 and holds the GIL */
2095 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2096 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002097 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002098 if (tss_tstate != tstate) {
2099 /* The Python thread does not hold the GIL */
2100 tss_tstate = NULL;
2101 }
2102 }
2103 else {
2104 /* Py_FatalError() has been called from a C thread
2105 which has no Python thread state. */
2106 }
2107 int has_tstate_and_gil = (tss_tstate != NULL);
2108
2109 if (has_tstate_and_gil) {
2110 /* If an exception is set, print the exception with its traceback */
2111 if (!_Py_FatalError_PrintExc(fd)) {
2112 /* No exception is set, or an exception is set without traceback */
2113 _Py_FatalError_DumpTracebacks(fd);
2114 }
2115 }
2116 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002117 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002118 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002119
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002120 /* The main purpose of faulthandler is to display the traceback.
2121 This function already did its best to display a traceback.
2122 Disable faulthandler to prevent writing a second traceback
2123 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002124 _PyFaulthandler_Fini();
2125
Victor Stinner791da1c2016-03-14 16:53:12 +01002126 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002127 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002128 /* Flush sys.stdout and sys.stderr */
2129 flush_std_files();
2130 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002131
Nick Coghland6009512014-11-20 21:39:37 +10002132#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002133 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002134#endif /* MS_WINDOWS */
2135
2136exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002137 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002138#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002139 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002140#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002141 abort();
2142 }
2143 else {
2144 exit(status);
2145 }
2146}
2147
Victor Stinner19760862017-12-20 01:41:59 +01002148void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002149Py_FatalError(const char *msg)
2150{
2151 fatal_error(NULL, msg, -1);
2152}
2153
Victor Stinner19760862017-12-20 01:41:59 +01002154void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002155Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002156{
Victor Stinner331a6a52019-05-27 16:39:22 +02002157 if (_PyStatus_IS_EXIT(status)) {
2158 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002159 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002160 else if (_PyStatus_IS_ERROR(status)) {
2161 fatal_error(status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002162 }
2163 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002164 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002165 }
Nick Coghland6009512014-11-20 21:39:37 +10002166}
2167
2168/* Clean up and exit */
2169
Victor Stinnerd7292b52016-06-17 12:29:00 +02002170# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002171
Nick Coghland6009512014-11-20 21:39:37 +10002172/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002173void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002174{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002175 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002176
Antoine Pitroufc5db952017-12-13 02:29:07 +01002177 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002178 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2179
2180 is->pyexitfunc = func;
2181 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002182}
2183
2184static void
Marcel Plch776407f2017-12-20 11:17:58 +01002185call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002186{
Marcel Plch776407f2017-12-20 11:17:58 +01002187 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002188 return;
2189
Marcel Plch776407f2017-12-20 11:17:58 +01002190 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002191 PyErr_Clear();
2192}
2193
2194/* Wait until threading._shutdown completes, provided
2195 the threading module was imported in the first place.
2196 The shutdown routine will wait until all non-daemon
2197 "threading" threads have completed. */
2198static void
2199wait_for_thread_shutdown(void)
2200{
Nick Coghland6009512014-11-20 21:39:37 +10002201 _Py_IDENTIFIER(_shutdown);
2202 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002203 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002204 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002205 if (PyErr_Occurred()) {
2206 PyErr_WriteUnraisable(NULL);
2207 }
2208 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002209 return;
2210 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002211 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002212 if (result == NULL) {
2213 PyErr_WriteUnraisable(threading);
2214 }
2215 else {
2216 Py_DECREF(result);
2217 }
2218 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002219}
2220
2221#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002222int Py_AtExit(void (*func)(void))
2223{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002224 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002225 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002226 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002227 return 0;
2228}
2229
2230static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002231call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002232{
Victor Stinner8e91c242019-04-24 17:24:01 +02002233 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002234 /* pop last function from the list */
2235 runtime->nexitfuncs--;
2236 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2237 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2238
2239 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002240 }
Nick Coghland6009512014-11-20 21:39:37 +10002241
2242 fflush(stdout);
2243 fflush(stderr);
2244}
2245
Victor Stinnercfc88312018-08-01 16:41:25 +02002246void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002247Py_Exit(int sts)
2248{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002249 if (Py_FinalizeEx() < 0) {
2250 sts = 120;
2251 }
Nick Coghland6009512014-11-20 21:39:37 +10002252
2253 exit(sts);
2254}
2255
Victor Stinner331a6a52019-05-27 16:39:22 +02002256static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002257init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002258{
2259#ifdef SIGPIPE
2260 PyOS_setsig(SIGPIPE, SIG_IGN);
2261#endif
2262#ifdef SIGXFZ
2263 PyOS_setsig(SIGXFZ, SIG_IGN);
2264#endif
2265#ifdef SIGXFSZ
2266 PyOS_setsig(SIGXFSZ, SIG_IGN);
2267#endif
2268 PyOS_InitInterrupts(); /* May imply initsignal() */
2269 if (PyErr_Occurred()) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002270 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002271 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002272 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002273}
2274
2275
2276/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2277 *
2278 * All of the code in this function must only use async-signal-safe functions,
2279 * listed at `man 7 signal` or
2280 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2281 */
2282void
2283_Py_RestoreSignals(void)
2284{
2285#ifdef SIGPIPE
2286 PyOS_setsig(SIGPIPE, SIG_DFL);
2287#endif
2288#ifdef SIGXFZ
2289 PyOS_setsig(SIGXFZ, SIG_DFL);
2290#endif
2291#ifdef SIGXFSZ
2292 PyOS_setsig(SIGXFSZ, SIG_DFL);
2293#endif
2294}
2295
2296
2297/*
2298 * The file descriptor fd is considered ``interactive'' if either
2299 * a) isatty(fd) is TRUE, or
2300 * b) the -i flag was given, and the filename associated with
2301 * the descriptor is NULL or "<stdin>" or "???".
2302 */
2303int
2304Py_FdIsInteractive(FILE *fp, const char *filename)
2305{
2306 if (isatty((int)fileno(fp)))
2307 return 1;
2308 if (!Py_InteractiveFlag)
2309 return 0;
2310 return (filename == NULL) ||
2311 (strcmp(filename, "<stdin>") == 0) ||
2312 (strcmp(filename, "???") == 0);
2313}
2314
2315
Nick Coghland6009512014-11-20 21:39:37 +10002316/* Wrappers around sigaction() or signal(). */
2317
2318PyOS_sighandler_t
2319PyOS_getsig(int sig)
2320{
2321#ifdef HAVE_SIGACTION
2322 struct sigaction context;
2323 if (sigaction(sig, NULL, &context) == -1)
2324 return SIG_ERR;
2325 return context.sa_handler;
2326#else
2327 PyOS_sighandler_t handler;
2328/* Special signal handling for the secure CRT in Visual Studio 2005 */
2329#if defined(_MSC_VER) && _MSC_VER >= 1400
2330 switch (sig) {
2331 /* Only these signals are valid */
2332 case SIGINT:
2333 case SIGILL:
2334 case SIGFPE:
2335 case SIGSEGV:
2336 case SIGTERM:
2337 case SIGBREAK:
2338 case SIGABRT:
2339 break;
2340 /* Don't call signal() with other values or it will assert */
2341 default:
2342 return SIG_ERR;
2343 }
2344#endif /* _MSC_VER && _MSC_VER >= 1400 */
2345 handler = signal(sig, SIG_IGN);
2346 if (handler != SIG_ERR)
2347 signal(sig, handler);
2348 return handler;
2349#endif
2350}
2351
2352/*
2353 * All of the code in this function must only use async-signal-safe functions,
2354 * listed at `man 7 signal` or
2355 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2356 */
2357PyOS_sighandler_t
2358PyOS_setsig(int sig, PyOS_sighandler_t handler)
2359{
2360#ifdef HAVE_SIGACTION
2361 /* Some code in Modules/signalmodule.c depends on sigaction() being
2362 * used here if HAVE_SIGACTION is defined. Fix that if this code
2363 * changes to invalidate that assumption.
2364 */
2365 struct sigaction context, ocontext;
2366 context.sa_handler = handler;
2367 sigemptyset(&context.sa_mask);
2368 context.sa_flags = 0;
2369 if (sigaction(sig, &context, &ocontext) == -1)
2370 return SIG_ERR;
2371 return ocontext.sa_handler;
2372#else
2373 PyOS_sighandler_t oldhandler;
2374 oldhandler = signal(sig, handler);
2375#ifdef HAVE_SIGINTERRUPT
2376 siginterrupt(sig, 1);
2377#endif
2378 return oldhandler;
2379#endif
2380}
2381
2382#ifdef __cplusplus
2383}
2384#endif