blob: 014b19aa8aa5fae24a63e9ee34050e2be6aa8de0 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner09532fe2019-05-10 23:39:09 +02007#include "pycore_ceval.h"
Victor Stinner99fcc612019-04-29 13:04:07 +02008#include "pycore_context.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02009#include "pycore_coreconfig.h"
Victor Stinner353933e2018-11-23 13:08:26 +010010#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010011#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010012#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010013#include "pycore_pylifecycle.h"
14#include "pycore_pymem.h"
15#include "pycore_pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100016#include "grammar.h"
17#include "node.h"
18#include "token.h"
19#include "parsetok.h"
20#include "errcode.h"
21#include "code.h"
22#include "symtable.h"
23#include "ast.h"
24#include "marshal.h"
25#include "osdefs.h"
26#include <locale.h>
27
28#ifdef HAVE_SIGNAL_H
29#include <signal.h>
30#endif
31
32#ifdef MS_WINDOWS
33#include "malloc.h" /* for alloca */
34#endif
35
36#ifdef HAVE_LANGINFO_H
37#include <langinfo.h>
38#endif
39
40#ifdef MS_WINDOWS
41#undef BYTE
42#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070043
44extern PyTypeObject PyWindowsConsoleIO_Type;
45#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100046#endif
47
48_Py_IDENTIFIER(flush);
49_Py_IDENTIFIER(name);
50_Py_IDENTIFIER(stdin);
51_Py_IDENTIFIER(stdout);
52_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060053_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100054
55#ifdef __cplusplus
56extern "C" {
57#endif
58
Nick Coghland6009512014-11-20 21:39:37 +100059extern grammar _PyParser_Grammar; /* From graminit.c */
60
61/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080062static _PyInitError add_main_module(PyInterpreterState *interp);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040063static _PyInitError init_import_size(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010064static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040065static _PyInitError init_signals(void);
Marcel Plch776407f2017-12-20 11:17:58 +010066static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100067static void wait_for_thread_shutdown(void);
Victor Stinner8e91c242019-04-24 17:24:01 +020068static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100069
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080070int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010072static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075_PyRuntime_Initialize(void)
76{
77 /* XXX We only initialize once in the process, which aligns with
78 the static initialization of the former globals now found in
79 _PyRuntime. However, _PyRuntime *should* be initialized with
80 every Py_Initialize() call, but doing so breaks the runtime.
81 This is because the runtime state is not properly finalized
82 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010083 if (runtime_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084 return _Py_INIT_OK();
85 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010086 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087
88 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
90
91void
92_PyRuntime_Finalize(void)
93{
94 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010095 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
97
98int
99_Py_IsFinalizing(void)
100{
101 return _PyRuntime.finalizing != NULL;
102}
103
Nick Coghland6009512014-11-20 21:39:37 +1000104/* Hack to force loading of object files */
105int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
106 PyOS_mystrnicmp; /* Python/pystrcmp.o */
107
108/* PyModule_GetWarningsModule is no longer necessary as of 2.6
109since _warnings is builtin. This API should not be used. */
110PyObject *
111PyModule_GetWarningsModule(void)
112{
113 return PyImport_ImportModule("warnings");
114}
115
Eric Snowc7ec9982017-05-23 23:00:52 -0700116
Eric Snow1abcf672017-05-23 21:46:51 -0700117/* APIs to access the initialization flags
118 *
119 * Can be called prior to Py_Initialize.
120 */
Nick Coghland6009512014-11-20 21:39:37 +1000121
Eric Snow1abcf672017-05-23 21:46:51 -0700122int
123_Py_IsCoreInitialized(void)
124{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600125 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700126}
Nick Coghland6009512014-11-20 21:39:37 +1000127
128int
129Py_IsInitialized(void)
130{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600131 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000132}
133
Nick Coghlan6ea41862017-06-11 13:16:15 +1000134
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000135/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
136 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000137 initializations fail, a fatal error is issued and the function does
138 not return. On return, the first thread and interpreter state have
139 been created.
140
141 Locking: you must hold the interpreter lock while calling this.
142 (If the lock has not yet been initialized, that's equivalent to
143 having the lock, but you cannot use multiple threads.)
144
145*/
146
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800147static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400148init_importlib(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000149{
150 PyObject *importlib;
151 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000152 PyObject *value;
153
154 /* Import _importlib through its frozen version, _frozen_importlib. */
155 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800156 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000157 }
158 else if (Py_VerboseFlag) {
159 PySys_FormatStderr("import _frozen_importlib # frozen\n");
160 }
161 importlib = PyImport_AddModule("_frozen_importlib");
162 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800163 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000164 }
165 interp->importlib = importlib;
166 Py_INCREF(interp->importlib);
167
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300168 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
169 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800170 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300171 Py_INCREF(interp->import_func);
172
Victor Stinnercd6e6942015-09-18 09:11:57 +0200173 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800174 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000175 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800176 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000177 }
178 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200179 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000180 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600181 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800182 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000183 }
184
Victor Stinnercd6e6942015-09-18 09:11:57 +0200185 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000186 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
187 if (value == NULL) {
188 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800189 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000190 }
191 Py_DECREF(value);
192 Py_DECREF(impmod);
193
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800194 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000195}
196
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800197static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400198init_importlib_external(PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700199{
200 PyObject *value;
201 value = PyObject_CallMethod(interp->importlib,
202 "_install_external_importers", "");
203 if (value == NULL) {
204 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800205 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700206 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200207 Py_DECREF(value);
Victor Stinner410b85a2019-05-13 17:12:45 +0200208 return _PyImportZip_Init(interp);
Eric Snow1abcf672017-05-23 21:46:51 -0700209}
Nick Coghland6009512014-11-20 21:39:37 +1000210
Nick Coghlan6ea41862017-06-11 13:16:15 +1000211/* Helper functions to better handle the legacy C locale
212 *
213 * The legacy C locale assumes ASCII as the default text encoding, which
214 * causes problems not only for the CPython runtime, but also other
215 * components like GNU readline.
216 *
217 * Accordingly, when the CLI detects it, it attempts to coerce it to a
218 * more capable UTF-8 based alternative as follows:
219 *
220 * if (_Py_LegacyLocaleDetected()) {
221 * _Py_CoerceLegacyLocale();
222 * }
223 *
224 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
225 *
226 * Locale coercion also impacts the default error handler for the standard
227 * streams: while the usual default is "strict", the default for the legacy
228 * C locale and for any of the coercion target locales is "surrogateescape".
229 */
230
231int
232_Py_LegacyLocaleDetected(void)
233{
234#ifndef MS_WINDOWS
235 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000236 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
237 * the POSIX locale as a simple alias for the C locale, so
238 * we may also want to check for that explicitly.
239 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000240 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
241 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
242#else
243 /* Windows uses code pages instead of locales, so no locale is legacy */
244 return 0;
245#endif
246}
247
Nick Coghlaneb817952017-06-18 12:29:42 +1000248static const char *_C_LOCALE_WARNING =
249 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
250 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
251 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
252 "locales is recommended.\n";
253
Nick Coghlaneb817952017-06-18 12:29:42 +1000254static void
Victor Stinner43125222019-04-24 18:23:53 +0200255emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000256{
Victor Stinner43125222019-04-24 18:23:53 +0200257 const _PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner20004952019-03-26 02:31:11 +0100258 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200259 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000260 }
261}
262
Nick Coghlan6ea41862017-06-11 13:16:15 +1000263typedef struct _CandidateLocale {
264 const char *locale_name; /* The locale to try as a coercion target */
265} _LocaleCoercionTarget;
266
267static _LocaleCoercionTarget _TARGET_LOCALES[] = {
268 {"C.UTF-8"},
269 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000270 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000271 {NULL}
272};
273
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200274
275int
276_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000277{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200278 const _LocaleCoercionTarget *target = NULL;
279 for (target = _TARGET_LOCALES; target->locale_name; target++) {
280 if (strcmp(ctype_loc, target->locale_name) == 0) {
281 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200283 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200284 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000285}
286
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200287
Nick Coghlan6ea41862017-06-11 13:16:15 +1000288#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100289static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000290 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
291 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
292
293static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200294_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295{
296 const char *newloc = target->locale_name;
297
298 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100299 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300
301 /* Set the relevant locale environment variable */
302 if (setenv("LC_CTYPE", newloc, 1)) {
303 fprintf(stderr,
304 "Error setting LC_CTYPE, skipping C locale coercion\n");
305 return;
306 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200307 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100308 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000309 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000310
311 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100312 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313}
314#endif
315
316void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200317_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318{
319#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200320 char *oldloc = NULL;
321
322 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
323 if (oldloc == NULL) {
324 return;
325 }
326
Victor Stinner94540602017-12-16 04:54:22 +0100327 const char *locale_override = getenv("LC_ALL");
328 if (locale_override == NULL || *locale_override == '\0') {
329 /* LC_ALL is also not set (or is set to an empty string) */
330 const _LocaleCoercionTarget *target = NULL;
331 for (target = _TARGET_LOCALES; target->locale_name; target++) {
332 const char *new_locale = setlocale(LC_CTYPE,
333 target->locale_name);
334 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400335#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100336 /* Also ensure that nl_langinfo works in this locale */
337 char *codeset = nl_langinfo(CODESET);
338 if (!codeset || *codeset == '\0') {
339 /* CODESET is not set or empty, so skip coercion */
340 new_locale = NULL;
341 _Py_SetLocaleFromEnv(LC_CTYPE);
342 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000343 }
Victor Stinner94540602017-12-16 04:54:22 +0100344#endif
345 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200346 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200347 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000348 }
349 }
350 }
351 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200352
353 setlocale(LC_CTYPE, oldloc);
354
355done:
356 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000357#endif
358}
359
xdegaye1588be62017-11-12 12:45:59 +0100360/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
361 * isolate the idiosyncrasies of different libc implementations. It reads the
362 * appropriate environment variable and uses its value to select the locale for
363 * 'category'. */
364char *
365_Py_SetLocaleFromEnv(int category)
366{
Victor Stinner353933e2018-11-23 13:08:26 +0100367 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100368#ifdef __ANDROID__
369 const char *locale;
370 const char **pvar;
371#ifdef PY_COERCE_C_LOCALE
372 const char *coerce_c_locale;
373#endif
374 const char *utf8_locale = "C.UTF-8";
375 const char *env_var_set[] = {
376 "LC_ALL",
377 "LC_CTYPE",
378 "LANG",
379 NULL,
380 };
381
382 /* Android setlocale(category, "") doesn't check the environment variables
383 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
384 * check the environment variables listed in env_var_set. */
385 for (pvar=env_var_set; *pvar; pvar++) {
386 locale = getenv(*pvar);
387 if (locale != NULL && *locale != '\0') {
388 if (strcmp(locale, utf8_locale) == 0 ||
389 strcmp(locale, "en_US.UTF-8") == 0) {
390 return setlocale(category, utf8_locale);
391 }
392 return setlocale(category, "C");
393 }
394 }
395
396 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
397 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
398 * Quote from POSIX section "8.2 Internationalization Variables":
399 * "4. If the LANG environment variable is not set or is set to the empty
400 * string, the implementation-defined default locale shall be used." */
401
402#ifdef PY_COERCE_C_LOCALE
403 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
404 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
405 /* Some other ported code may check the environment variables (e.g. in
406 * extension modules), so we make sure that they match the locale
407 * configuration */
408 if (setenv("LC_CTYPE", utf8_locale, 1)) {
409 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
410 "environment variable to %s\n", utf8_locale);
411 }
412 }
413#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100414 res = setlocale(category, utf8_locale);
415#else /* !defined(__ANDROID__) */
416 res = setlocale(category, "");
417#endif
418 _Py_ResetForceASCII();
419 return res;
xdegaye1588be62017-11-12 12:45:59 +0100420}
421
Nick Coghlan6ea41862017-06-11 13:16:15 +1000422
Eric Snow1abcf672017-05-23 21:46:51 -0700423/* Global initializations. Can be undone by Py_Finalize(). Don't
424 call this twice without an intervening Py_Finalize() call.
425
Victor Stinner484f20d2019-03-27 02:04:16 +0100426 Every call to _Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700427 must have a corresponding call to Py_Finalize.
428
429 Locking: you must hold the interpreter lock while calling these APIs.
430 (If the lock has not yet been initialized, that's equivalent to
431 having the lock, but you cannot use multiple threads.)
432
433*/
434
Victor Stinner1dc6e392018-07-25 02:49:17 +0200435static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200436_Py_Initialize_ReconfigureCore(_PyRuntimeState *runtime,
437 PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200438 const _PyCoreConfig *core_config)
439{
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200440 _PyInitError err;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100441 PyThreadState *tstate = _PyThreadState_GET();
442 if (!tstate) {
443 return _Py_INIT_ERR("failed to read thread state");
444 }
445
446 PyInterpreterState *interp = tstate->interp;
447 if (interp == NULL) {
448 return _Py_INIT_ERR("can't make main interpreter");
449 }
450 *interp_p = interp;
451
Victor Stinner43125222019-04-24 18:23:53 +0200452 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200453
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200454 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
455 if (_Py_INIT_FAILED(err)) {
456 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200457 }
458 core_config = &interp->core_config;
459
460 if (core_config->_install_importlib) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200461 err = _PyCoreConfig_SetPathConfig(core_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200462 if (_Py_INIT_FAILED(err)) {
463 return err;
464 }
465 }
466 return _Py_INIT_OK();
467}
468
469
Victor Stinner1dc6e392018-07-25 02:49:17 +0200470static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200471pycore_init_runtime(_PyRuntimeState *runtime,
472 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000473{
Victor Stinner43125222019-04-24 18:23:53 +0200474 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200475 return _Py_INIT_ERR("main interpreter already initialized");
476 }
Victor Stinnerda273412017-12-15 01:46:02 +0100477
Victor Stinner43125222019-04-24 18:23:53 +0200478 _PyCoreConfig_Write(core_config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600479
Eric Snow1abcf672017-05-23 21:46:51 -0700480 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
481 * threads behave a little more gracefully at interpreter shutdown.
482 * We clobber it here so the new interpreter can start with a clean
483 * slate.
484 *
485 * However, this may still lead to misbehaviour if there are daemon
486 * threads still hanging around from a previous Py_Initialize/Finalize
487 * pair :(
488 */
Victor Stinner43125222019-04-24 18:23:53 +0200489 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600490
Victor Stinner43125222019-04-24 18:23:53 +0200491 _PyInitError err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800492 if (_Py_INIT_FAILED(err)) {
493 return err;
494 }
495
Victor Stinner43125222019-04-24 18:23:53 +0200496 err = _PyInterpreterState_Enable(runtime);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800497 if (_Py_INIT_FAILED(err)) {
498 return err;
499 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100500 return _Py_INIT_OK();
501}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800502
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100503
504static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200505pycore_create_interpreter(_PyRuntimeState *runtime,
506 const _PyCoreConfig *core_config,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100507 PyInterpreterState **interp_p)
508{
509 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100510 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800511 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100512 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200513 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100514
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200515 _PyInitError err = _PyCoreConfig_Copy(&interp->core_config, core_config);
516 if (_Py_INIT_FAILED(err)) {
517 return err;
Victor Stinnerda273412017-12-15 01:46:02 +0100518 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200519 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000520
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200521 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000522 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800523 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000524 (void) PyThreadState_Swap(tstate);
525
Victor Stinner99fcc612019-04-29 13:04:07 +0200526 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
527 destroying the GIL might fail when it is being referenced from
528 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000529 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000530 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner09532fe2019-05-10 23:39:09 +0200531 _PyEval_FiniThreads(&runtime->ceval);
Victor Stinner2914bb32018-01-29 11:57:45 +0100532
Nick Coghland6009512014-11-20 21:39:37 +1000533 /* Auto-thread-state API */
Victor Stinner43125222019-04-24 18:23:53 +0200534 _PyGILState_Init(runtime, interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000535
Victor Stinner2914bb32018-01-29 11:57:45 +0100536 /* Create the GIL */
537 PyEval_InitThreads();
538
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100539 return _Py_INIT_OK();
540}
Nick Coghland6009512014-11-20 21:39:37 +1000541
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100542
543static _PyInitError
544pycore_init_types(void)
545{
Victor Stinnerab672812019-01-23 15:04:40 +0100546 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100547 if (_Py_INIT_FAILED(err)) {
548 return err;
549 }
550
551 err = _PyUnicode_Init();
552 if (_Py_INIT_FAILED(err)) {
553 return err;
554 }
555
556 if (_PyStructSequence_Init() < 0) {
557 return _Py_INIT_ERR("can't initialize structseq");
558 }
559
560 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800561 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100562 }
Nick Coghland6009512014-11-20 21:39:37 +1000563
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100564 err = _PyExc_Init();
565 if (_Py_INIT_FAILED(err)) {
566 return err;
567 }
568
569 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800570 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100571 }
Nick Coghland6009512014-11-20 21:39:37 +1000572
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573 if (!_PyContext_Init()) {
574 return _Py_INIT_ERR("can't init context");
575 }
576 return _Py_INIT_OK();
577}
578
579
580static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100581pycore_init_builtins(PyInterpreterState *interp)
582{
583 PyObject *bimod = _PyBuiltin_Init();
584 if (bimod == NULL) {
585 return _Py_INIT_ERR("can't initialize builtins modules");
586 }
587 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
588
589 interp->builtins = PyModule_GetDict(bimod);
590 if (interp->builtins == NULL) {
591 return _Py_INIT_ERR("can't initialize builtins dict");
592 }
593 Py_INCREF(interp->builtins);
594
595 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
596 if (_Py_INIT_FAILED(err)) {
597 return err;
598 }
599 return _Py_INIT_OK();
600}
601
602
603static _PyInitError
604pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
605{
606 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800607 if (_Py_INIT_FAILED(err)) {
608 return err;
609 }
Nick Coghland6009512014-11-20 21:39:37 +1000610
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800611 err = _PyImportHooks_Init();
612 if (_Py_INIT_FAILED(err)) {
613 return err;
614 }
Nick Coghland6009512014-11-20 21:39:37 +1000615
616 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100617 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100618 return _Py_INIT_ERR("can't initialize warnings");
619 }
Nick Coghland6009512014-11-20 21:39:37 +1000620
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100621 if (interp->core_config._install_importlib) {
622 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200623 if (_Py_INIT_FAILED(err)) {
624 return err;
625 }
626 }
627
Eric Snow1abcf672017-05-23 21:46:51 -0700628 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100629 if (interp->core_config._install_importlib) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400630 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800631 if (_Py_INIT_FAILED(err)) {
632 return err;
633 }
Eric Snow1abcf672017-05-23 21:46:51 -0700634 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100635 return _Py_INIT_OK();
636}
637
638
639static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200640_Py_InitializeCore_impl(_PyRuntimeState *runtime,
641 PyInterpreterState **interp_p,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100642 const _PyCoreConfig *core_config)
643{
644 PyInterpreterState *interp;
645
Victor Stinner43125222019-04-24 18:23:53 +0200646 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100647
Victor Stinner43125222019-04-24 18:23:53 +0200648 _PyInitError err = pycore_init_runtime(runtime, core_config);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100649 if (_Py_INIT_FAILED(err)) {
650 return err;
651 }
652
Victor Stinner43125222019-04-24 18:23:53 +0200653 err = pycore_create_interpreter(runtime, core_config, &interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100654 if (_Py_INIT_FAILED(err)) {
655 return err;
656 }
657 core_config = &interp->core_config;
658 *interp_p = interp;
659
660 err = pycore_init_types();
661 if (_Py_INIT_FAILED(err)) {
662 return err;
663 }
664
665 PyObject *sysmod;
Victor Stinner43125222019-04-24 18:23:53 +0200666 err = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100667 if (_Py_INIT_FAILED(err)) {
668 return err;
669 }
670
671 err = pycore_init_builtins(interp);
672 if (_Py_INIT_FAILED(err)) {
673 return err;
674 }
675
676 err = pycore_init_import_warnings(interp, sysmod);
677 if (_Py_INIT_FAILED(err)) {
678 return err;
679 }
Eric Snow1abcf672017-05-23 21:46:51 -0700680
681 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200682 runtime->core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800683 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700684}
685
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100686
Victor Stinner70005ac2019-05-02 15:25:34 -0400687_PyInitError
688_Py_PreInitializeFromPyArgv(const _PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100689{
690 _PyInitError err;
691
692 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100693 if (_Py_INIT_FAILED(err)) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100694 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100695 }
Victor Stinner43125222019-04-24 18:23:53 +0200696 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100697
Victor Stinner43125222019-04-24 18:23:53 +0200698 if (runtime->pre_initialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100699 /* If it's already configured: ignored the new configuration */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100700 return _Py_INIT_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100701 }
702
Victor Stinner5ac27a52019-03-27 13:40:14 +0100703 _PyPreConfig config = _PyPreConfig_INIT;
704
Victor Stinnerf72346c2019-03-25 17:54:58 +0100705 if (src_config) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100706 if (_PyPreConfig_Copy(&config, src_config) < 0) {
707 err = _Py_INIT_NO_MEMORY();
Victor Stinner20004952019-03-26 02:31:11 +0100708 goto done;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100709 }
710 }
711
Victor Stinner5ac27a52019-03-27 13:40:14 +0100712 err = _PyPreConfig_Read(&config, args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100713 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100714 goto done;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100715 }
716
Victor Stinner5ac27a52019-03-27 13:40:14 +0100717 err = _PyPreConfig_Write(&config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100718 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100719 goto done;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100720 }
721
Victor Stinner43125222019-04-24 18:23:53 +0200722 runtime->pre_initialized = 1;
Victor Stinner20004952019-03-26 02:31:11 +0100723 err = _Py_INIT_OK();
724
725done:
Victor Stinner5ac27a52019-03-27 13:40:14 +0100726 _PyPreConfig_Clear(&config);
Victor Stinner20004952019-03-26 02:31:11 +0100727 return err;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100728}
729
Victor Stinner70005ac2019-05-02 15:25:34 -0400730
Victor Stinnerf72346c2019-03-25 17:54:58 +0100731_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100732_Py_PreInitializeFromArgs(const _PyPreConfig *src_config, int argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100733{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100734 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400735 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100736}
737
738
739_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100740_Py_PreInitializeFromWideArgs(const _PyPreConfig *src_config, int argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100741{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100742 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400743 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100744}
745
746
747_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100748_Py_PreInitialize(const _PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100749{
Victor Stinner70005ac2019-05-02 15:25:34 -0400750 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100751}
752
753
754_PyInitError
Victor Stinner70005ac2019-05-02 15:25:34 -0400755_Py_PreInitializeFromCoreConfig(const _PyCoreConfig *coreconfig,
756 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100757{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100758 _PyPreConfig config = _PyPreConfig_INIT;
Victor Stinner70005ac2019-05-02 15:25:34 -0400759 if (coreconfig != NULL) {
760 _PyCoreConfig_GetCoreConfig(&config, coreconfig);
761 }
762 return _Py_PreInitializeFromPyArgv(&config, args);
Victor Stinner5ac27a52019-03-27 13:40:14 +0100763 /* No need to clear config:
764 _PyCoreConfig_GetCoreConfig() doesn't allocate memory */
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100765}
766
767
768static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200769pyinit_coreconfig(_PyRuntimeState *runtime,
770 _PyCoreConfig *config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100771 const _PyCoreConfig *src_config,
772 const _PyArgv *args,
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100773 PyInterpreterState **interp_p)
774{
Victor Stinner5f38b842019-05-01 02:30:12 +0200775 _PyInitError err;
776
Victor Stinnerd929f182019-03-27 18:28:46 +0100777 if (src_config) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200778 err = _PyCoreConfig_Copy(config, src_config);
779 if (_Py_INIT_FAILED(err)) {
780 return err;
Victor Stinnerd929f182019-03-27 18:28:46 +0100781 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100782 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100783
Victor Stinner5f38b842019-05-01 02:30:12 +0200784 if (args) {
785 err = _PyCoreConfig_SetPyArgv(config, args);
786 if (_Py_INIT_FAILED(err)) {
787 return err;
788 }
789 }
790
791 err = _PyCoreConfig_Read(config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100792 if (_Py_INIT_FAILED(err)) {
793 return err;
794 }
795
Victor Stinner43125222019-04-24 18:23:53 +0200796 if (!runtime->core_initialized) {
797 return _Py_InitializeCore_impl(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100798 }
799 else {
Victor Stinner43125222019-04-24 18:23:53 +0200800 return _Py_Initialize_ReconfigureCore(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100801 }
802}
803
804
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100805/* Begin interpreter initialization
806 *
807 * On return, the first thread and interpreter state have been created,
808 * but the compiler, signal handling, multithreading and
809 * multiple interpreter support, and codec infrastructure are not yet
810 * available.
811 *
812 * The import system will support builtin and frozen modules only.
813 * The only supported io is writing to sys.stderr
814 *
815 * If any operation invoked by this function fails, a fatal error is
816 * issued and the function does not return.
817 *
818 * Any code invoked from this function should *not* assume it has access
819 * to the Python C API (unless the API is explicitly listed as being
820 * safe to call without calling Py_Initialize first)
821 */
Victor Stinner484f20d2019-03-27 02:04:16 +0100822static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200823_Py_InitializeCore(_PyRuntimeState *runtime,
824 const _PyCoreConfig *src_config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100825 const _PyArgv *args,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100826 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200827{
Victor Stinnerd929f182019-03-27 18:28:46 +0100828 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200829
Victor Stinner70005ac2019-05-02 15:25:34 -0400830 err = _Py_PreInitializeFromCoreConfig(src_config, args);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200831 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100832 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200833 }
834
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100835 _PyCoreConfig local_config = _PyCoreConfig_INIT;
Victor Stinner43125222019-04-24 18:23:53 +0200836 err = pyinit_coreconfig(runtime, &local_config, src_config, args, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100837 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200838 return err;
839}
840
Victor Stinner5ac27a52019-03-27 13:40:14 +0100841
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200842/* Py_Initialize() has already been called: update the main interpreter
843 configuration. Example of bpo-34008: Py_Main() called after
844 Py_Initialize(). */
845static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100846_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200847{
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100848 _PyCoreConfig *core_config = &interp->core_config;
849
850 PyObject *argv = _PyWstrList_AsList(&core_config->argv);
851 if (argv == NULL) {
852 return _Py_INIT_NO_MEMORY(); \
853 }
854
855 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
856 Py_DECREF(argv);
857 if (res < 0) {
858 return _Py_INIT_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200859 }
860 return _Py_INIT_OK();
861}
862
Eric Snowc7ec9982017-05-23 23:00:52 -0700863/* Update interpreter state based on supplied configuration settings
864 *
865 * After calling this function, most of the restrictions on the interpreter
866 * are lifted. The only remaining incomplete settings are those related
867 * to the main module (sys.argv[0], __main__ metadata)
868 *
869 * Calling this when the interpreter is not initializing, is already
870 * initialized or without a valid current thread state is a fatal error.
871 * Other errors should be reported as normal Python exceptions with a
872 * non-zero return code.
873 */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100874static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200875_Py_InitializeMainInterpreter(_PyRuntimeState *runtime,
876 PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700877{
Victor Stinner43125222019-04-24 18:23:53 +0200878 if (!runtime->core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800879 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700880 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700881
Victor Stinner1dc6e392018-07-25 02:49:17 +0200882 /* Configure the main interpreter */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200883 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700884
Victor Stinner43125222019-04-24 18:23:53 +0200885 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100886 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200887 }
888
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200889 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700890 /* Special mode for freeze_importlib: run with no import system
891 *
892 * This means anything which needs support from extension modules
893 * or pure Python code in the standard library won't work.
894 */
Victor Stinner43125222019-04-24 18:23:53 +0200895 runtime->initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800896 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700897 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100898
Victor Stinner33c377e2017-12-05 15:12:41 +0100899 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800900 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100901 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200902
Victor Stinner43125222019-04-24 18:23:53 +0200903 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800904 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100905 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800906
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400907 _PyInitError err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800908 if (_Py_INIT_FAILED(err)) {
909 return err;
910 }
Nick Coghland6009512014-11-20 21:39:37 +1000911
912 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200913 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800914 if (_Py_INIT_FAILED(err)) {
915 return err;
916 }
Nick Coghland6009512014-11-20 21:39:37 +1000917
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400918 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800919 if (_Py_INIT_FAILED(err)) {
920 return err;
921 }
Nick Coghland6009512014-11-20 21:39:37 +1000922
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100923 if (core_config->install_signal_handlers) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400924 err = init_signals();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800925 if (_Py_INIT_FAILED(err)) {
926 return err;
927 }
928 }
Nick Coghland6009512014-11-20 21:39:37 +1000929
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200930 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200932 }
Nick Coghland6009512014-11-20 21:39:37 +1000933
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800934 err = add_main_module(interp);
935 if (_Py_INIT_FAILED(err)) {
936 return err;
937 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800938
Victor Stinner91106cd2017-12-13 12:29:09 +0100939 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800940 if (_Py_INIT_FAILED(err)) {
941 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800942 }
Nick Coghland6009512014-11-20 21:39:37 +1000943
944 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100945 PyObject *warnoptions = PySys_GetObject("warnoptions");
946 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100947 {
Nick Coghland6009512014-11-20 21:39:37 +1000948 PyObject *warnings_module = PyImport_ImportModule("warnings");
949 if (warnings_module == NULL) {
950 fprintf(stderr, "'import warnings' failed; traceback:\n");
951 PyErr_Print();
952 }
953 Py_XDECREF(warnings_module);
954 }
955
Victor Stinner43125222019-04-24 18:23:53 +0200956 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700957
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200958 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400959 err = init_import_size(); /* Module site */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800960 if (_Py_INIT_FAILED(err)) {
961 return err;
962 }
963 }
Victor Stinnercf215042018-08-29 22:56:06 +0200964
965#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200966 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200967#endif
968
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800969 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000970}
971
Eric Snowc7ec9982017-05-23 23:00:52 -0700972#undef _INIT_DEBUG_PRINT
973
Victor Stinner5ac27a52019-03-27 13:40:14 +0100974static _PyInitError
975init_python(const _PyCoreConfig *config, const _PyArgv *args)
Eric Snow1abcf672017-05-23 21:46:51 -0700976{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800977 _PyInitError err;
Victor Stinner43125222019-04-24 18:23:53 +0200978
979 err = _PyRuntime_Initialize();
980 if (_Py_INIT_FAILED(err)) {
981 return err;
982 }
983 _PyRuntimeState *runtime = &_PyRuntime;
984
985 PyInterpreterState *interp = NULL;
986 err = _Py_InitializeCore(runtime, config, args, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800987 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200988 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800989 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200990 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100991
Victor Stinner4631da12019-05-02 15:30:21 -0400992 if (!config->_frozen) {
Victor Stinner43125222019-04-24 18:23:53 +0200993 err = _Py_InitializeMainInterpreter(runtime, interp);
Victor Stinner484f20d2019-03-27 02:04:16 +0100994 if (_Py_INIT_FAILED(err)) {
995 return err;
996 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800997 }
Victor Stinner484f20d2019-03-27 02:04:16 +0100998
Victor Stinner1dc6e392018-07-25 02:49:17 +0200999 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001000}
1001
1002
Victor Stinner5ac27a52019-03-27 13:40:14 +01001003_PyInitError
1004_Py_InitializeFromArgs(const _PyCoreConfig *config, int argc, char **argv)
1005{
1006 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1007 return init_python(config, &args);
1008}
1009
1010
1011_PyInitError
1012_Py_InitializeFromWideArgs(const _PyCoreConfig *config, int argc, wchar_t **argv)
1013{
1014 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1015 return init_python(config, &args);
1016}
1017
1018
1019_PyInitError
1020_Py_InitializeFromConfig(const _PyCoreConfig *config)
1021{
1022 return init_python(config, NULL);
1023}
1024
1025
Eric Snow1abcf672017-05-23 21:46:51 -07001026void
Nick Coghland6009512014-11-20 21:39:37 +10001027Py_InitializeEx(int install_sigs)
1028{
Victor Stinner43125222019-04-24 18:23:53 +02001029 _PyInitError err;
1030
1031 err = _PyRuntime_Initialize();
1032 if (_Py_INIT_FAILED(err)) {
1033 _Py_ExitInitError(err);
1034 }
1035 _PyRuntimeState *runtime = &_PyRuntime;
1036
1037 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001038 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1039 return;
1040 }
1041
Victor Stinner1dc6e392018-07-25 02:49:17 +02001042 _PyCoreConfig config = _PyCoreConfig_INIT;
1043 config.install_signal_handlers = install_sigs;
1044
Victor Stinner43125222019-04-24 18:23:53 +02001045 err = _Py_InitializeFromConfig(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001046 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001047 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001048 }
Nick Coghland6009512014-11-20 21:39:37 +10001049}
1050
1051void
1052Py_Initialize(void)
1053{
1054 Py_InitializeEx(1);
1055}
1056
1057
1058#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001059extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001060#endif
1061
1062/* Flush stdout and stderr */
1063
1064static int
1065file_is_closed(PyObject *fobj)
1066{
1067 int r;
1068 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1069 if (tmp == NULL) {
1070 PyErr_Clear();
1071 return 0;
1072 }
1073 r = PyObject_IsTrue(tmp);
1074 Py_DECREF(tmp);
1075 if (r < 0)
1076 PyErr_Clear();
1077 return r > 0;
1078}
1079
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001080static int
Nick Coghland6009512014-11-20 21:39:37 +10001081flush_std_files(void)
1082{
1083 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1084 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1085 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001086 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001087
1088 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001089 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001090 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001091 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001092 status = -1;
1093 }
Nick Coghland6009512014-11-20 21:39:37 +10001094 else
1095 Py_DECREF(tmp);
1096 }
1097
1098 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001099 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001100 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001101 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001102 status = -1;
1103 }
Nick Coghland6009512014-11-20 21:39:37 +10001104 else
1105 Py_DECREF(tmp);
1106 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001107
1108 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001109}
1110
1111/* Undo the effect of Py_Initialize().
1112
1113 Beware: if multiple interpreter and/or thread states exist, these
1114 are not wiped out; only the current thread and interpreter state
1115 are deleted. But since everything else is deleted, those other
1116 interpreter and thread states should no longer be used.
1117
1118 (XXX We should do better, e.g. wipe out all interpreters and
1119 threads.)
1120
1121 Locking: as above.
1122
1123*/
1124
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001125int
1126Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001127{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001128 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001129
Victor Stinner8e91c242019-04-24 17:24:01 +02001130 _PyRuntimeState *runtime = &_PyRuntime;
1131 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001132 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001133 }
Nick Coghland6009512014-11-20 21:39:37 +10001134
Eric Snow842a2f02019-03-15 15:47:51 -06001135 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001136 wait_for_thread_shutdown();
1137
Eric Snow842a2f02019-03-15 15:47:51 -06001138 // Make any remaining pending calls.
Victor Stinner09532fe2019-05-10 23:39:09 +02001139 _Py_FinishPendingCalls(runtime);
Eric Snow842a2f02019-03-15 15:47:51 -06001140
Victor Stinner8e91c242019-04-24 17:24:01 +02001141 /* Get current thread state and interpreter pointer */
Victor Stinner09532fe2019-05-10 23:39:09 +02001142 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001143 PyInterpreterState *interp = tstate->interp;
1144
Nick Coghland6009512014-11-20 21:39:37 +10001145 /* The interpreter is still entirely intact at this point, and the
1146 * exit funcs may be relying on that. In particular, if some thread
1147 * or exit func is still waiting to do an import, the import machinery
1148 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001149 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001150 * Note that Threading.py uses an exit func to do a join on all the
1151 * threads created thru it, so this also protects pending imports in
1152 * the threads created via Threading.
1153 */
Nick Coghland6009512014-11-20 21:39:37 +10001154
Marcel Plch776407f2017-12-20 11:17:58 +01001155 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001156
Victor Stinnerda273412017-12-15 01:46:02 +01001157 /* Copy the core config, PyInterpreterState_Delete() free
1158 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001159#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001160 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001161#endif
1162#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001163 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001164#endif
1165#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001166 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001167#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001168
Nick Coghland6009512014-11-20 21:39:37 +10001169 /* Remaining threads (e.g. daemon threads) will automatically exit
1170 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001171 runtime->finalizing = tstate;
1172 runtime->initialized = 0;
1173 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001174
Victor Stinnere0deff32015-03-24 13:46:18 +01001175 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001176 if (flush_std_files() < 0) {
1177 status = -1;
1178 }
Nick Coghland6009512014-11-20 21:39:37 +10001179
1180 /* Disable signal handling */
1181 PyOS_FiniInterrupts();
1182
1183 /* Collect garbage. This may call finalizers; it's nice to call these
1184 * before all modules are destroyed.
1185 * XXX If a __del__ or weakref callback is triggered here, and tries to
1186 * XXX import a module, bad things can happen, because Python no
1187 * XXX longer believes it's initialized.
1188 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1189 * XXX is easy to provoke that way. I've also seen, e.g.,
1190 * XXX Exception exceptions.ImportError: 'No module named sha'
1191 * XXX in <function callback at 0x008F5718> ignored
1192 * XXX but I'm unclear on exactly how that one happens. In any case,
1193 * XXX I haven't seen a real-life report of either of these.
1194 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001195 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001196#ifdef COUNT_ALLOCS
1197 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1198 each collection might release some types from the type
1199 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001200 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001201 /* nothing */;
1202#endif
Eric Snowdae02762017-09-14 00:35:58 -07001203
Nick Coghland6009512014-11-20 21:39:37 +10001204 /* Destroy all modules */
1205 PyImport_Cleanup();
1206
Victor Stinnere0deff32015-03-24 13:46:18 +01001207 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001208 if (flush_std_files() < 0) {
1209 status = -1;
1210 }
Nick Coghland6009512014-11-20 21:39:37 +10001211
1212 /* Collect final garbage. This disposes of cycles created by
1213 * class definitions, for example.
1214 * XXX This is disabled because it caused too many problems. If
1215 * XXX a __del__ or weakref callback triggers here, Python code has
1216 * XXX a hard time running, because even the sys module has been
1217 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1218 * XXX One symptom is a sequence of information-free messages
1219 * XXX coming from threads (if a __del__ or callback is invoked,
1220 * XXX other threads can execute too, and any exception they encounter
1221 * XXX triggers a comedy of errors as subsystem after subsystem
1222 * XXX fails to find what it *expects* to find in sys to help report
1223 * XXX the exception and consequent unexpected failures). I've also
1224 * XXX seen segfaults then, after adding print statements to the
1225 * XXX Python code getting called.
1226 */
1227#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001228 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001229#endif
1230
1231 /* Disable tracemalloc after all Python objects have been destroyed,
1232 so it is possible to use tracemalloc in objects destructor. */
1233 _PyTraceMalloc_Fini();
1234
1235 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1236 _PyImport_Fini();
1237
1238 /* Cleanup typeobject.c's internal caches. */
1239 _PyType_Fini();
1240
1241 /* unload faulthandler module */
1242 _PyFaulthandler_Fini();
1243
1244 /* Debugging stuff */
1245#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001246 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001247#endif
1248 /* dump hash stats */
1249 _PyHash_Fini();
1250
Eric Snowdae02762017-09-14 00:35:58 -07001251#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001252 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001253 _PyDebug_PrintTotalRefs();
1254 }
Eric Snowdae02762017-09-14 00:35:58 -07001255#endif
Nick Coghland6009512014-11-20 21:39:37 +10001256
1257#ifdef Py_TRACE_REFS
1258 /* Display all objects still alive -- this can invoke arbitrary
1259 * __repr__ overrides, so requires a mostly-intact interpreter.
1260 * Alas, a lot of stuff may still be alive now that will be cleaned
1261 * up later.
1262 */
Victor Stinnerda273412017-12-15 01:46:02 +01001263 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001264 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001265 }
Nick Coghland6009512014-11-20 21:39:37 +10001266#endif /* Py_TRACE_REFS */
1267
1268 /* Clear interpreter state and all thread states. */
1269 PyInterpreterState_Clear(interp);
1270
1271 /* Now we decref the exception classes. After this point nothing
1272 can raise an exception. That's okay, because each Fini() method
1273 below has been checked to make sure no exceptions are ever
1274 raised.
1275 */
1276
1277 _PyExc_Fini();
1278
1279 /* Sundry finalizers */
1280 PyMethod_Fini();
1281 PyFrame_Fini();
1282 PyCFunction_Fini();
1283 PyTuple_Fini();
1284 PyList_Fini();
1285 PySet_Fini();
1286 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001287 PyLong_Fini();
1288 PyFloat_Fini();
1289 PyDict_Fini();
1290 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001291 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001292 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001293 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001294 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001295 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001296 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001297
1298 /* Cleanup Unicode implementation */
1299 _PyUnicode_Fini();
1300
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001301 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001302
1303 /* XXX Still allocated:
1304 - various static ad-hoc pointers to interned strings
1305 - int and float free list blocks
1306 - whatever various modules and libraries allocate
1307 */
1308
1309 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1310
1311 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001312 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001313
1314 /* Delete current thread. After this, many C API calls become crashy. */
1315 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001316
Nick Coghland6009512014-11-20 21:39:37 +10001317 PyInterpreterState_Delete(interp);
1318
1319#ifdef Py_TRACE_REFS
1320 /* Display addresses (& refcnts) of all objects still alive.
1321 * An address can be used to find the repr of the object, printed
1322 * above by _Py_PrintReferences.
1323 */
Victor Stinnerda273412017-12-15 01:46:02 +01001324 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001325 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001326 }
Nick Coghland6009512014-11-20 21:39:37 +10001327#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001328#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001329 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001330 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001331 }
Nick Coghland6009512014-11-20 21:39:37 +10001332#endif
1333
Victor Stinner8e91c242019-04-24 17:24:01 +02001334 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001335
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001336 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001337 return status;
1338}
1339
1340void
1341Py_Finalize(void)
1342{
1343 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001344}
1345
1346/* Create and initialize a new interpreter and thread, and return the
1347 new thread. This requires that Py_Initialize() has been called
1348 first.
1349
1350 Unsuccessful initialization yields a NULL pointer. Note that *no*
1351 exception information is available even in this case -- the
1352 exception information is held in the thread, and there is no
1353 thread.
1354
1355 Locking: as above.
1356
1357*/
1358
Victor Stinnera7368ac2017-11-15 18:11:45 -08001359static _PyInitError
1360new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001361{
Victor Stinner9316ee42017-11-25 03:17:57 +01001362 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001363
Victor Stinner43125222019-04-24 18:23:53 +02001364 err = _PyRuntime_Initialize();
1365 if (_Py_INIT_FAILED(err)) {
1366 return err;
1367 }
1368 _PyRuntimeState *runtime = &_PyRuntime;
1369
1370 if (!runtime->initialized) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001371 return _Py_INIT_ERR("Py_Initialize must be called first");
1372 }
Nick Coghland6009512014-11-20 21:39:37 +10001373
Victor Stinner8a1be612016-03-14 22:07:55 +01001374 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1375 interpreters: disable PyGILState_Check(). */
1376 _PyGILState_check_enabled = 0;
1377
Victor Stinner43125222019-04-24 18:23:53 +02001378 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001379 if (interp == NULL) {
1380 *tstate_p = NULL;
1381 return _Py_INIT_OK();
1382 }
Nick Coghland6009512014-11-20 21:39:37 +10001383
Victor Stinner43125222019-04-24 18:23:53 +02001384 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001385 if (tstate == NULL) {
1386 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001387 *tstate_p = NULL;
1388 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001389 }
1390
Victor Stinner43125222019-04-24 18:23:53 +02001391 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001392
Eric Snow1abcf672017-05-23 21:46:51 -07001393 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001394 _PyCoreConfig *core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001395 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001396 core_config = &save_tstate->interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001397 } else {
1398 /* No current thread state, copy from the main interpreter */
1399 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001400 core_config = &main_interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001401 }
1402
Victor Stinner1a9f0d82019-05-01 15:22:52 +02001403 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
1404 if (_Py_INIT_FAILED(err)) {
1405 return err;
Victor Stinnerda273412017-12-15 01:46:02 +01001406 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001407 core_config = &interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001408
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001409 err = _PyExc_Init();
1410 if (_Py_INIT_FAILED(err)) {
1411 return err;
1412 }
1413
Nick Coghland6009512014-11-20 21:39:37 +10001414 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001415 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001416 if (modules == NULL) {
1417 return _Py_INIT_ERR("can't make modules dictionary");
1418 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001419 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001420
Victor Stinner43125222019-04-24 18:23:53 +02001421 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001422 if (sysmod != NULL) {
1423 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001424 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001425 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001426 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001427 Py_INCREF(interp->sysdict);
1428 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner43125222019-04-24 18:23:53 +02001429 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerab672812019-01-23 15:04:40 +01001430 return _Py_INIT_ERR("can't finish initializing sys");
1431 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001432 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001433 else if (PyErr_Occurred()) {
1434 goto handle_error;
1435 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001436
Victor Stinner43125222019-04-24 18:23:53 +02001437 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001438 if (bimod != NULL) {
1439 interp->builtins = PyModule_GetDict(bimod);
1440 if (interp->builtins == NULL)
1441 goto handle_error;
1442 Py_INCREF(interp->builtins);
1443 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001444 else if (PyErr_Occurred()) {
1445 goto handle_error;
1446 }
Nick Coghland6009512014-11-20 21:39:37 +10001447
Nick Coghland6009512014-11-20 21:39:37 +10001448 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001449 err = _PyBuiltins_AddExceptions(bimod);
1450 if (_Py_INIT_FAILED(err)) {
1451 return err;
1452 }
Nick Coghland6009512014-11-20 21:39:37 +10001453
Victor Stinnerab672812019-01-23 15:04:40 +01001454 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1455 if (_Py_INIT_FAILED(err)) {
1456 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001457 }
Nick Coghland6009512014-11-20 21:39:37 +10001458
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001459 err = _PyImportHooks_Init();
1460 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001461 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001462 }
Nick Coghland6009512014-11-20 21:39:37 +10001463
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001464 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001465 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001466 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001467 }
Nick Coghland6009512014-11-20 21:39:37 +10001468
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001469 err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001470 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001471 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001472 }
Nick Coghland6009512014-11-20 21:39:37 +10001473
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001474 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001475 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001476 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001477 }
1478
Victor Stinner91106cd2017-12-13 12:29:09 +01001479 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001480 if (_Py_INIT_FAILED(err)) {
1481 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001482 }
1483
1484 err = add_main_module(interp);
1485 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001486 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001487 }
1488
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001489 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001490 err = init_import_size();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001491 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001492 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001493 }
1494 }
Nick Coghland6009512014-11-20 21:39:37 +10001495 }
1496
Victor Stinnera7368ac2017-11-15 18:11:45 -08001497 if (PyErr_Occurred()) {
1498 goto handle_error;
1499 }
Nick Coghland6009512014-11-20 21:39:37 +10001500
Victor Stinnera7368ac2017-11-15 18:11:45 -08001501 *tstate_p = tstate;
1502 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001503
Nick Coghland6009512014-11-20 21:39:37 +10001504handle_error:
1505 /* Oops, it didn't work. Undo it all. */
1506
1507 PyErr_PrintEx(0);
1508 PyThreadState_Clear(tstate);
1509 PyThreadState_Swap(save_tstate);
1510 PyThreadState_Delete(tstate);
1511 PyInterpreterState_Delete(interp);
1512
Victor Stinnera7368ac2017-11-15 18:11:45 -08001513 *tstate_p = NULL;
1514 return _Py_INIT_OK();
1515}
1516
1517PyThreadState *
1518Py_NewInterpreter(void)
1519{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001520 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001521 _PyInitError err = new_interpreter(&tstate);
1522 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001523 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001524 }
1525 return tstate;
1526
Nick Coghland6009512014-11-20 21:39:37 +10001527}
1528
1529/* Delete an interpreter and its last thread. This requires that the
1530 given thread state is current, that the thread has no remaining
1531 frames, and that it is its interpreter's only remaining thread.
1532 It is a fatal error to violate these constraints.
1533
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001534 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001535 everything, regardless.)
1536
1537 Locking: as above.
1538
1539*/
1540
1541void
1542Py_EndInterpreter(PyThreadState *tstate)
1543{
1544 PyInterpreterState *interp = tstate->interp;
1545
Victor Stinner50b48572018-11-01 01:51:40 +01001546 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001547 Py_FatalError("Py_EndInterpreter: thread is not current");
1548 if (tstate->frame != NULL)
1549 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001550 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001551
Eric Snow842a2f02019-03-15 15:47:51 -06001552 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001553 wait_for_thread_shutdown();
1554
Marcel Plch776407f2017-12-20 11:17:58 +01001555 call_py_exitfuncs(interp);
1556
Nick Coghland6009512014-11-20 21:39:37 +10001557 if (tstate != interp->tstate_head || tstate->next != NULL)
1558 Py_FatalError("Py_EndInterpreter: not the last thread");
1559
1560 PyImport_Cleanup();
1561 PyInterpreterState_Clear(interp);
1562 PyThreadState_Swap(NULL);
1563 PyInterpreterState_Delete(interp);
1564}
1565
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001566/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001567
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001568static _PyInitError
1569add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001570{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001571 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001572 m = PyImport_AddModule("__main__");
1573 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001574 return _Py_INIT_ERR("can't create __main__ module");
1575
Nick Coghland6009512014-11-20 21:39:37 +10001576 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001577 ann_dict = PyDict_New();
1578 if ((ann_dict == NULL) ||
1579 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001580 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001581 }
1582 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001583
Nick Coghland6009512014-11-20 21:39:37 +10001584 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1585 PyObject *bimod = PyImport_ImportModule("builtins");
1586 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001587 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001588 }
1589 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001590 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001591 }
1592 Py_DECREF(bimod);
1593 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001594
Nick Coghland6009512014-11-20 21:39:37 +10001595 /* Main is a little special - imp.is_builtin("__main__") will return
1596 * False, but BuiltinImporter is still the most appropriate initial
1597 * setting for its __loader__ attribute. A more suitable value will
1598 * be set if __main__ gets further initialized later in the startup
1599 * process.
1600 */
1601 loader = PyDict_GetItemString(d, "__loader__");
1602 if (loader == NULL || loader == Py_None) {
1603 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1604 "BuiltinImporter");
1605 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001606 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001607 }
1608 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001609 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001610 }
1611 Py_DECREF(loader);
1612 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001613 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001614}
1615
Nick Coghland6009512014-11-20 21:39:37 +10001616/* Import the site module (not into __main__ though) */
1617
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001618static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001619init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001620{
1621 PyObject *m;
1622 m = PyImport_ImportModule("site");
1623 if (m == NULL) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001624 return _Py_INIT_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001625 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001626 Py_DECREF(m);
1627 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001628}
1629
Victor Stinner874dbe82015-09-04 17:29:57 +02001630/* Check if a file descriptor is valid or not.
1631 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1632static int
1633is_valid_fd(int fd)
1634{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001635/* dup() is faster than fstat(): fstat() can require input/output operations,
1636 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1637 startup. Problem: dup() doesn't check if the file descriptor is valid on
1638 some platforms.
1639
1640 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1641 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1642 EBADF. FreeBSD has similar issue (bpo-32849).
1643
1644 Only use dup() on platforms where dup() is enough to detect invalid FD in
1645 corner cases: on Linux and Windows (bpo-32849). */
1646#if defined(__linux__) || defined(MS_WINDOWS)
1647 if (fd < 0) {
1648 return 0;
1649 }
1650 int fd2;
1651
1652 _Py_BEGIN_SUPPRESS_IPH
1653 fd2 = dup(fd);
1654 if (fd2 >= 0) {
1655 close(fd2);
1656 }
1657 _Py_END_SUPPRESS_IPH
1658
1659 return (fd2 >= 0);
1660#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001661 struct stat st;
1662 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001663#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001664}
1665
1666/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001667static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001668create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001669 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001670 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001671{
1672 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1673 const char* mode;
1674 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001675 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001676 int buffering, isatty;
1677 _Py_IDENTIFIER(open);
1678 _Py_IDENTIFIER(isatty);
1679 _Py_IDENTIFIER(TextIOWrapper);
1680 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001681 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001682
Victor Stinner874dbe82015-09-04 17:29:57 +02001683 if (!is_valid_fd(fd))
1684 Py_RETURN_NONE;
1685
Nick Coghland6009512014-11-20 21:39:37 +10001686 /* stdin is always opened in buffered mode, first because it shouldn't
1687 make a difference in common use cases, second because TextIOWrapper
1688 depends on the presence of a read1() method which only exists on
1689 buffered streams.
1690 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001691 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001692 buffering = 0;
1693 else
1694 buffering = -1;
1695 if (write_mode)
1696 mode = "wb";
1697 else
1698 mode = "rb";
1699 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1700 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001701 Py_None, Py_None, /* encoding, errors */
1702 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001703 if (buf == NULL)
1704 goto error;
1705
1706 if (buffering) {
1707 _Py_IDENTIFIER(raw);
1708 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1709 if (raw == NULL)
1710 goto error;
1711 }
1712 else {
1713 raw = buf;
1714 Py_INCREF(raw);
1715 }
1716
Steve Dower39294992016-08-30 21:22:36 -07001717#ifdef MS_WINDOWS
1718 /* Windows console IO is always UTF-8 encoded */
1719 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001720 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001721#endif
1722
Nick Coghland6009512014-11-20 21:39:37 +10001723 text = PyUnicode_FromString(name);
1724 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1725 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001726 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001727 if (res == NULL)
1728 goto error;
1729 isatty = PyObject_IsTrue(res);
1730 Py_DECREF(res);
1731 if (isatty == -1)
1732 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001733 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001734 write_through = Py_True;
1735 else
1736 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001737 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001738 line_buffering = Py_True;
1739 else
1740 line_buffering = Py_False;
1741
1742 Py_CLEAR(raw);
1743 Py_CLEAR(text);
1744
1745#ifdef MS_WINDOWS
1746 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1747 newlines to "\n".
1748 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1749 newline = NULL;
1750#else
1751 /* sys.stdin: split lines at "\n".
1752 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1753 newline = "\n";
1754#endif
1755
Victor Stinner709d23d2019-05-02 14:56:30 -04001756 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1757 if (encoding_str == NULL) {
1758 Py_CLEAR(buf);
1759 goto error;
1760 }
1761
1762 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1763 if (errors_str == NULL) {
1764 Py_CLEAR(buf);
1765 Py_CLEAR(encoding_str);
1766 goto error;
1767 }
1768
1769 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1770 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001771 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001772 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001773 Py_CLEAR(encoding_str);
1774 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001775 if (stream == NULL)
1776 goto error;
1777
1778 if (write_mode)
1779 mode = "w";
1780 else
1781 mode = "r";
1782 text = PyUnicode_FromString(mode);
1783 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1784 goto error;
1785 Py_CLEAR(text);
1786 return stream;
1787
1788error:
1789 Py_XDECREF(buf);
1790 Py_XDECREF(stream);
1791 Py_XDECREF(text);
1792 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001793
Victor Stinner874dbe82015-09-04 17:29:57 +02001794 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1795 /* Issue #24891: the file descriptor was closed after the first
1796 is_valid_fd() check was called. Ignore the OSError and set the
1797 stream to None. */
1798 PyErr_Clear();
1799 Py_RETURN_NONE;
1800 }
1801 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001802}
1803
1804/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001805static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001806init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001807{
1808 PyObject *iomod = NULL, *wrapper;
1809 PyObject *bimod = NULL;
1810 PyObject *m;
1811 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001812 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001813 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001814 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001815 _PyCoreConfig *config = &interp->core_config;
1816
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001817 /* Check that stdin is not a directory
1818 Using shell redirection, you can redirect stdin to a directory,
1819 crashing the Python interpreter. Catch this common mistake here
1820 and output a useful error message. Note that under MS Windows,
1821 the shell already prevents that. */
1822#ifndef MS_WINDOWS
1823 struct _Py_stat_struct sb;
1824 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1825 S_ISDIR(sb.st_mode)) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001826 return _Py_INIT_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001827 }
1828#endif
1829
Nick Coghland6009512014-11-20 21:39:37 +10001830 /* Hack to avoid a nasty recursion issue when Python is invoked
1831 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1832 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1833 goto error;
1834 }
1835 Py_DECREF(m);
1836
1837 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1838 goto error;
1839 }
1840 Py_DECREF(m);
1841
1842 if (!(bimod = PyImport_ImportModule("builtins"))) {
1843 goto error;
1844 }
1845
1846 if (!(iomod = PyImport_ImportModule("io"))) {
1847 goto error;
1848 }
1849 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1850 goto error;
1851 }
1852
1853 /* Set builtins.open */
1854 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1855 Py_DECREF(wrapper);
1856 goto error;
1857 }
1858 Py_DECREF(wrapper);
1859
Nick Coghland6009512014-11-20 21:39:37 +10001860 /* Set sys.stdin */
1861 fd = fileno(stdin);
1862 /* Under some conditions stdin, stdout and stderr may not be connected
1863 * and fileno() may point to an invalid file descriptor. For example
1864 * GUI apps don't have valid standard streams by default.
1865 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001866 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001867 config->stdio_encoding,
1868 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001869 if (std == NULL)
1870 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001871 PySys_SetObject("__stdin__", std);
1872 _PySys_SetObjectId(&PyId_stdin, std);
1873 Py_DECREF(std);
1874
1875 /* Set sys.stdout */
1876 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001877 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001878 config->stdio_encoding,
1879 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001880 if (std == NULL)
1881 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001882 PySys_SetObject("__stdout__", std);
1883 _PySys_SetObjectId(&PyId_stdout, std);
1884 Py_DECREF(std);
1885
1886#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1887 /* Set sys.stderr, replaces the preliminary stderr */
1888 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001889 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001890 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001891 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001892 if (std == NULL)
1893 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001894
1895 /* Same as hack above, pre-import stderr's codec to avoid recursion
1896 when import.c tries to write to stderr in verbose mode. */
1897 encoding_attr = PyObject_GetAttrString(std, "encoding");
1898 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001899 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001900 if (std_encoding != NULL) {
1901 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1902 Py_XDECREF(codec_info);
1903 }
1904 Py_DECREF(encoding_attr);
1905 }
1906 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1907
1908 if (PySys_SetObject("__stderr__", std) < 0) {
1909 Py_DECREF(std);
1910 goto error;
1911 }
1912 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1913 Py_DECREF(std);
1914 goto error;
1915 }
1916 Py_DECREF(std);
1917#endif
1918
Victor Stinnera7368ac2017-11-15 18:11:45 -08001919 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001920
Victor Stinnera7368ac2017-11-15 18:11:45 -08001921error:
1922 res = _Py_INIT_ERR("can't initialize sys standard streams");
1923
1924done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001925 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001926
Nick Coghland6009512014-11-20 21:39:37 +10001927 Py_XDECREF(bimod);
1928 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001929 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001930}
1931
1932
Victor Stinner10dc4842015-03-24 12:01:30 +01001933static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001934_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001935{
Victor Stinner10dc4842015-03-24 12:01:30 +01001936 fputc('\n', stderr);
1937 fflush(stderr);
1938
1939 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001940 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001941}
Victor Stinner791da1c2016-03-14 16:53:12 +01001942
1943/* Print the current exception (if an exception is set) with its traceback,
1944 or display the current Python stack.
1945
1946 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1947 called on catastrophic cases.
1948
1949 Return 1 if the traceback was displayed, 0 otherwise. */
1950
1951static int
1952_Py_FatalError_PrintExc(int fd)
1953{
1954 PyObject *ferr, *res;
1955 PyObject *exception, *v, *tb;
1956 int has_tb;
1957
Victor Stinner791da1c2016-03-14 16:53:12 +01001958 PyErr_Fetch(&exception, &v, &tb);
1959 if (exception == NULL) {
1960 /* No current exception */
1961 return 0;
1962 }
1963
1964 ferr = _PySys_GetObjectId(&PyId_stderr);
1965 if (ferr == NULL || ferr == Py_None) {
1966 /* sys.stderr is not set yet or set to None,
1967 no need to try to display the exception */
1968 return 0;
1969 }
1970
1971 PyErr_NormalizeException(&exception, &v, &tb);
1972 if (tb == NULL) {
1973 tb = Py_None;
1974 Py_INCREF(tb);
1975 }
1976 PyException_SetTraceback(v, tb);
1977 if (exception == NULL) {
1978 /* PyErr_NormalizeException() failed */
1979 return 0;
1980 }
1981
1982 has_tb = (tb != Py_None);
1983 PyErr_Display(exception, v, tb);
1984 Py_XDECREF(exception);
1985 Py_XDECREF(v);
1986 Py_XDECREF(tb);
1987
1988 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001989 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001990 if (res == NULL)
1991 PyErr_Clear();
1992 else
1993 Py_DECREF(res);
1994
1995 return has_tb;
1996}
1997
Nick Coghland6009512014-11-20 21:39:37 +10001998/* Print fatal error message and abort */
1999
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002000#ifdef MS_WINDOWS
2001static void
2002fatal_output_debug(const char *msg)
2003{
2004 /* buffer of 256 bytes allocated on the stack */
2005 WCHAR buffer[256 / sizeof(WCHAR)];
2006 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2007 size_t msglen;
2008
2009 OutputDebugStringW(L"Fatal Python error: ");
2010
2011 msglen = strlen(msg);
2012 while (msglen) {
2013 size_t i;
2014
2015 if (buflen > msglen) {
2016 buflen = msglen;
2017 }
2018
2019 /* Convert the message to wchar_t. This uses a simple one-to-one
2020 conversion, assuming that the this error message actually uses
2021 ASCII only. If this ceases to be true, we will have to convert. */
2022 for (i=0; i < buflen; ++i) {
2023 buffer[i] = msg[i];
2024 }
2025 buffer[i] = L'\0';
2026 OutputDebugStringW(buffer);
2027
2028 msg += buflen;
2029 msglen -= buflen;
2030 }
2031 OutputDebugStringW(L"\n");
2032}
2033#endif
2034
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002035static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002036fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002037{
2038 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002039 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002040
2041 if (reentrant) {
2042 /* Py_FatalError() caused a second fatal error.
2043 Example: flush_std_files() raises a recursion error. */
2044 goto exit;
2045 }
2046 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002047
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002048 fprintf(stderr, "Fatal Python error: ");
2049 if (prefix) {
2050 fputs(prefix, stderr);
2051 fputs(": ", stderr);
2052 }
2053 if (msg) {
2054 fputs(msg, stderr);
2055 }
2056 else {
2057 fprintf(stderr, "<message not set>");
2058 }
2059 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002060 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002061
Victor Stinner3a228ab2018-11-01 00:26:41 +01002062 /* Check if the current thread has a Python thread state
2063 and holds the GIL */
2064 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2065 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002066 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002067 if (tss_tstate != tstate) {
2068 /* The Python thread does not hold the GIL */
2069 tss_tstate = NULL;
2070 }
2071 }
2072 else {
2073 /* Py_FatalError() has been called from a C thread
2074 which has no Python thread state. */
2075 }
2076 int has_tstate_and_gil = (tss_tstate != NULL);
2077
2078 if (has_tstate_and_gil) {
2079 /* If an exception is set, print the exception with its traceback */
2080 if (!_Py_FatalError_PrintExc(fd)) {
2081 /* No exception is set, or an exception is set without traceback */
2082 _Py_FatalError_DumpTracebacks(fd);
2083 }
2084 }
2085 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002086 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002087 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002088
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002089 /* The main purpose of faulthandler is to display the traceback.
2090 This function already did its best to display a traceback.
2091 Disable faulthandler to prevent writing a second traceback
2092 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002093 _PyFaulthandler_Fini();
2094
Victor Stinner791da1c2016-03-14 16:53:12 +01002095 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002096 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002097 /* Flush sys.stdout and sys.stderr */
2098 flush_std_files();
2099 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002100
Nick Coghland6009512014-11-20 21:39:37 +10002101#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002102 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002103#endif /* MS_WINDOWS */
2104
2105exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002106 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002107#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002108 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002109#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002110 abort();
2111 }
2112 else {
2113 exit(status);
2114 }
2115}
2116
Victor Stinner19760862017-12-20 01:41:59 +01002117void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002118Py_FatalError(const char *msg)
2119{
2120 fatal_error(NULL, msg, -1);
2121}
2122
Victor Stinner19760862017-12-20 01:41:59 +01002123void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002124_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002125{
Victor Stinnerdb719752019-05-01 05:35:33 +02002126 assert(_Py_INIT_FAILED(err));
2127 if (_Py_INIT_IS_EXIT(err)) {
2128#ifdef MS_WINDOWS
2129 ExitProcess(err.exitcode);
2130#else
Victor Stinnerdfe88472019-03-01 12:14:41 +01002131 exit(err.exitcode);
Victor Stinnerdb719752019-05-01 05:35:33 +02002132#endif
Victor Stinnerdfe88472019-03-01 12:14:41 +01002133 }
2134 else {
Victor Stinnerdb719752019-05-01 05:35:33 +02002135 assert(_Py_INIT_IS_ERROR(err));
2136 fatal_error(err._func, err.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002137 }
Nick Coghland6009512014-11-20 21:39:37 +10002138}
2139
2140/* Clean up and exit */
2141
Victor Stinnerd7292b52016-06-17 12:29:00 +02002142# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002143
Nick Coghland6009512014-11-20 21:39:37 +10002144/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002145void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002146{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002147 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002148
Antoine Pitroufc5db952017-12-13 02:29:07 +01002149 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002150 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2151
2152 is->pyexitfunc = func;
2153 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002154}
2155
2156static void
Marcel Plch776407f2017-12-20 11:17:58 +01002157call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002158{
Marcel Plch776407f2017-12-20 11:17:58 +01002159 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002160 return;
2161
Marcel Plch776407f2017-12-20 11:17:58 +01002162 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002163 PyErr_Clear();
2164}
2165
2166/* Wait until threading._shutdown completes, provided
2167 the threading module was imported in the first place.
2168 The shutdown routine will wait until all non-daemon
2169 "threading" threads have completed. */
2170static void
2171wait_for_thread_shutdown(void)
2172{
Nick Coghland6009512014-11-20 21:39:37 +10002173 _Py_IDENTIFIER(_shutdown);
2174 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002175 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002176 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002177 if (PyErr_Occurred()) {
2178 PyErr_WriteUnraisable(NULL);
2179 }
2180 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002181 return;
2182 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002183 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002184 if (result == NULL) {
2185 PyErr_WriteUnraisable(threading);
2186 }
2187 else {
2188 Py_DECREF(result);
2189 }
2190 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002191}
2192
2193#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002194int Py_AtExit(void (*func)(void))
2195{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002196 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002197 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002198 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002199 return 0;
2200}
2201
2202static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002203call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002204{
Victor Stinner8e91c242019-04-24 17:24:01 +02002205 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002206 /* pop last function from the list */
2207 runtime->nexitfuncs--;
2208 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2209 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2210
2211 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002212 }
Nick Coghland6009512014-11-20 21:39:37 +10002213
2214 fflush(stdout);
2215 fflush(stderr);
2216}
2217
Victor Stinnercfc88312018-08-01 16:41:25 +02002218void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002219Py_Exit(int sts)
2220{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002221 if (Py_FinalizeEx() < 0) {
2222 sts = 120;
2223 }
Nick Coghland6009512014-11-20 21:39:37 +10002224
2225 exit(sts);
2226}
2227
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002228static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002229init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002230{
2231#ifdef SIGPIPE
2232 PyOS_setsig(SIGPIPE, SIG_IGN);
2233#endif
2234#ifdef SIGXFZ
2235 PyOS_setsig(SIGXFZ, SIG_IGN);
2236#endif
2237#ifdef SIGXFSZ
2238 PyOS_setsig(SIGXFSZ, SIG_IGN);
2239#endif
2240 PyOS_InitInterrupts(); /* May imply initsignal() */
2241 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002242 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002243 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002244 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002245}
2246
2247
2248/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2249 *
2250 * All of the code in this function must only use async-signal-safe functions,
2251 * listed at `man 7 signal` or
2252 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2253 */
2254void
2255_Py_RestoreSignals(void)
2256{
2257#ifdef SIGPIPE
2258 PyOS_setsig(SIGPIPE, SIG_DFL);
2259#endif
2260#ifdef SIGXFZ
2261 PyOS_setsig(SIGXFZ, SIG_DFL);
2262#endif
2263#ifdef SIGXFSZ
2264 PyOS_setsig(SIGXFSZ, SIG_DFL);
2265#endif
2266}
2267
2268
2269/*
2270 * The file descriptor fd is considered ``interactive'' if either
2271 * a) isatty(fd) is TRUE, or
2272 * b) the -i flag was given, and the filename associated with
2273 * the descriptor is NULL or "<stdin>" or "???".
2274 */
2275int
2276Py_FdIsInteractive(FILE *fp, const char *filename)
2277{
2278 if (isatty((int)fileno(fp)))
2279 return 1;
2280 if (!Py_InteractiveFlag)
2281 return 0;
2282 return (filename == NULL) ||
2283 (strcmp(filename, "<stdin>") == 0) ||
2284 (strcmp(filename, "???") == 0);
2285}
2286
2287
Nick Coghland6009512014-11-20 21:39:37 +10002288/* Wrappers around sigaction() or signal(). */
2289
2290PyOS_sighandler_t
2291PyOS_getsig(int sig)
2292{
2293#ifdef HAVE_SIGACTION
2294 struct sigaction context;
2295 if (sigaction(sig, NULL, &context) == -1)
2296 return SIG_ERR;
2297 return context.sa_handler;
2298#else
2299 PyOS_sighandler_t handler;
2300/* Special signal handling for the secure CRT in Visual Studio 2005 */
2301#if defined(_MSC_VER) && _MSC_VER >= 1400
2302 switch (sig) {
2303 /* Only these signals are valid */
2304 case SIGINT:
2305 case SIGILL:
2306 case SIGFPE:
2307 case SIGSEGV:
2308 case SIGTERM:
2309 case SIGBREAK:
2310 case SIGABRT:
2311 break;
2312 /* Don't call signal() with other values or it will assert */
2313 default:
2314 return SIG_ERR;
2315 }
2316#endif /* _MSC_VER && _MSC_VER >= 1400 */
2317 handler = signal(sig, SIG_IGN);
2318 if (handler != SIG_ERR)
2319 signal(sig, handler);
2320 return handler;
2321#endif
2322}
2323
2324/*
2325 * All of the code in this function must only use async-signal-safe functions,
2326 * listed at `man 7 signal` or
2327 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2328 */
2329PyOS_sighandler_t
2330PyOS_setsig(int sig, PyOS_sighandler_t handler)
2331{
2332#ifdef HAVE_SIGACTION
2333 /* Some code in Modules/signalmodule.c depends on sigaction() being
2334 * used here if HAVE_SIGACTION is defined. Fix that if this code
2335 * changes to invalidate that assumption.
2336 */
2337 struct sigaction context, ocontext;
2338 context.sa_handler = handler;
2339 sigemptyset(&context.sa_mask);
2340 context.sa_flags = 0;
2341 if (sigaction(sig, &context, &ocontext) == -1)
2342 return SIG_ERR;
2343 return ocontext.sa_handler;
2344#else
2345 PyOS_sighandler_t oldhandler;
2346 oldhandler = signal(sig, handler);
2347#ifdef HAVE_SIGINTERRUPT
2348 siginterrupt(sig, 1);
2349#endif
2350 return oldhandler;
2351#endif
2352}
2353
2354#ifdef __cplusplus
2355}
2356#endif