blob: 4d7873fd522481f0e2eb4d95663028667cf0148d [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) {
Victor Stinner9f3dcf82019-09-21 02:13:14 +0200475 status = _PyPathConfig_Init();
Victor Stinner331a6a52019-05-27 16:39:22 +0200476 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 Stinner9f3dcf82019-09-21 02:13:14 +0200626 const PyConfig *config = &interp->config;
627
Victor Stinner331a6a52019-05-27 16:39:22 +0200628 PyStatus status = _PyImport_Init(interp);
629 if (_PyStatus_EXCEPTION(status)) {
630 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800631 }
Nick Coghland6009512014-11-20 21:39:37 +1000632
Victor Stinner331a6a52019-05-27 16:39:22 +0200633 status = _PyImportHooks_Init();
634 if (_PyStatus_EXCEPTION(status)) {
635 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800636 }
Nick Coghland6009512014-11-20 21:39:37 +1000637
638 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100639 if (_PyWarnings_Init() == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200640 return _PyStatus_ERR("can't initialize warnings");
Victor Stinner1f151112017-11-23 10:43:14 +0100641 }
Nick Coghland6009512014-11-20 21:39:37 +1000642
Victor Stinner9f3dcf82019-09-21 02:13:14 +0200643 if (config->_install_importlib) {
644 status = _PyPathConfig_Init();
Victor Stinner331a6a52019-05-27 16:39:22 +0200645 if (_PyStatus_EXCEPTION(status)) {
646 return status;
Victor Stinnerb1147e42018-07-21 02:06:16 +0200647 }
648 }
649
Eric Snow1abcf672017-05-23 21:46:51 -0700650 /* This call sets up builtin and frozen import support */
Victor Stinner9f3dcf82019-09-21 02:13:14 +0200651 if (config->_install_importlib) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200652 status = init_importlib(interp, sysmod);
653 if (_PyStatus_EXCEPTION(status)) {
654 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800655 }
Eric Snow1abcf672017-05-23 21:46:51 -0700656 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200657 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100658}
659
660
Victor Stinner331a6a52019-05-27 16:39:22 +0200661static PyStatus
662pyinit_config(_PyRuntimeState *runtime,
663 PyInterpreterState **interp_p,
664 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100665{
666 PyInterpreterState *interp;
667
Victor Stinner331a6a52019-05-27 16:39:22 +0200668 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100669
Victor Stinner331a6a52019-05-27 16:39:22 +0200670 PyStatus status = pycore_init_runtime(runtime, config);
671 if (_PyStatus_EXCEPTION(status)) {
672 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100673 }
674
Victor Stinner331a6a52019-05-27 16:39:22 +0200675 status = pycore_create_interpreter(runtime, config, &interp);
676 if (_PyStatus_EXCEPTION(status)) {
677 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100678 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200679 config = &interp->config;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100680 *interp_p = interp;
681
Victor Stinner331a6a52019-05-27 16:39:22 +0200682 status = pycore_init_types();
683 if (_PyStatus_EXCEPTION(status)) {
684 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100685 }
686
687 PyObject *sysmod;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200688 status = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200689 if (_PyStatus_EXCEPTION(status)) {
690 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100691 }
692
Victor Stinner331a6a52019-05-27 16:39:22 +0200693 status = pycore_init_builtins(interp);
694 if (_PyStatus_EXCEPTION(status)) {
695 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100696 }
697
Victor Stinner331a6a52019-05-27 16:39:22 +0200698 status = pycore_init_import_warnings(interp, sysmod);
699 if (_PyStatus_EXCEPTION(status)) {
700 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100701 }
Eric Snow1abcf672017-05-23 21:46:51 -0700702
703 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200704 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200705 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700706}
707
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100708
Victor Stinner331a6a52019-05-27 16:39:22 +0200709PyStatus
710_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100711{
Victor Stinner331a6a52019-05-27 16:39:22 +0200712 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100713
Victor Stinner6d1c4672019-05-20 11:02:00 +0200714 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200715 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200716 }
717
Victor Stinner331a6a52019-05-27 16:39:22 +0200718 status = _PyRuntime_Initialize();
719 if (_PyStatus_EXCEPTION(status)) {
720 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100721 }
Victor Stinner43125222019-04-24 18:23:53 +0200722 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100723
Victor Stinner47bbab92019-09-18 14:10:16 +0200724 if (runtime->preinitialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100725 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200726 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100727 }
728
Victor Stinner47bbab92019-09-18 14:10:16 +0200729 /* Note: preinitialized remains 1 on error, it is only set to 0
730 at exit on success. */
731 runtime->preinitializing = 1;
732
Victor Stinner331a6a52019-05-27 16:39:22 +0200733 PyPreConfig config;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200734 _PyPreConfig_InitFromPreConfig(&config, src_config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100735
Victor Stinner331a6a52019-05-27 16:39:22 +0200736 status = _PyPreConfig_Read(&config, args);
737 if (_PyStatus_EXCEPTION(status)) {
738 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100739 }
740
Victor Stinner331a6a52019-05-27 16:39:22 +0200741 status = _PyPreConfig_Write(&config);
742 if (_PyStatus_EXCEPTION(status)) {
743 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100744 }
745
Victor Stinner47bbab92019-09-18 14:10:16 +0200746 runtime->preinitializing = 0;
747 runtime->preinitialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200748 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100749}
750
Victor Stinner70005ac2019-05-02 15:25:34 -0400751
Victor Stinner331a6a52019-05-27 16:39:22 +0200752PyStatus
753Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100754{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100755 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400756 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100757}
758
759
Victor Stinner331a6a52019-05-27 16:39:22 +0200760PyStatus
761Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100762{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100763 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400764 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100765}
766
767
Victor Stinner331a6a52019-05-27 16:39:22 +0200768PyStatus
769Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100770{
Victor Stinner70005ac2019-05-02 15:25:34 -0400771 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100772}
773
774
Victor Stinner331a6a52019-05-27 16:39:22 +0200775PyStatus
776_Py_PreInitializeFromConfig(const PyConfig *config,
777 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100778{
Victor Stinner331a6a52019-05-27 16:39:22 +0200779 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200780
Victor Stinner331a6a52019-05-27 16:39:22 +0200781 PyStatus status = _PyRuntime_Initialize();
782 if (_PyStatus_EXCEPTION(status)) {
783 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200784 }
785 _PyRuntimeState *runtime = &_PyRuntime;
786
Victor Stinner47bbab92019-09-18 14:10:16 +0200787 if (runtime->preinitialized) {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200788 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200789 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400790 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200791
Victor Stinner331a6a52019-05-27 16:39:22 +0200792 PyPreConfig preconfig;
793 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200794
Victor Stinner331a6a52019-05-27 16:39:22 +0200795 if (!config->parse_argv) {
796 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200797 }
798 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200799 _PyArgv config_args = {
800 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200801 .argc = config->argv.length,
802 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200803 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200804 }
805 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200806 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200807 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100808}
809
810
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100811/* Begin interpreter initialization
812 *
813 * On return, the first thread and interpreter state have been created,
814 * but the compiler, signal handling, multithreading and
815 * multiple interpreter support, and codec infrastructure are not yet
816 * available.
817 *
818 * The import system will support builtin and frozen modules only.
819 * The only supported io is writing to sys.stderr
820 *
821 * If any operation invoked by this function fails, a fatal error is
822 * issued and the function does not return.
823 *
824 * Any code invoked from this function should *not* assume it has access
825 * to the Python C API (unless the API is explicitly listed as being
826 * safe to call without calling Py_Initialize first)
827 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200828static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200829pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200830 const PyConfig *src_config,
Victor Stinner5edcf262019-05-23 00:57:57 +0200831 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200832{
Victor Stinner331a6a52019-05-27 16:39:22 +0200833 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200834
Victor Stinner331a6a52019-05-27 16:39:22 +0200835 status = _Py_PreInitializeFromConfig(src_config, NULL);
836 if (_PyStatus_EXCEPTION(status)) {
837 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200838 }
839
Victor Stinner331a6a52019-05-27 16:39:22 +0200840 PyConfig config;
841 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200842
Victor Stinner331a6a52019-05-27 16:39:22 +0200843 status = _PyConfig_Copy(&config, src_config);
844 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200845 goto done;
846 }
847
Victor Stinner331a6a52019-05-27 16:39:22 +0200848 status = PyConfig_Read(&config);
849 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200850 goto done;
851 }
852
853 if (!runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200854 status = pyinit_config(runtime, interp_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200855 }
856 else {
Victor Stinner331a6a52019-05-27 16:39:22 +0200857 status = pyinit_core_reconfigure(runtime, interp_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200858 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200859 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200860 goto done;
861 }
862
863done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200864 PyConfig_Clear(&config);
865 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200866}
867
Victor Stinner5ac27a52019-03-27 13:40:14 +0100868
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200869/* Py_Initialize() has already been called: update the main interpreter
870 configuration. Example of bpo-34008: Py_Main() called after
871 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200872static PyStatus
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100873_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200874{
Victor Stinner331a6a52019-05-27 16:39:22 +0200875 PyConfig *config = &interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100876
Victor Stinner331a6a52019-05-27 16:39:22 +0200877 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100878 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200879 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100880 }
881
882 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
883 Py_DECREF(argv);
884 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200885 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200886 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200887 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200888}
889
Eric Snowc7ec9982017-05-23 23:00:52 -0700890/* Update interpreter state based on supplied configuration settings
891 *
892 * After calling this function, most of the restrictions on the interpreter
893 * are lifted. The only remaining incomplete settings are those related
894 * to the main module (sys.argv[0], __main__ metadata)
895 *
896 * Calling this when the interpreter is not initializing, is already
897 * initialized or without a valid current thread state is a fatal error.
898 * Other errors should be reported as normal Python exceptions with a
899 * non-zero return code.
900 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200901static PyStatus
Victor Stinner0fd2c302019-06-04 03:15:09 +0200902pyinit_main(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700903{
Victor Stinner43125222019-04-24 18:23:53 +0200904 if (!runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200905 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700906 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700907
Victor Stinner1dc6e392018-07-25 02:49:17 +0200908 /* Configure the main interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +0200909 PyConfig *config = &interp->config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700910
Victor Stinner43125222019-04-24 18:23:53 +0200911 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100912 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200913 }
914
Victor Stinner331a6a52019-05-27 16:39:22 +0200915 if (!config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700916 /* Special mode for freeze_importlib: run with no import system
917 *
918 * This means anything which needs support from extension modules
919 * or pure Python code in the standard library won't work.
920 */
Victor Stinner43125222019-04-24 18:23:53 +0200921 runtime->initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200922 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700923 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100924
Victor Stinner33c377e2017-12-05 15:12:41 +0100925 if (_PyTime_Init() < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200926 return _PyStatus_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100927 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200928
Victor Stinner0fd2c302019-06-04 03:15:09 +0200929 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200930 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100931 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800932
Victor Stinner331a6a52019-05-27 16:39:22 +0200933 PyStatus status = init_importlib_external(interp);
934 if (_PyStatus_EXCEPTION(status)) {
935 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800936 }
Nick Coghland6009512014-11-20 21:39:37 +1000937
938 /* initialize the faulthandler module */
Victor Stinner331a6a52019-05-27 16:39:22 +0200939 status = _PyFaulthandler_Init(config->faulthandler);
940 if (_PyStatus_EXCEPTION(status)) {
941 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800942 }
Nick Coghland6009512014-11-20 21:39:37 +1000943
Victor Stinnerc5c64252019-09-23 15:59:00 +0200944 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
945 status = _PyUnicode_InitEncodings(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200946 if (_PyStatus_EXCEPTION(status)) {
947 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800948 }
Nick Coghland6009512014-11-20 21:39:37 +1000949
Victor Stinner331a6a52019-05-27 16:39:22 +0200950 if (config->install_signal_handlers) {
951 status = init_signals();
952 if (_PyStatus_EXCEPTION(status)) {
953 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800954 }
955 }
Nick Coghland6009512014-11-20 21:39:37 +1000956
Victor Stinner331a6a52019-05-27 16:39:22 +0200957 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
958 return _PyStatus_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200959 }
Nick Coghland6009512014-11-20 21:39:37 +1000960
Victor Stinner331a6a52019-05-27 16:39:22 +0200961 status = add_main_module(interp);
962 if (_PyStatus_EXCEPTION(status)) {
963 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800964 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800965
Victor Stinner331a6a52019-05-27 16:39:22 +0200966 status = init_sys_streams(interp);
967 if (_PyStatus_EXCEPTION(status)) {
968 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800969 }
Nick Coghland6009512014-11-20 21:39:37 +1000970
971 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100972 PyObject *warnoptions = PySys_GetObject("warnoptions");
973 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100974 {
Nick Coghland6009512014-11-20 21:39:37 +1000975 PyObject *warnings_module = PyImport_ImportModule("warnings");
976 if (warnings_module == NULL) {
977 fprintf(stderr, "'import warnings' failed; traceback:\n");
978 PyErr_Print();
979 }
980 Py_XDECREF(warnings_module);
981 }
982
Victor Stinner43125222019-04-24 18:23:53 +0200983 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700984
Victor Stinner331a6a52019-05-27 16:39:22 +0200985 if (config->site_import) {
986 status = init_import_size(); /* Module site */
987 if (_PyStatus_EXCEPTION(status)) {
988 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800989 }
990 }
Victor Stinnercf215042018-08-29 22:56:06 +0200991
992#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200993 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200994#endif
995
Victor Stinner331a6a52019-05-27 16:39:22 +0200996 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000997}
998
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200999
Victor Stinner331a6a52019-05-27 16:39:22 +02001000PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001001_Py_InitializeMain(void)
1002{
Victor Stinner331a6a52019-05-27 16:39:22 +02001003 PyStatus status = _PyRuntime_Initialize();
1004 if (_PyStatus_EXCEPTION(status)) {
1005 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001006 }
1007 _PyRuntimeState *runtime = &_PyRuntime;
1008 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
1009
Victor Stinner0fd2c302019-06-04 03:15:09 +02001010 return pyinit_main(runtime, interp);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001011}
1012
1013
Victor Stinner331a6a52019-05-27 16:39:22 +02001014PyStatus
1015Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001016{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001017 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001018 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001019 }
1020
Victor Stinner331a6a52019-05-27 16:39:22 +02001021 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001022
Victor Stinner331a6a52019-05-27 16:39:22 +02001023 status = _PyRuntime_Initialize();
1024 if (_PyStatus_EXCEPTION(status)) {
1025 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001026 }
1027 _PyRuntimeState *runtime = &_PyRuntime;
1028
1029 PyInterpreterState *interp = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001030 status = pyinit_core(runtime, config, &interp);
1031 if (_PyStatus_EXCEPTION(status)) {
1032 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001033 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001034 config = &interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001035
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001036 if (config->_init_main) {
Victor Stinner0fd2c302019-06-04 03:15:09 +02001037 status = pyinit_main(runtime, interp);
Victor Stinner331a6a52019-05-27 16:39:22 +02001038 if (_PyStatus_EXCEPTION(status)) {
1039 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001040 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001041 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001042
Victor Stinner331a6a52019-05-27 16:39:22 +02001043 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001044}
1045
1046
Eric Snow1abcf672017-05-23 21:46:51 -07001047void
Nick Coghland6009512014-11-20 21:39:37 +10001048Py_InitializeEx(int install_sigs)
1049{
Victor Stinner331a6a52019-05-27 16:39:22 +02001050 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001051
Victor Stinner331a6a52019-05-27 16:39:22 +02001052 status = _PyRuntime_Initialize();
1053 if (_PyStatus_EXCEPTION(status)) {
1054 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001055 }
1056 _PyRuntimeState *runtime = &_PyRuntime;
1057
1058 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001059 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1060 return;
1061 }
1062
Victor Stinner331a6a52019-05-27 16:39:22 +02001063 PyConfig config;
1064 _PyConfig_InitCompatConfig(&config);
Victor Stinner1dc6e392018-07-25 02:49:17 +02001065 config.install_signal_handlers = install_sigs;
1066
Victor Stinner331a6a52019-05-27 16:39:22 +02001067 status = Py_InitializeFromConfig(&config);
1068 if (_PyStatus_EXCEPTION(status)) {
1069 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001070 }
Nick Coghland6009512014-11-20 21:39:37 +10001071}
1072
1073void
1074Py_Initialize(void)
1075{
1076 Py_InitializeEx(1);
1077}
1078
1079
1080#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001081extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001082#endif
1083
1084/* Flush stdout and stderr */
1085
1086static int
1087file_is_closed(PyObject *fobj)
1088{
1089 int r;
1090 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1091 if (tmp == NULL) {
1092 PyErr_Clear();
1093 return 0;
1094 }
1095 r = PyObject_IsTrue(tmp);
1096 Py_DECREF(tmp);
1097 if (r < 0)
1098 PyErr_Clear();
1099 return r > 0;
1100}
1101
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001102static int
Nick Coghland6009512014-11-20 21:39:37 +10001103flush_std_files(void)
1104{
1105 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1106 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1107 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001108 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001109
1110 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001111 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001112 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001113 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001114 status = -1;
1115 }
Nick Coghland6009512014-11-20 21:39:37 +10001116 else
1117 Py_DECREF(tmp);
1118 }
1119
1120 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001121 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001122 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001123 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001124 status = -1;
1125 }
Nick Coghland6009512014-11-20 21:39:37 +10001126 else
1127 Py_DECREF(tmp);
1128 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001129
1130 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001131}
1132
1133/* Undo the effect of Py_Initialize().
1134
1135 Beware: if multiple interpreter and/or thread states exist, these
1136 are not wiped out; only the current thread and interpreter state
1137 are deleted. But since everything else is deleted, those other
1138 interpreter and thread states should no longer be used.
1139
1140 (XXX We should do better, e.g. wipe out all interpreters and
1141 threads.)
1142
1143 Locking: as above.
1144
1145*/
1146
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001147int
1148Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001149{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001150 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001151
Victor Stinner8e91c242019-04-24 17:24:01 +02001152 _PyRuntimeState *runtime = &_PyRuntime;
1153 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001154 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001155 }
Nick Coghland6009512014-11-20 21:39:37 +10001156
Eric Snow842a2f02019-03-15 15:47:51 -06001157 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001158 wait_for_thread_shutdown();
1159
Eric Snow842a2f02019-03-15 15:47:51 -06001160 // Make any remaining pending calls.
Victor Stinnere225beb2019-06-03 18:14:24 +02001161 _Py_FinishPendingCalls(runtime);
1162
1163 /* Get current thread state and interpreter pointer */
1164 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1165 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001166
Nick Coghland6009512014-11-20 21:39:37 +10001167 /* The interpreter is still entirely intact at this point, and the
1168 * exit funcs may be relying on that. In particular, if some thread
1169 * or exit func is still waiting to do an import, the import machinery
1170 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001171 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001172 * Note that Threading.py uses an exit func to do a join on all the
1173 * threads created thru it, so this also protects pending imports in
1174 * the threads created via Threading.
1175 */
Nick Coghland6009512014-11-20 21:39:37 +10001176
Marcel Plch776407f2017-12-20 11:17:58 +01001177 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001178
Victor Stinnerda273412017-12-15 01:46:02 +01001179 /* Copy the core config, PyInterpreterState_Delete() free
1180 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001181#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001182 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001183#endif
1184#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001185 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001186#endif
1187#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001188 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001189#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001190
Nick Coghland6009512014-11-20 21:39:37 +10001191 /* Remaining threads (e.g. daemon threads) will automatically exit
1192 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001193 runtime->finalizing = tstate;
1194 runtime->initialized = 0;
1195 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001196
Victor Stinnere0deff32015-03-24 13:46:18 +01001197 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001198 if (flush_std_files() < 0) {
1199 status = -1;
1200 }
Nick Coghland6009512014-11-20 21:39:37 +10001201
1202 /* Disable signal handling */
1203 PyOS_FiniInterrupts();
1204
1205 /* Collect garbage. This may call finalizers; it's nice to call these
1206 * before all modules are destroyed.
1207 * XXX If a __del__ or weakref callback is triggered here, and tries to
1208 * XXX import a module, bad things can happen, because Python no
1209 * XXX longer believes it's initialized.
1210 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1211 * XXX is easy to provoke that way. I've also seen, e.g.,
1212 * XXX Exception exceptions.ImportError: 'No module named sha'
1213 * XXX in <function callback at 0x008F5718> ignored
1214 * XXX but I'm unclear on exactly how that one happens. In any case,
1215 * XXX I haven't seen a real-life report of either of these.
1216 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001217 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001218#ifdef COUNT_ALLOCS
1219 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1220 each collection might release some types from the type
1221 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001222 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001223 /* nothing */;
1224#endif
Eric Snowdae02762017-09-14 00:35:58 -07001225
Steve Dowerb82e17e2019-05-23 08:45:22 -07001226 /* Clear all loghooks */
1227 /* We want minimal exposure of this function, so define the extern
1228 * here. The linker should discover the correct function without
1229 * exporting a symbol. */
1230 extern void _PySys_ClearAuditHooks(void);
1231 _PySys_ClearAuditHooks();
1232
Nick Coghland6009512014-11-20 21:39:37 +10001233 /* Destroy all modules */
1234 PyImport_Cleanup();
1235
Inada Naoki91234a12019-06-03 21:30:58 +09001236 /* Print debug stats if any */
1237 _PyEval_Fini();
1238
Victor Stinnere0deff32015-03-24 13:46:18 +01001239 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001240 if (flush_std_files() < 0) {
1241 status = -1;
1242 }
Nick Coghland6009512014-11-20 21:39:37 +10001243
1244 /* Collect final garbage. This disposes of cycles created by
1245 * class definitions, for example.
1246 * XXX This is disabled because it caused too many problems. If
1247 * XXX a __del__ or weakref callback triggers here, Python code has
1248 * XXX a hard time running, because even the sys module has been
1249 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1250 * XXX One symptom is a sequence of information-free messages
1251 * XXX coming from threads (if a __del__ or callback is invoked,
1252 * XXX other threads can execute too, and any exception they encounter
1253 * XXX triggers a comedy of errors as subsystem after subsystem
1254 * XXX fails to find what it *expects* to find in sys to help report
1255 * XXX the exception and consequent unexpected failures). I've also
1256 * XXX seen segfaults then, after adding print statements to the
1257 * XXX Python code getting called.
1258 */
1259#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001260 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001261#endif
1262
1263 /* Disable tracemalloc after all Python objects have been destroyed,
1264 so it is possible to use tracemalloc in objects destructor. */
1265 _PyTraceMalloc_Fini();
1266
1267 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1268 _PyImport_Fini();
1269
1270 /* Cleanup typeobject.c's internal caches. */
1271 _PyType_Fini();
1272
1273 /* unload faulthandler module */
1274 _PyFaulthandler_Fini();
1275
1276 /* Debugging stuff */
1277#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001278 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001279#endif
1280 /* dump hash stats */
1281 _PyHash_Fini();
1282
Eric Snowdae02762017-09-14 00:35:58 -07001283#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001284 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001285 _PyDebug_PrintTotalRefs();
1286 }
Eric Snowdae02762017-09-14 00:35:58 -07001287#endif
Nick Coghland6009512014-11-20 21:39:37 +10001288
1289#ifdef Py_TRACE_REFS
1290 /* Display all objects still alive -- this can invoke arbitrary
1291 * __repr__ overrides, so requires a mostly-intact interpreter.
1292 * Alas, a lot of stuff may still be alive now that will be cleaned
1293 * up later.
1294 */
Victor Stinnerda273412017-12-15 01:46:02 +01001295 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001296 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001297 }
Nick Coghland6009512014-11-20 21:39:37 +10001298#endif /* Py_TRACE_REFS */
1299
1300 /* Clear interpreter state and all thread states. */
1301 PyInterpreterState_Clear(interp);
1302
1303 /* Now we decref the exception classes. After this point nothing
1304 can raise an exception. That's okay, because each Fini() method
1305 below has been checked to make sure no exceptions are ever
1306 raised.
1307 */
1308
1309 _PyExc_Fini();
1310
1311 /* Sundry finalizers */
1312 PyMethod_Fini();
1313 PyFrame_Fini();
1314 PyCFunction_Fini();
1315 PyTuple_Fini();
1316 PyList_Fini();
1317 PySet_Fini();
1318 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001319 PyLong_Fini();
1320 PyFloat_Fini();
1321 PyDict_Fini();
1322 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001323 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001324 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001325 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001326 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001327 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001328 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001329
1330 /* Cleanup Unicode implementation */
1331 _PyUnicode_Fini();
1332
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001333 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001334
1335 /* XXX Still allocated:
1336 - various static ad-hoc pointers to interned strings
1337 - int and float free list blocks
1338 - whatever various modules and libraries allocate
1339 */
1340
1341 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1342
1343 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001344 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001345
1346 /* Delete current thread. After this, many C API calls become crashy. */
1347 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001348
Nick Coghland6009512014-11-20 21:39:37 +10001349 PyInterpreterState_Delete(interp);
1350
1351#ifdef Py_TRACE_REFS
1352 /* Display addresses (& refcnts) of all objects still alive.
1353 * An address can be used to find the repr of the object, printed
1354 * above by _Py_PrintReferences.
1355 */
Victor Stinnerda273412017-12-15 01:46:02 +01001356 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001357 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001358 }
Nick Coghland6009512014-11-20 21:39:37 +10001359#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001360#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001361 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001362 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001363 }
Nick Coghland6009512014-11-20 21:39:37 +10001364#endif
1365
Victor Stinner8e91c242019-04-24 17:24:01 +02001366 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001367
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001368 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001369 return status;
1370}
1371
1372void
1373Py_Finalize(void)
1374{
1375 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001376}
1377
1378/* Create and initialize a new interpreter and thread, and return the
1379 new thread. This requires that Py_Initialize() has been called
1380 first.
1381
1382 Unsuccessful initialization yields a NULL pointer. Note that *no*
1383 exception information is available even in this case -- the
1384 exception information is held in the thread, and there is no
1385 thread.
1386
1387 Locking: as above.
1388
1389*/
1390
Victor Stinner331a6a52019-05-27 16:39:22 +02001391static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001392new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001393{
Victor Stinner331a6a52019-05-27 16:39:22 +02001394 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001395
Victor Stinner331a6a52019-05-27 16:39:22 +02001396 status = _PyRuntime_Initialize();
1397 if (_PyStatus_EXCEPTION(status)) {
1398 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001399 }
1400 _PyRuntimeState *runtime = &_PyRuntime;
1401
1402 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001403 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001404 }
Nick Coghland6009512014-11-20 21:39:37 +10001405
Victor Stinner8a1be612016-03-14 22:07:55 +01001406 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1407 interpreters: disable PyGILState_Check(). */
1408 _PyGILState_check_enabled = 0;
1409
Victor Stinner43125222019-04-24 18:23:53 +02001410 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001411 if (interp == NULL) {
1412 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001413 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001414 }
Nick Coghland6009512014-11-20 21:39:37 +10001415
Victor Stinner43125222019-04-24 18:23:53 +02001416 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001417 if (tstate == NULL) {
1418 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001419 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001420 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001421 }
1422
Victor Stinner43125222019-04-24 18:23:53 +02001423 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001424
Eric Snow1abcf672017-05-23 21:46:51 -07001425 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001426 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001427 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001428 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001429 } else {
1430 /* No current thread state, copy from the main interpreter */
1431 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001432 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001433 }
1434
Victor Stinner331a6a52019-05-27 16:39:22 +02001435 status = _PyConfig_Copy(&interp->config, config);
1436 if (_PyStatus_EXCEPTION(status)) {
1437 return status;
Victor Stinnerda273412017-12-15 01:46:02 +01001438 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001439 config = &interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001440
Victor Stinner331a6a52019-05-27 16:39:22 +02001441 status = _PyExc_Init();
1442 if (_PyStatus_EXCEPTION(status)) {
1443 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001444 }
1445
Victor Stinner331a6a52019-05-27 16:39:22 +02001446 status = _PyErr_Init();
1447 if (_PyStatus_EXCEPTION(status)) {
1448 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +02001449 }
1450
1451
Nick Coghland6009512014-11-20 21:39:37 +10001452 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001453 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001454 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001455 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001456 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001457 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001458
Victor Stinner43125222019-04-24 18:23:53 +02001459 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001460 if (sysmod != NULL) {
1461 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001462 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001463 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001464 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001465 Py_INCREF(interp->sysdict);
1466 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner0fd2c302019-06-04 03:15:09 +02001467 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001468 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerab672812019-01-23 15:04:40 +01001469 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001470 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001471 else if (PyErr_Occurred()) {
1472 goto handle_error;
1473 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001474
Victor Stinner43125222019-04-24 18:23:53 +02001475 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001476 if (bimod != NULL) {
1477 interp->builtins = PyModule_GetDict(bimod);
1478 if (interp->builtins == NULL)
1479 goto handle_error;
1480 Py_INCREF(interp->builtins);
1481 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001482 else if (PyErr_Occurred()) {
1483 goto handle_error;
1484 }
Nick Coghland6009512014-11-20 21:39:37 +10001485
Nick Coghland6009512014-11-20 21:39:37 +10001486 if (bimod != NULL && sysmod != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001487 status = _PyBuiltins_AddExceptions(bimod);
1488 if (_PyStatus_EXCEPTION(status)) {
1489 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001490 }
Nick Coghland6009512014-11-20 21:39:37 +10001491
Victor Stinner331a6a52019-05-27 16:39:22 +02001492 status = _PySys_SetPreliminaryStderr(interp->sysdict);
1493 if (_PyStatus_EXCEPTION(status)) {
1494 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001495 }
Nick Coghland6009512014-11-20 21:39:37 +10001496
Victor Stinner331a6a52019-05-27 16:39:22 +02001497 status = _PyImportHooks_Init();
1498 if (_PyStatus_EXCEPTION(status)) {
1499 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001500 }
Nick Coghland6009512014-11-20 21:39:37 +10001501
Victor Stinner331a6a52019-05-27 16:39:22 +02001502 status = init_importlib(interp, sysmod);
1503 if (_PyStatus_EXCEPTION(status)) {
1504 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001505 }
Nick Coghland6009512014-11-20 21:39:37 +10001506
Victor Stinner331a6a52019-05-27 16:39:22 +02001507 status = init_importlib_external(interp);
1508 if (_PyStatus_EXCEPTION(status)) {
1509 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001510 }
Nick Coghland6009512014-11-20 21:39:37 +10001511
Victor Stinnerc5c64252019-09-23 15:59:00 +02001512 status = _PyUnicode_InitEncodings(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001513 if (_PyStatus_EXCEPTION(status)) {
1514 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515 }
1516
Victor Stinner331a6a52019-05-27 16:39:22 +02001517 status = init_sys_streams(interp);
1518 if (_PyStatus_EXCEPTION(status)) {
1519 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001520 }
1521
Victor Stinner331a6a52019-05-27 16:39:22 +02001522 status = add_main_module(interp);
1523 if (_PyStatus_EXCEPTION(status)) {
1524 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001525 }
1526
Victor Stinner331a6a52019-05-27 16:39:22 +02001527 if (config->site_import) {
1528 status = init_import_size();
1529 if (_PyStatus_EXCEPTION(status)) {
1530 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001531 }
1532 }
Nick Coghland6009512014-11-20 21:39:37 +10001533 }
1534
Victor Stinnera7368ac2017-11-15 18:11:45 -08001535 if (PyErr_Occurred()) {
1536 goto handle_error;
1537 }
Nick Coghland6009512014-11-20 21:39:37 +10001538
Victor Stinnera7368ac2017-11-15 18:11:45 -08001539 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001540 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001541
Nick Coghland6009512014-11-20 21:39:37 +10001542handle_error:
1543 /* Oops, it didn't work. Undo it all. */
1544
1545 PyErr_PrintEx(0);
1546 PyThreadState_Clear(tstate);
1547 PyThreadState_Swap(save_tstate);
1548 PyThreadState_Delete(tstate);
1549 PyInterpreterState_Delete(interp);
1550
Victor Stinnera7368ac2017-11-15 18:11:45 -08001551 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001552 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001553}
1554
1555PyThreadState *
1556Py_NewInterpreter(void)
1557{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001558 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001559 PyStatus status = new_interpreter(&tstate);
1560 if (_PyStatus_EXCEPTION(status)) {
1561 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001562 }
1563 return tstate;
1564
Nick Coghland6009512014-11-20 21:39:37 +10001565}
1566
1567/* Delete an interpreter and its last thread. This requires that the
1568 given thread state is current, that the thread has no remaining
1569 frames, and that it is its interpreter's only remaining thread.
1570 It is a fatal error to violate these constraints.
1571
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001572 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001573 everything, regardless.)
1574
1575 Locking: as above.
1576
1577*/
1578
1579void
1580Py_EndInterpreter(PyThreadState *tstate)
1581{
1582 PyInterpreterState *interp = tstate->interp;
1583
Victor Stinner50b48572018-11-01 01:51:40 +01001584 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001585 Py_FatalError("Py_EndInterpreter: thread is not current");
1586 if (tstate->frame != NULL)
1587 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001588 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001589
Eric Snow842a2f02019-03-15 15:47:51 -06001590 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001591 wait_for_thread_shutdown();
1592
Marcel Plch776407f2017-12-20 11:17:58 +01001593 call_py_exitfuncs(interp);
1594
Nick Coghland6009512014-11-20 21:39:37 +10001595 if (tstate != interp->tstate_head || tstate->next != NULL)
1596 Py_FatalError("Py_EndInterpreter: not the last thread");
1597
1598 PyImport_Cleanup();
1599 PyInterpreterState_Clear(interp);
1600 PyThreadState_Swap(NULL);
1601 PyInterpreterState_Delete(interp);
1602}
1603
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001604/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001605
Victor Stinner331a6a52019-05-27 16:39:22 +02001606static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001607add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001608{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001609 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001610 m = PyImport_AddModule("__main__");
1611 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001612 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001613
Nick Coghland6009512014-11-20 21:39:37 +10001614 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001615 ann_dict = PyDict_New();
1616 if ((ann_dict == NULL) ||
1617 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001618 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001619 }
1620 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001621
Nick Coghland6009512014-11-20 21:39:37 +10001622 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1623 PyObject *bimod = PyImport_ImportModule("builtins");
1624 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001625 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001626 }
1627 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001628 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001629 }
1630 Py_DECREF(bimod);
1631 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001632
Nick Coghland6009512014-11-20 21:39:37 +10001633 /* Main is a little special - imp.is_builtin("__main__") will return
1634 * False, but BuiltinImporter is still the most appropriate initial
1635 * setting for its __loader__ attribute. A more suitable value will
1636 * be set if __main__ gets further initialized later in the startup
1637 * process.
1638 */
1639 loader = PyDict_GetItemString(d, "__loader__");
1640 if (loader == NULL || loader == Py_None) {
1641 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1642 "BuiltinImporter");
1643 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001644 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001645 }
1646 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001647 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001648 }
1649 Py_DECREF(loader);
1650 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001651 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001652}
1653
Nick Coghland6009512014-11-20 21:39:37 +10001654/* Import the site module (not into __main__ though) */
1655
Victor Stinner331a6a52019-05-27 16:39:22 +02001656static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001657init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001658{
1659 PyObject *m;
1660 m = PyImport_ImportModule("site");
1661 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001662 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001663 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001664 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001665 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001666}
1667
Victor Stinner874dbe82015-09-04 17:29:57 +02001668/* Check if a file descriptor is valid or not.
1669 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1670static int
1671is_valid_fd(int fd)
1672{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001673/* dup() is faster than fstat(): fstat() can require input/output operations,
1674 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1675 startup. Problem: dup() doesn't check if the file descriptor is valid on
1676 some platforms.
1677
1678 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1679 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1680 EBADF. FreeBSD has similar issue (bpo-32849).
1681
1682 Only use dup() on platforms where dup() is enough to detect invalid FD in
1683 corner cases: on Linux and Windows (bpo-32849). */
1684#if defined(__linux__) || defined(MS_WINDOWS)
1685 if (fd < 0) {
1686 return 0;
1687 }
1688 int fd2;
1689
1690 _Py_BEGIN_SUPPRESS_IPH
1691 fd2 = dup(fd);
1692 if (fd2 >= 0) {
1693 close(fd2);
1694 }
1695 _Py_END_SUPPRESS_IPH
1696
1697 return (fd2 >= 0);
1698#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001699 struct stat st;
1700 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001701#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001702}
1703
1704/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001705static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001706create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001707 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001708 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001709{
1710 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1711 const char* mode;
1712 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001713 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001714 int buffering, isatty;
1715 _Py_IDENTIFIER(open);
1716 _Py_IDENTIFIER(isatty);
1717 _Py_IDENTIFIER(TextIOWrapper);
1718 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001719 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001720
Victor Stinner874dbe82015-09-04 17:29:57 +02001721 if (!is_valid_fd(fd))
1722 Py_RETURN_NONE;
1723
Nick Coghland6009512014-11-20 21:39:37 +10001724 /* stdin is always opened in buffered mode, first because it shouldn't
1725 make a difference in common use cases, second because TextIOWrapper
1726 depends on the presence of a read1() method which only exists on
1727 buffered streams.
1728 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001729 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001730 buffering = 0;
1731 else
1732 buffering = -1;
1733 if (write_mode)
1734 mode = "wb";
1735 else
1736 mode = "rb";
1737 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1738 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001739 Py_None, Py_None, /* encoding, errors */
1740 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001741 if (buf == NULL)
1742 goto error;
1743
1744 if (buffering) {
1745 _Py_IDENTIFIER(raw);
1746 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1747 if (raw == NULL)
1748 goto error;
1749 }
1750 else {
1751 raw = buf;
1752 Py_INCREF(raw);
1753 }
1754
Steve Dower39294992016-08-30 21:22:36 -07001755#ifdef MS_WINDOWS
1756 /* Windows console IO is always UTF-8 encoded */
1757 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001758 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001759#endif
1760
Nick Coghland6009512014-11-20 21:39:37 +10001761 text = PyUnicode_FromString(name);
1762 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1763 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001764 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001765 if (res == NULL)
1766 goto error;
1767 isatty = PyObject_IsTrue(res);
1768 Py_DECREF(res);
1769 if (isatty == -1)
1770 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001771 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001772 write_through = Py_True;
1773 else
1774 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001775 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001776 line_buffering = Py_True;
1777 else
1778 line_buffering = Py_False;
1779
1780 Py_CLEAR(raw);
1781 Py_CLEAR(text);
1782
1783#ifdef MS_WINDOWS
1784 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1785 newlines to "\n".
1786 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1787 newline = NULL;
1788#else
1789 /* sys.stdin: split lines at "\n".
1790 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1791 newline = "\n";
1792#endif
1793
Victor Stinner709d23d2019-05-02 14:56:30 -04001794 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1795 if (encoding_str == NULL) {
1796 Py_CLEAR(buf);
1797 goto error;
1798 }
1799
1800 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1801 if (errors_str == NULL) {
1802 Py_CLEAR(buf);
1803 Py_CLEAR(encoding_str);
1804 goto error;
1805 }
1806
1807 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1808 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001809 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001810 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001811 Py_CLEAR(encoding_str);
1812 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001813 if (stream == NULL)
1814 goto error;
1815
1816 if (write_mode)
1817 mode = "w";
1818 else
1819 mode = "r";
1820 text = PyUnicode_FromString(mode);
1821 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1822 goto error;
1823 Py_CLEAR(text);
1824 return stream;
1825
1826error:
1827 Py_XDECREF(buf);
1828 Py_XDECREF(stream);
1829 Py_XDECREF(text);
1830 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001831
Victor Stinner874dbe82015-09-04 17:29:57 +02001832 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1833 /* Issue #24891: the file descriptor was closed after the first
1834 is_valid_fd() check was called. Ignore the OSError and set the
1835 stream to None. */
1836 PyErr_Clear();
1837 Py_RETURN_NONE;
1838 }
1839 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001840}
1841
1842/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001843static PyStatus
Victor Stinner91106cd2017-12-13 12:29:09 +01001844init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001845{
1846 PyObject *iomod = NULL, *wrapper;
1847 PyObject *bimod = NULL;
1848 PyObject *m;
1849 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001850 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001851 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001852 PyStatus res = _PyStatus_OK();
1853 PyConfig *config = &interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001854
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001855 /* Check that stdin is not a directory
1856 Using shell redirection, you can redirect stdin to a directory,
1857 crashing the Python interpreter. Catch this common mistake here
1858 and output a useful error message. Note that under MS Windows,
1859 the shell already prevents that. */
1860#ifndef MS_WINDOWS
1861 struct _Py_stat_struct sb;
1862 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1863 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001864 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001865 }
1866#endif
1867
Nick Coghland6009512014-11-20 21:39:37 +10001868 /* Hack to avoid a nasty recursion issue when Python is invoked
1869 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1870 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1871 goto error;
1872 }
1873 Py_DECREF(m);
1874
1875 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1876 goto error;
1877 }
1878 Py_DECREF(m);
1879
1880 if (!(bimod = PyImport_ImportModule("builtins"))) {
1881 goto error;
1882 }
1883
1884 if (!(iomod = PyImport_ImportModule("io"))) {
1885 goto error;
1886 }
1887 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1888 goto error;
1889 }
1890
1891 /* Set builtins.open */
1892 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1893 Py_DECREF(wrapper);
1894 goto error;
1895 }
1896 Py_DECREF(wrapper);
1897
Nick Coghland6009512014-11-20 21:39:37 +10001898 /* Set sys.stdin */
1899 fd = fileno(stdin);
1900 /* Under some conditions stdin, stdout and stderr may not be connected
1901 * and fileno() may point to an invalid file descriptor. For example
1902 * GUI apps don't have valid standard streams by default.
1903 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001904 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001905 config->stdio_encoding,
1906 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001907 if (std == NULL)
1908 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001909 PySys_SetObject("__stdin__", std);
1910 _PySys_SetObjectId(&PyId_stdin, std);
1911 Py_DECREF(std);
1912
1913 /* Set sys.stdout */
1914 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001915 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001916 config->stdio_encoding,
1917 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001918 if (std == NULL)
1919 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001920 PySys_SetObject("__stdout__", std);
1921 _PySys_SetObjectId(&PyId_stdout, std);
1922 Py_DECREF(std);
1923
1924#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1925 /* Set sys.stderr, replaces the preliminary stderr */
1926 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001927 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001928 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001929 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001930 if (std == NULL)
1931 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001932
1933 /* Same as hack above, pre-import stderr's codec to avoid recursion
1934 when import.c tries to write to stderr in verbose mode. */
1935 encoding_attr = PyObject_GetAttrString(std, "encoding");
1936 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001937 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001938 if (std_encoding != NULL) {
1939 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1940 Py_XDECREF(codec_info);
1941 }
1942 Py_DECREF(encoding_attr);
1943 }
1944 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1945
1946 if (PySys_SetObject("__stderr__", std) < 0) {
1947 Py_DECREF(std);
1948 goto error;
1949 }
1950 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1951 Py_DECREF(std);
1952 goto error;
1953 }
1954 Py_DECREF(std);
1955#endif
1956
Victor Stinnera7368ac2017-11-15 18:11:45 -08001957 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001958
Victor Stinnera7368ac2017-11-15 18:11:45 -08001959error:
Victor Stinner331a6a52019-05-27 16:39:22 +02001960 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001961
1962done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001963 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001964
Nick Coghland6009512014-11-20 21:39:37 +10001965 Py_XDECREF(bimod);
1966 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001967 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001968}
1969
1970
Victor Stinner10dc4842015-03-24 12:01:30 +01001971static void
Victor Stinner47bbab92019-09-18 14:10:16 +02001972_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
1973 PyThreadState *tstate)
Victor Stinner10dc4842015-03-24 12:01:30 +01001974{
Victor Stinner10dc4842015-03-24 12:01:30 +01001975 fputc('\n', stderr);
1976 fflush(stderr);
1977
1978 /* display the current Python stack */
Victor Stinner47bbab92019-09-18 14:10:16 +02001979 _Py_DumpTracebackThreads(fd, interp, tstate);
Victor Stinner10dc4842015-03-24 12:01:30 +01001980}
Victor Stinner791da1c2016-03-14 16:53:12 +01001981
1982/* Print the current exception (if an exception is set) with its traceback,
1983 or display the current Python stack.
1984
1985 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1986 called on catastrophic cases.
1987
1988 Return 1 if the traceback was displayed, 0 otherwise. */
1989
1990static int
1991_Py_FatalError_PrintExc(int fd)
1992{
1993 PyObject *ferr, *res;
1994 PyObject *exception, *v, *tb;
1995 int has_tb;
1996
Victor Stinner791da1c2016-03-14 16:53:12 +01001997 PyErr_Fetch(&exception, &v, &tb);
1998 if (exception == NULL) {
1999 /* No current exception */
2000 return 0;
2001 }
2002
2003 ferr = _PySys_GetObjectId(&PyId_stderr);
2004 if (ferr == NULL || ferr == Py_None) {
2005 /* sys.stderr is not set yet or set to None,
2006 no need to try to display the exception */
2007 return 0;
2008 }
2009
2010 PyErr_NormalizeException(&exception, &v, &tb);
2011 if (tb == NULL) {
2012 tb = Py_None;
2013 Py_INCREF(tb);
2014 }
2015 PyException_SetTraceback(v, tb);
2016 if (exception == NULL) {
2017 /* PyErr_NormalizeException() failed */
2018 return 0;
2019 }
2020
2021 has_tb = (tb != Py_None);
2022 PyErr_Display(exception, v, tb);
2023 Py_XDECREF(exception);
2024 Py_XDECREF(v);
2025 Py_XDECREF(tb);
2026
2027 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002028 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002029 if (res == NULL)
2030 PyErr_Clear();
2031 else
2032 Py_DECREF(res);
2033
2034 return has_tb;
2035}
2036
Nick Coghland6009512014-11-20 21:39:37 +10002037/* Print fatal error message and abort */
2038
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002039#ifdef MS_WINDOWS
2040static void
2041fatal_output_debug(const char *msg)
2042{
2043 /* buffer of 256 bytes allocated on the stack */
2044 WCHAR buffer[256 / sizeof(WCHAR)];
2045 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2046 size_t msglen;
2047
2048 OutputDebugStringW(L"Fatal Python error: ");
2049
2050 msglen = strlen(msg);
2051 while (msglen) {
2052 size_t i;
2053
2054 if (buflen > msglen) {
2055 buflen = msglen;
2056 }
2057
2058 /* Convert the message to wchar_t. This uses a simple one-to-one
2059 conversion, assuming that the this error message actually uses
2060 ASCII only. If this ceases to be true, we will have to convert. */
2061 for (i=0; i < buflen; ++i) {
2062 buffer[i] = msg[i];
2063 }
2064 buffer[i] = L'\0';
2065 OutputDebugStringW(buffer);
2066
2067 msg += buflen;
2068 msglen -= buflen;
2069 }
2070 OutputDebugStringW(L"\n");
2071}
2072#endif
2073
Victor Stinner47bbab92019-09-18 14:10:16 +02002074
2075static void
2076fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2077{
2078 fprintf(stream, "Python runtime state: ");
2079 if (runtime->finalizing) {
2080 fprintf(stream, "finalizing (tstate=%p)", runtime->finalizing);
2081 }
2082 else if (runtime->initialized) {
2083 fprintf(stream, "initialized");
2084 }
2085 else if (runtime->core_initialized) {
2086 fprintf(stream, "core initialized");
2087 }
2088 else if (runtime->preinitialized) {
2089 fprintf(stream, "preinitialized");
2090 }
2091 else if (runtime->preinitializing) {
2092 fprintf(stream, "preinitializing");
2093 }
2094 else {
2095 fprintf(stream, "unknown");
2096 }
2097 fprintf(stream, "\n");
2098 fflush(stream);
2099}
2100
2101
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002102static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002103fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002104{
Victor Stinner47bbab92019-09-18 14:10:16 +02002105 FILE *stream = stderr;
2106 const int fd = fileno(stream);
Victor Stinner53345a42015-03-25 01:55:14 +01002107 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002108
2109 if (reentrant) {
2110 /* Py_FatalError() caused a second fatal error.
2111 Example: flush_std_files() raises a recursion error. */
2112 goto exit;
2113 }
2114 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002115
Victor Stinner47bbab92019-09-18 14:10:16 +02002116 fprintf(stream, "Fatal Python error: ");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002117 if (prefix) {
Victor Stinner47bbab92019-09-18 14:10:16 +02002118 fputs(prefix, stream);
2119 fputs(": ", stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002120 }
2121 if (msg) {
Victor Stinner47bbab92019-09-18 14:10:16 +02002122 fputs(msg, stream);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002123 }
2124 else {
Victor Stinner47bbab92019-09-18 14:10:16 +02002125 fprintf(stream, "<message not set>");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002126 }
Victor Stinner47bbab92019-09-18 14:10:16 +02002127 fputs("\n", stream);
2128 fflush(stream); /* it helps in Windows debug build */
2129
2130 _PyRuntimeState *runtime = &_PyRuntime;
2131 fatal_error_dump_runtime(stream, runtime);
2132
2133 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2134 PyInterpreterState *interp = NULL;
2135 if (tstate != NULL) {
2136 interp = tstate->interp;
2137 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002138
Victor Stinner3a228ab2018-11-01 00:26:41 +01002139 /* Check if the current thread has a Python thread state
Victor Stinner47bbab92019-09-18 14:10:16 +02002140 and holds the GIL.
Victor Stinner3a228ab2018-11-01 00:26:41 +01002141
Victor Stinner47bbab92019-09-18 14:10:16 +02002142 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2143 has no Python thread state.
2144
2145 tss_tstate != tstate if the current Python thread does not hold the GIL.
2146 */
2147 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2148 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002149 if (has_tstate_and_gil) {
2150 /* If an exception is set, print the exception with its traceback */
2151 if (!_Py_FatalError_PrintExc(fd)) {
2152 /* No exception is set, or an exception is set without traceback */
Victor Stinner47bbab92019-09-18 14:10:16 +02002153 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner3a228ab2018-11-01 00:26:41 +01002154 }
2155 }
2156 else {
Victor Stinner47bbab92019-09-18 14:10:16 +02002157 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002158 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002159
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002160 /* The main purpose of faulthandler is to display the traceback.
2161 This function already did its best to display a traceback.
2162 Disable faulthandler to prevent writing a second traceback
2163 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002164 _PyFaulthandler_Fini();
2165
Victor Stinner791da1c2016-03-14 16:53:12 +01002166 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002167 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002168 /* Flush sys.stdout and sys.stderr */
2169 flush_std_files();
2170 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002171
Nick Coghland6009512014-11-20 21:39:37 +10002172#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002173 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002174#endif /* MS_WINDOWS */
2175
2176exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002177 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002178#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002179 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002180#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002181 abort();
2182 }
2183 else {
2184 exit(status);
2185 }
2186}
2187
Victor Stinner19760862017-12-20 01:41:59 +01002188void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002189Py_FatalError(const char *msg)
2190{
2191 fatal_error(NULL, msg, -1);
2192}
2193
Victor Stinner19760862017-12-20 01:41:59 +01002194void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002195Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002196{
Victor Stinner331a6a52019-05-27 16:39:22 +02002197 if (_PyStatus_IS_EXIT(status)) {
2198 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002199 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002200 else if (_PyStatus_IS_ERROR(status)) {
2201 fatal_error(status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002202 }
2203 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002204 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002205 }
Nick Coghland6009512014-11-20 21:39:37 +10002206}
2207
2208/* Clean up and exit */
2209
Victor Stinnerd7292b52016-06-17 12:29:00 +02002210# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002211
Nick Coghland6009512014-11-20 21:39:37 +10002212/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002213void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002214{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002215 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002216
Antoine Pitroufc5db952017-12-13 02:29:07 +01002217 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002218 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2219
2220 is->pyexitfunc = func;
2221 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002222}
2223
2224static void
Marcel Plch776407f2017-12-20 11:17:58 +01002225call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002226{
Marcel Plch776407f2017-12-20 11:17:58 +01002227 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002228 return;
2229
Marcel Plch776407f2017-12-20 11:17:58 +01002230 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002231 PyErr_Clear();
2232}
2233
2234/* Wait until threading._shutdown completes, provided
2235 the threading module was imported in the first place.
2236 The shutdown routine will wait until all non-daemon
2237 "threading" threads have completed. */
2238static void
2239wait_for_thread_shutdown(void)
2240{
Nick Coghland6009512014-11-20 21:39:37 +10002241 _Py_IDENTIFIER(_shutdown);
2242 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002243 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002244 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002245 if (PyErr_Occurred()) {
2246 PyErr_WriteUnraisable(NULL);
2247 }
2248 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002249 return;
2250 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002251 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002252 if (result == NULL) {
2253 PyErr_WriteUnraisable(threading);
2254 }
2255 else {
2256 Py_DECREF(result);
2257 }
2258 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002259}
2260
2261#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002262int Py_AtExit(void (*func)(void))
2263{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002264 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002265 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002266 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002267 return 0;
2268}
2269
2270static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002271call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002272{
Victor Stinner8e91c242019-04-24 17:24:01 +02002273 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002274 /* pop last function from the list */
2275 runtime->nexitfuncs--;
2276 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2277 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2278
2279 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002280 }
Nick Coghland6009512014-11-20 21:39:37 +10002281
2282 fflush(stdout);
2283 fflush(stderr);
2284}
2285
Victor Stinnercfc88312018-08-01 16:41:25 +02002286void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002287Py_Exit(int sts)
2288{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002289 if (Py_FinalizeEx() < 0) {
2290 sts = 120;
2291 }
Nick Coghland6009512014-11-20 21:39:37 +10002292
2293 exit(sts);
2294}
2295
Victor Stinner331a6a52019-05-27 16:39:22 +02002296static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002297init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002298{
2299#ifdef SIGPIPE
2300 PyOS_setsig(SIGPIPE, SIG_IGN);
2301#endif
2302#ifdef SIGXFZ
2303 PyOS_setsig(SIGXFZ, SIG_IGN);
2304#endif
2305#ifdef SIGXFSZ
2306 PyOS_setsig(SIGXFSZ, SIG_IGN);
2307#endif
2308 PyOS_InitInterrupts(); /* May imply initsignal() */
2309 if (PyErr_Occurred()) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002310 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002311 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002312 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002313}
2314
2315
2316/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2317 *
2318 * All of the code in this function must only use async-signal-safe functions,
2319 * listed at `man 7 signal` or
2320 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2321 */
2322void
2323_Py_RestoreSignals(void)
2324{
2325#ifdef SIGPIPE
2326 PyOS_setsig(SIGPIPE, SIG_DFL);
2327#endif
2328#ifdef SIGXFZ
2329 PyOS_setsig(SIGXFZ, SIG_DFL);
2330#endif
2331#ifdef SIGXFSZ
2332 PyOS_setsig(SIGXFSZ, SIG_DFL);
2333#endif
2334}
2335
2336
2337/*
2338 * The file descriptor fd is considered ``interactive'' if either
2339 * a) isatty(fd) is TRUE, or
2340 * b) the -i flag was given, and the filename associated with
2341 * the descriptor is NULL or "<stdin>" or "???".
2342 */
2343int
2344Py_FdIsInteractive(FILE *fp, const char *filename)
2345{
2346 if (isatty((int)fileno(fp)))
2347 return 1;
2348 if (!Py_InteractiveFlag)
2349 return 0;
2350 return (filename == NULL) ||
2351 (strcmp(filename, "<stdin>") == 0) ||
2352 (strcmp(filename, "???") == 0);
2353}
2354
2355
Nick Coghland6009512014-11-20 21:39:37 +10002356/* Wrappers around sigaction() or signal(). */
2357
2358PyOS_sighandler_t
2359PyOS_getsig(int sig)
2360{
2361#ifdef HAVE_SIGACTION
2362 struct sigaction context;
2363 if (sigaction(sig, NULL, &context) == -1)
2364 return SIG_ERR;
2365 return context.sa_handler;
2366#else
2367 PyOS_sighandler_t handler;
2368/* Special signal handling for the secure CRT in Visual Studio 2005 */
2369#if defined(_MSC_VER) && _MSC_VER >= 1400
2370 switch (sig) {
2371 /* Only these signals are valid */
2372 case SIGINT:
2373 case SIGILL:
2374 case SIGFPE:
2375 case SIGSEGV:
2376 case SIGTERM:
2377 case SIGBREAK:
2378 case SIGABRT:
2379 break;
2380 /* Don't call signal() with other values or it will assert */
2381 default:
2382 return SIG_ERR;
2383 }
2384#endif /* _MSC_VER && _MSC_VER >= 1400 */
2385 handler = signal(sig, SIG_IGN);
2386 if (handler != SIG_ERR)
2387 signal(sig, handler);
2388 return handler;
2389#endif
2390}
2391
2392/*
2393 * All of the code in this function must only use async-signal-safe functions,
2394 * listed at `man 7 signal` or
2395 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2396 */
2397PyOS_sighandler_t
2398PyOS_setsig(int sig, PyOS_sighandler_t handler)
2399{
2400#ifdef HAVE_SIGACTION
2401 /* Some code in Modules/signalmodule.c depends on sigaction() being
2402 * used here if HAVE_SIGACTION is defined. Fix that if this code
2403 * changes to invalidate that assumption.
2404 */
2405 struct sigaction context, ocontext;
2406 context.sa_handler = handler;
2407 sigemptyset(&context.sa_mask);
2408 context.sa_flags = 0;
2409 if (sigaction(sig, &context, &ocontext) == -1)
2410 return SIG_ERR;
2411 return ocontext.sa_handler;
2412#else
2413 PyOS_sighandler_t oldhandler;
2414 oldhandler = signal(sig, handler);
2415#ifdef HAVE_SIGINTERRUPT
2416 siginterrupt(sig, 1);
2417#endif
2418 return oldhandler;
2419#endif
2420}
2421
2422#ifdef __cplusplus
2423}
2424#endif