blob: d29b293b79eb44dfad11057975b3d5d782b1b523 [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;
Victor Stinnerc96be812019-05-14 17:34:56 +0200153 int verbose = interp->core_config.verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000154
155 /* Import _importlib through its frozen version, _frozen_importlib. */
156 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800157 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000158 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200159 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000160 PySys_FormatStderr("import _frozen_importlib # frozen\n");
161 }
162 importlib = PyImport_AddModule("_frozen_importlib");
163 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800164 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000165 }
166 interp->importlib = importlib;
167 Py_INCREF(interp->importlib);
168
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300169 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
170 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800171 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300172 Py_INCREF(interp->import_func);
173
Victor Stinnercd6e6942015-09-18 09:11:57 +0200174 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800175 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000176 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800177 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000178 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200179 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200180 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000181 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600182 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800183 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000184 }
185
Victor Stinnercd6e6942015-09-18 09:11:57 +0200186 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000187 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
188 if (value == NULL) {
189 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800190 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000191 }
192 Py_DECREF(value);
193 Py_DECREF(impmod);
194
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800195 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000196}
197
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800198static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400199init_importlib_external(PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700200{
201 PyObject *value;
202 value = PyObject_CallMethod(interp->importlib,
203 "_install_external_importers", "");
204 if (value == NULL) {
205 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800206 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700207 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200208 Py_DECREF(value);
Victor Stinner410b85a2019-05-13 17:12:45 +0200209 return _PyImportZip_Init(interp);
Eric Snow1abcf672017-05-23 21:46:51 -0700210}
Nick Coghland6009512014-11-20 21:39:37 +1000211
Nick Coghlan6ea41862017-06-11 13:16:15 +1000212/* Helper functions to better handle the legacy C locale
213 *
214 * The legacy C locale assumes ASCII as the default text encoding, which
215 * causes problems not only for the CPython runtime, but also other
216 * components like GNU readline.
217 *
218 * Accordingly, when the CLI detects it, it attempts to coerce it to a
219 * more capable UTF-8 based alternative as follows:
220 *
221 * if (_Py_LegacyLocaleDetected()) {
222 * _Py_CoerceLegacyLocale();
223 * }
224 *
225 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
226 *
227 * Locale coercion also impacts the default error handler for the standard
228 * streams: while the usual default is "strict", the default for the legacy
229 * C locale and for any of the coercion target locales is "surrogateescape".
230 */
231
232int
233_Py_LegacyLocaleDetected(void)
234{
235#ifndef MS_WINDOWS
236 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000237 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
238 * the POSIX locale as a simple alias for the C locale, so
239 * we may also want to check for that explicitly.
240 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000241 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
242 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
243#else
244 /* Windows uses code pages instead of locales, so no locale is legacy */
245 return 0;
246#endif
247}
248
Nick Coghlaneb817952017-06-18 12:29:42 +1000249static const char *_C_LOCALE_WARNING =
250 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
251 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
252 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
253 "locales is recommended.\n";
254
Nick Coghlaneb817952017-06-18 12:29:42 +1000255static void
Victor Stinner43125222019-04-24 18:23:53 +0200256emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000257{
Victor Stinner43125222019-04-24 18:23:53 +0200258 const _PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner20004952019-03-26 02:31:11 +0100259 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200260 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000261 }
262}
263
Nick Coghlan6ea41862017-06-11 13:16:15 +1000264typedef struct _CandidateLocale {
265 const char *locale_name; /* The locale to try as a coercion target */
266} _LocaleCoercionTarget;
267
268static _LocaleCoercionTarget _TARGET_LOCALES[] = {
269 {"C.UTF-8"},
270 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000271 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000272 {NULL}
273};
274
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200275
276int
277_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000278{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200279 const _LocaleCoercionTarget *target = NULL;
280 for (target = _TARGET_LOCALES; target->locale_name; target++) {
281 if (strcmp(ctype_loc, target->locale_name) == 0) {
282 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000283 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200284 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200285 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000286}
287
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200288
Nick Coghlan6ea41862017-06-11 13:16:15 +1000289#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100290static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000291 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
292 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
293
294static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200295_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000296{
297 const char *newloc = target->locale_name;
298
299 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100300 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301
302 /* Set the relevant locale environment variable */
303 if (setenv("LC_CTYPE", newloc, 1)) {
304 fprintf(stderr,
305 "Error setting LC_CTYPE, skipping C locale coercion\n");
306 return;
307 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200308 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100309 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000310 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311
312 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100313 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000314}
315#endif
316
317void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200318_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319{
320#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200321 char *oldloc = NULL;
322
323 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
324 if (oldloc == NULL) {
325 return;
326 }
327
Victor Stinner94540602017-12-16 04:54:22 +0100328 const char *locale_override = getenv("LC_ALL");
329 if (locale_override == NULL || *locale_override == '\0') {
330 /* LC_ALL is also not set (or is set to an empty string) */
331 const _LocaleCoercionTarget *target = NULL;
332 for (target = _TARGET_LOCALES; target->locale_name; target++) {
333 const char *new_locale = setlocale(LC_CTYPE,
334 target->locale_name);
335 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400336#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100337 /* Also ensure that nl_langinfo works in this locale */
338 char *codeset = nl_langinfo(CODESET);
339 if (!codeset || *codeset == '\0') {
340 /* CODESET is not set or empty, so skip coercion */
341 new_locale = NULL;
342 _Py_SetLocaleFromEnv(LC_CTYPE);
343 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000344 }
Victor Stinner94540602017-12-16 04:54:22 +0100345#endif
346 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200347 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200348 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000349 }
350 }
351 }
352 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200353
354 setlocale(LC_CTYPE, oldloc);
355
356done:
357 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000358#endif
359}
360
xdegaye1588be62017-11-12 12:45:59 +0100361/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
362 * isolate the idiosyncrasies of different libc implementations. It reads the
363 * appropriate environment variable and uses its value to select the locale for
364 * 'category'. */
365char *
366_Py_SetLocaleFromEnv(int category)
367{
Victor Stinner353933e2018-11-23 13:08:26 +0100368 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100369#ifdef __ANDROID__
370 const char *locale;
371 const char **pvar;
372#ifdef PY_COERCE_C_LOCALE
373 const char *coerce_c_locale;
374#endif
375 const char *utf8_locale = "C.UTF-8";
376 const char *env_var_set[] = {
377 "LC_ALL",
378 "LC_CTYPE",
379 "LANG",
380 NULL,
381 };
382
383 /* Android setlocale(category, "") doesn't check the environment variables
384 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
385 * check the environment variables listed in env_var_set. */
386 for (pvar=env_var_set; *pvar; pvar++) {
387 locale = getenv(*pvar);
388 if (locale != NULL && *locale != '\0') {
389 if (strcmp(locale, utf8_locale) == 0 ||
390 strcmp(locale, "en_US.UTF-8") == 0) {
391 return setlocale(category, utf8_locale);
392 }
393 return setlocale(category, "C");
394 }
395 }
396
397 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
398 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
399 * Quote from POSIX section "8.2 Internationalization Variables":
400 * "4. If the LANG environment variable is not set or is set to the empty
401 * string, the implementation-defined default locale shall be used." */
402
403#ifdef PY_COERCE_C_LOCALE
404 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
405 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
406 /* Some other ported code may check the environment variables (e.g. in
407 * extension modules), so we make sure that they match the locale
408 * configuration */
409 if (setenv("LC_CTYPE", utf8_locale, 1)) {
410 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
411 "environment variable to %s\n", utf8_locale);
412 }
413 }
414#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100415 res = setlocale(category, utf8_locale);
416#else /* !defined(__ANDROID__) */
417 res = setlocale(category, "");
418#endif
419 _Py_ResetForceASCII();
420 return res;
xdegaye1588be62017-11-12 12:45:59 +0100421}
422
Nick Coghlan6ea41862017-06-11 13:16:15 +1000423
Eric Snow1abcf672017-05-23 21:46:51 -0700424/* Global initializations. Can be undone by Py_Finalize(). Don't
425 call this twice without an intervening Py_Finalize() call.
426
Victor Stinner484f20d2019-03-27 02:04:16 +0100427 Every call to _Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700428 must have a corresponding call to Py_Finalize.
429
430 Locking: you must hold the interpreter lock while calling these APIs.
431 (If the lock has not yet been initialized, that's equivalent to
432 having the lock, but you cannot use multiple threads.)
433
434*/
435
Victor Stinner1dc6e392018-07-25 02:49:17 +0200436static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200437_Py_Initialize_ReconfigureCore(_PyRuntimeState *runtime,
438 PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200439 const _PyCoreConfig *core_config)
440{
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200441 _PyInitError err;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100442 PyThreadState *tstate = _PyThreadState_GET();
443 if (!tstate) {
444 return _Py_INIT_ERR("failed to read thread state");
445 }
446
447 PyInterpreterState *interp = tstate->interp;
448 if (interp == NULL) {
449 return _Py_INIT_ERR("can't make main interpreter");
450 }
451 *interp_p = interp;
452
Victor Stinner43125222019-04-24 18:23:53 +0200453 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200454
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200455 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
456 if (_Py_INIT_FAILED(err)) {
457 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200458 }
459 core_config = &interp->core_config;
460
461 if (core_config->_install_importlib) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200462 err = _PyCoreConfig_SetPathConfig(core_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200463 if (_Py_INIT_FAILED(err)) {
464 return err;
465 }
466 }
467 return _Py_INIT_OK();
468}
469
470
Victor Stinner1dc6e392018-07-25 02:49:17 +0200471static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200472pycore_init_runtime(_PyRuntimeState *runtime,
473 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000474{
Victor Stinner43125222019-04-24 18:23:53 +0200475 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200476 return _Py_INIT_ERR("main interpreter already initialized");
477 }
Victor Stinnerda273412017-12-15 01:46:02 +0100478
Victor Stinner43125222019-04-24 18:23:53 +0200479 _PyCoreConfig_Write(core_config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600480
Eric Snow1abcf672017-05-23 21:46:51 -0700481 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
482 * threads behave a little more gracefully at interpreter shutdown.
483 * We clobber it here so the new interpreter can start with a clean
484 * slate.
485 *
486 * However, this may still lead to misbehaviour if there are daemon
487 * threads still hanging around from a previous Py_Initialize/Finalize
488 * pair :(
489 */
Victor Stinner43125222019-04-24 18:23:53 +0200490 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600491
Victor Stinner43125222019-04-24 18:23:53 +0200492 _PyInitError err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800493 if (_Py_INIT_FAILED(err)) {
494 return err;
495 }
496
Victor Stinner43125222019-04-24 18:23:53 +0200497 err = _PyInterpreterState_Enable(runtime);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800498 if (_Py_INIT_FAILED(err)) {
499 return err;
500 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100501 return _Py_INIT_OK();
502}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800503
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100504
505static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200506pycore_create_interpreter(_PyRuntimeState *runtime,
507 const _PyCoreConfig *core_config,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100508 PyInterpreterState **interp_p)
509{
510 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100511 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800512 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100513 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200514 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100515
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200516 _PyInitError err = _PyCoreConfig_Copy(&interp->core_config, core_config);
517 if (_Py_INIT_FAILED(err)) {
518 return err;
Victor Stinnerda273412017-12-15 01:46:02 +0100519 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200520 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000521
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200522 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000523 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800524 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000525 (void) PyThreadState_Swap(tstate);
526
Victor Stinner99fcc612019-04-29 13:04:07 +0200527 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
528 destroying the GIL might fail when it is being referenced from
529 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000530 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000531 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner09532fe2019-05-10 23:39:09 +0200532 _PyEval_FiniThreads(&runtime->ceval);
Victor Stinner2914bb32018-01-29 11:57:45 +0100533
Nick Coghland6009512014-11-20 21:39:37 +1000534 /* Auto-thread-state API */
Victor Stinner43125222019-04-24 18:23:53 +0200535 _PyGILState_Init(runtime, interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000536
Victor Stinner2914bb32018-01-29 11:57:45 +0100537 /* Create the GIL */
538 PyEval_InitThreads();
539
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100540 return _Py_INIT_OK();
541}
Nick Coghland6009512014-11-20 21:39:37 +1000542
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100543
544static _PyInitError
545pycore_init_types(void)
546{
Victor Stinnerab672812019-01-23 15:04:40 +0100547 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100548 if (_Py_INIT_FAILED(err)) {
549 return err;
550 }
551
552 err = _PyUnicode_Init();
553 if (_Py_INIT_FAILED(err)) {
554 return err;
555 }
556
557 if (_PyStructSequence_Init() < 0) {
558 return _Py_INIT_ERR("can't initialize structseq");
559 }
560
561 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800562 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100563 }
Nick Coghland6009512014-11-20 21:39:37 +1000564
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100565 err = _PyExc_Init();
566 if (_Py_INIT_FAILED(err)) {
567 return err;
568 }
569
570 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800571 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100572 }
Nick Coghland6009512014-11-20 21:39:37 +1000573
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100574 if (!_PyContext_Init()) {
575 return _Py_INIT_ERR("can't init context");
576 }
577 return _Py_INIT_OK();
578}
579
580
581static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100582pycore_init_builtins(PyInterpreterState *interp)
583{
584 PyObject *bimod = _PyBuiltin_Init();
585 if (bimod == NULL) {
586 return _Py_INIT_ERR("can't initialize builtins modules");
587 }
588 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
589
590 interp->builtins = PyModule_GetDict(bimod);
591 if (interp->builtins == NULL) {
592 return _Py_INIT_ERR("can't initialize builtins dict");
593 }
594 Py_INCREF(interp->builtins);
595
596 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
597 if (_Py_INIT_FAILED(err)) {
598 return err;
599 }
600 return _Py_INIT_OK();
601}
602
603
604static _PyInitError
605pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
606{
607 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800608 if (_Py_INIT_FAILED(err)) {
609 return err;
610 }
Nick Coghland6009512014-11-20 21:39:37 +1000611
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800612 err = _PyImportHooks_Init();
613 if (_Py_INIT_FAILED(err)) {
614 return err;
615 }
Nick Coghland6009512014-11-20 21:39:37 +1000616
617 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100618 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100619 return _Py_INIT_ERR("can't initialize warnings");
620 }
Nick Coghland6009512014-11-20 21:39:37 +1000621
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100622 if (interp->core_config._install_importlib) {
623 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200624 if (_Py_INIT_FAILED(err)) {
625 return err;
626 }
627 }
628
Eric Snow1abcf672017-05-23 21:46:51 -0700629 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100630 if (interp->core_config._install_importlib) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400631 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800632 if (_Py_INIT_FAILED(err)) {
633 return err;
634 }
Eric Snow1abcf672017-05-23 21:46:51 -0700635 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100636 return _Py_INIT_OK();
637}
638
639
640static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200641_Py_InitializeCore_impl(_PyRuntimeState *runtime,
642 PyInterpreterState **interp_p,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100643 const _PyCoreConfig *core_config)
644{
645 PyInterpreterState *interp;
646
Victor Stinner43125222019-04-24 18:23:53 +0200647 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100648
Victor Stinner43125222019-04-24 18:23:53 +0200649 _PyInitError err = pycore_init_runtime(runtime, core_config);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100650 if (_Py_INIT_FAILED(err)) {
651 return err;
652 }
653
Victor Stinner43125222019-04-24 18:23:53 +0200654 err = pycore_create_interpreter(runtime, core_config, &interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100655 if (_Py_INIT_FAILED(err)) {
656 return err;
657 }
658 core_config = &interp->core_config;
659 *interp_p = interp;
660
661 err = pycore_init_types();
662 if (_Py_INIT_FAILED(err)) {
663 return err;
664 }
665
666 PyObject *sysmod;
Victor Stinner43125222019-04-24 18:23:53 +0200667 err = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100668 if (_Py_INIT_FAILED(err)) {
669 return err;
670 }
671
672 err = pycore_init_builtins(interp);
673 if (_Py_INIT_FAILED(err)) {
674 return err;
675 }
676
677 err = pycore_init_import_warnings(interp, sysmod);
678 if (_Py_INIT_FAILED(err)) {
679 return err;
680 }
Eric Snow1abcf672017-05-23 21:46:51 -0700681
682 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200683 runtime->core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800684 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700685}
686
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100687
Victor Stinner70005ac2019-05-02 15:25:34 -0400688_PyInitError
689_Py_PreInitializeFromPyArgv(const _PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100690{
691 _PyInitError err;
692
693 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100694 if (_Py_INIT_FAILED(err)) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100695 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100696 }
Victor Stinner43125222019-04-24 18:23:53 +0200697 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100698
Victor Stinner43125222019-04-24 18:23:53 +0200699 if (runtime->pre_initialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100700 /* If it's already configured: ignored the new configuration */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100701 return _Py_INIT_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100702 }
703
Victor Stinnercab5d072019-05-17 19:01:14 +0200704 _PyPreConfig config;
705 _PyPreConfig_Init(&config);
Victor Stinner5ac27a52019-03-27 13:40:14 +0100706
Victor Stinnerf72346c2019-03-25 17:54:58 +0100707 if (src_config) {
Victor Stinnerb5947842019-05-18 00:38:16 +0200708 _PyPreConfig_Copy(&config, src_config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100709 }
710
Victor Stinner5ac27a52019-03-27 13:40:14 +0100711 err = _PyPreConfig_Read(&config, args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100712 if (_Py_INIT_FAILED(err)) {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200713 return err;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100714 }
715
Victor Stinner5ac27a52019-03-27 13:40:14 +0100716 err = _PyPreConfig_Write(&config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100717 if (_Py_INIT_FAILED(err)) {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200718 return err;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100719 }
720
Victor Stinner43125222019-04-24 18:23:53 +0200721 runtime->pre_initialized = 1;
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200722 return _Py_INIT_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100723}
724
Victor Stinner70005ac2019-05-02 15:25:34 -0400725
Victor Stinnerf72346c2019-03-25 17:54:58 +0100726_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +0200727_Py_PreInitializeFromArgs(const _PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100728{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100729 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400730 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100731}
732
733
734_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +0200735_Py_PreInitializeFromWideArgs(const _PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100736{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100737 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400738 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100739}
740
741
742_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100743_Py_PreInitialize(const _PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100744{
Victor Stinner70005ac2019-05-02 15:25:34 -0400745 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100746}
747
748
749_PyInitError
Victor Stinner70005ac2019-05-02 15:25:34 -0400750_Py_PreInitializeFromCoreConfig(const _PyCoreConfig *coreconfig,
751 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100752{
Victor Stinnercab5d072019-05-17 19:01:14 +0200753 _PyPreConfig config;
754 _PyPreConfig_Init(&config);
Victor Stinner70005ac2019-05-02 15:25:34 -0400755 if (coreconfig != NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200756 _PyPreConfig_GetCoreConfig(&config, coreconfig);
Victor Stinner70005ac2019-05-02 15:25:34 -0400757 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200758
759 if (args == NULL && coreconfig != NULL && coreconfig->parse_argv) {
760 _PyArgv config_args = {
761 .use_bytes_argv = 0,
762 .argc = coreconfig->argv.length,
763 .wchar_argv = coreconfig->argv.items};
764 return _Py_PreInitializeFromPyArgv(&config, &config_args);
765 }
766 else {
767 return _Py_PreInitializeFromPyArgv(&config, args);
768 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100769}
770
771
772static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200773pyinit_coreconfig(_PyRuntimeState *runtime,
774 _PyCoreConfig *config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100775 const _PyCoreConfig *src_config,
776 const _PyArgv *args,
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100777 PyInterpreterState **interp_p)
778{
Victor Stinner5f38b842019-05-01 02:30:12 +0200779 _PyInitError err;
780
Victor Stinnerd929f182019-03-27 18:28:46 +0100781 if (src_config) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200782 err = _PyCoreConfig_Copy(config, src_config);
783 if (_Py_INIT_FAILED(err)) {
784 return err;
Victor Stinnerd929f182019-03-27 18:28:46 +0100785 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100786 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100787
Victor Stinner5f38b842019-05-01 02:30:12 +0200788 if (args) {
789 err = _PyCoreConfig_SetPyArgv(config, args);
790 if (_Py_INIT_FAILED(err)) {
791 return err;
792 }
793 }
794
795 err = _PyCoreConfig_Read(config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100796 if (_Py_INIT_FAILED(err)) {
797 return err;
798 }
799
Victor Stinner43125222019-04-24 18:23:53 +0200800 if (!runtime->core_initialized) {
801 return _Py_InitializeCore_impl(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100802 }
803 else {
Victor Stinner43125222019-04-24 18:23:53 +0200804 return _Py_Initialize_ReconfigureCore(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100805 }
806}
807
808
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100809/* Begin interpreter initialization
810 *
811 * On return, the first thread and interpreter state have been created,
812 * but the compiler, signal handling, multithreading and
813 * multiple interpreter support, and codec infrastructure are not yet
814 * available.
815 *
816 * The import system will support builtin and frozen modules only.
817 * The only supported io is writing to sys.stderr
818 *
819 * If any operation invoked by this function fails, a fatal error is
820 * issued and the function does not return.
821 *
822 * Any code invoked from this function should *not* assume it has access
823 * to the Python C API (unless the API is explicitly listed as being
824 * safe to call without calling Py_Initialize first)
825 */
Victor Stinner484f20d2019-03-27 02:04:16 +0100826static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200827_Py_InitializeCore(_PyRuntimeState *runtime,
828 const _PyCoreConfig *src_config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100829 const _PyArgv *args,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100830 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200831{
Victor Stinnerd929f182019-03-27 18:28:46 +0100832 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200833
Victor Stinner70005ac2019-05-02 15:25:34 -0400834 err = _Py_PreInitializeFromCoreConfig(src_config, args);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200835 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100836 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200837 }
838
Victor Stinnercab5d072019-05-17 19:01:14 +0200839 _PyCoreConfig local_config;
840 _PyCoreConfig_Init(&local_config);
Victor Stinner43125222019-04-24 18:23:53 +0200841 err = pyinit_coreconfig(runtime, &local_config, src_config, args, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100842 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200843 return err;
844}
845
Victor Stinner5ac27a52019-03-27 13:40:14 +0100846
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200847/* Py_Initialize() has already been called: update the main interpreter
848 configuration. Example of bpo-34008: Py_Main() called after
849 Py_Initialize(). */
850static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100851_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200852{
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100853 _PyCoreConfig *core_config = &interp->core_config;
854
855 PyObject *argv = _PyWstrList_AsList(&core_config->argv);
856 if (argv == NULL) {
857 return _Py_INIT_NO_MEMORY(); \
858 }
859
860 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
861 Py_DECREF(argv);
862 if (res < 0) {
863 return _Py_INIT_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200864 }
865 return _Py_INIT_OK();
866}
867
Eric Snowc7ec9982017-05-23 23:00:52 -0700868/* Update interpreter state based on supplied configuration settings
869 *
870 * After calling this function, most of the restrictions on the interpreter
871 * are lifted. The only remaining incomplete settings are those related
872 * to the main module (sys.argv[0], __main__ metadata)
873 *
874 * Calling this when the interpreter is not initializing, is already
875 * initialized or without a valid current thread state is a fatal error.
876 * Other errors should be reported as normal Python exceptions with a
877 * non-zero return code.
878 */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100879static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200880_Py_InitializeMainInterpreter(_PyRuntimeState *runtime,
881 PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700882{
Victor Stinner43125222019-04-24 18:23:53 +0200883 if (!runtime->core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800884 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700885 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700886
Victor Stinner1dc6e392018-07-25 02:49:17 +0200887 /* Configure the main interpreter */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200888 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700889
Victor Stinner43125222019-04-24 18:23:53 +0200890 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100891 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200892 }
893
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200894 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700895 /* Special mode for freeze_importlib: run with no import system
896 *
897 * This means anything which needs support from extension modules
898 * or pure Python code in the standard library won't work.
899 */
Victor Stinner43125222019-04-24 18:23:53 +0200900 runtime->initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800901 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700902 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100903
Victor Stinner33c377e2017-12-05 15:12:41 +0100904 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800905 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100906 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200907
Victor Stinner43125222019-04-24 18:23:53 +0200908 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800909 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100910 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800911
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400912 _PyInitError err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 if (_Py_INIT_FAILED(err)) {
914 return err;
915 }
Nick Coghland6009512014-11-20 21:39:37 +1000916
917 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200918 err = _PyFaulthandler_Init(core_config->faulthandler);
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 Stinner43fc3bb2019-05-02 11:54:20 -0400923 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800924 if (_Py_INIT_FAILED(err)) {
925 return err;
926 }
Nick Coghland6009512014-11-20 21:39:37 +1000927
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100928 if (core_config->install_signal_handlers) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400929 err = init_signals();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800930 if (_Py_INIT_FAILED(err)) {
931 return err;
932 }
933 }
Nick Coghland6009512014-11-20 21:39:37 +1000934
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200935 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800936 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200937 }
Nick Coghland6009512014-11-20 21:39:37 +1000938
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800939 err = add_main_module(interp);
940 if (_Py_INIT_FAILED(err)) {
941 return err;
942 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800943
Victor Stinner91106cd2017-12-13 12:29:09 +0100944 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800945 if (_Py_INIT_FAILED(err)) {
946 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800947 }
Nick Coghland6009512014-11-20 21:39:37 +1000948
949 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100950 PyObject *warnoptions = PySys_GetObject("warnoptions");
951 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100952 {
Nick Coghland6009512014-11-20 21:39:37 +1000953 PyObject *warnings_module = PyImport_ImportModule("warnings");
954 if (warnings_module == NULL) {
955 fprintf(stderr, "'import warnings' failed; traceback:\n");
956 PyErr_Print();
957 }
958 Py_XDECREF(warnings_module);
959 }
960
Victor Stinner43125222019-04-24 18:23:53 +0200961 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700962
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200963 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400964 err = init_import_size(); /* Module site */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800965 if (_Py_INIT_FAILED(err)) {
966 return err;
967 }
968 }
Victor Stinnercf215042018-08-29 22:56:06 +0200969
970#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200971 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200972#endif
973
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800974 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000975}
976
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200977
978_PyInitError
979_Py_InitializeMain(void)
980{
981 _PyInitError err = _PyRuntime_Initialize();
982 if (_Py_INIT_FAILED(err)) {
983 return err;
984 }
985 _PyRuntimeState *runtime = &_PyRuntime;
986 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
987
988 return _Py_InitializeMainInterpreter(runtime, interp);
989}
990
991
Eric Snowc7ec9982017-05-23 23:00:52 -0700992#undef _INIT_DEBUG_PRINT
993
Victor Stinner5ac27a52019-03-27 13:40:14 +0100994static _PyInitError
995init_python(const _PyCoreConfig *config, const _PyArgv *args)
Eric Snow1abcf672017-05-23 21:46:51 -0700996{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800997 _PyInitError err;
Victor Stinner43125222019-04-24 18:23:53 +0200998
999 err = _PyRuntime_Initialize();
1000 if (_Py_INIT_FAILED(err)) {
1001 return err;
1002 }
1003 _PyRuntimeState *runtime = &_PyRuntime;
1004
1005 PyInterpreterState *interp = NULL;
1006 err = _Py_InitializeCore(runtime, config, args, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001007 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001008 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001009 }
Victor Stinner1dc6e392018-07-25 02:49:17 +02001010 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001011
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001012 if (config->_init_main) {
Victor Stinner43125222019-04-24 18:23:53 +02001013 err = _Py_InitializeMainInterpreter(runtime, interp);
Victor Stinner484f20d2019-03-27 02:04:16 +01001014 if (_Py_INIT_FAILED(err)) {
1015 return err;
1016 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001017 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001018
Victor Stinner1dc6e392018-07-25 02:49:17 +02001019 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001020}
1021
1022
Victor Stinner5ac27a52019-03-27 13:40:14 +01001023_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +02001024_Py_InitializeFromArgs(const _PyCoreConfig *config, Py_ssize_t argc, char **argv)
Victor Stinner5ac27a52019-03-27 13:40:14 +01001025{
1026 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1027 return init_python(config, &args);
1028}
1029
1030
1031_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +02001032_Py_InitializeFromWideArgs(const _PyCoreConfig *config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner5ac27a52019-03-27 13:40:14 +01001033{
1034 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1035 return init_python(config, &args);
1036}
1037
1038
1039_PyInitError
1040_Py_InitializeFromConfig(const _PyCoreConfig *config)
1041{
1042 return init_python(config, NULL);
1043}
1044
1045
Eric Snow1abcf672017-05-23 21:46:51 -07001046void
Nick Coghland6009512014-11-20 21:39:37 +10001047Py_InitializeEx(int install_sigs)
1048{
Victor Stinner43125222019-04-24 18:23:53 +02001049 _PyInitError err;
1050
1051 err = _PyRuntime_Initialize();
1052 if (_Py_INIT_FAILED(err)) {
1053 _Py_ExitInitError(err);
1054 }
1055 _PyRuntimeState *runtime = &_PyRuntime;
1056
1057 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001058 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1059 return;
1060 }
1061
Victor Stinnercab5d072019-05-17 19:01:14 +02001062 _PyCoreConfig config;
1063 _PyCoreConfig_Init(&config);
Victor Stinner1dc6e392018-07-25 02:49:17 +02001064 config.install_signal_handlers = install_sigs;
1065
Victor Stinner43125222019-04-24 18:23:53 +02001066 err = _Py_InitializeFromConfig(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001067 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001068 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001069 }
Nick Coghland6009512014-11-20 21:39:37 +10001070}
1071
1072void
1073Py_Initialize(void)
1074{
1075 Py_InitializeEx(1);
1076}
1077
1078
1079#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001080extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001081#endif
1082
1083/* Flush stdout and stderr */
1084
1085static int
1086file_is_closed(PyObject *fobj)
1087{
1088 int r;
1089 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1090 if (tmp == NULL) {
1091 PyErr_Clear();
1092 return 0;
1093 }
1094 r = PyObject_IsTrue(tmp);
1095 Py_DECREF(tmp);
1096 if (r < 0)
1097 PyErr_Clear();
1098 return r > 0;
1099}
1100
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001101static int
Nick Coghland6009512014-11-20 21:39:37 +10001102flush_std_files(void)
1103{
1104 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1105 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1106 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001107 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001108
1109 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001110 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001111 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001112 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001113 status = -1;
1114 }
Nick Coghland6009512014-11-20 21:39:37 +10001115 else
1116 Py_DECREF(tmp);
1117 }
1118
1119 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001120 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001121 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001122 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001123 status = -1;
1124 }
Nick Coghland6009512014-11-20 21:39:37 +10001125 else
1126 Py_DECREF(tmp);
1127 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001128
1129 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001130}
1131
1132/* Undo the effect of Py_Initialize().
1133
1134 Beware: if multiple interpreter and/or thread states exist, these
1135 are not wiped out; only the current thread and interpreter state
1136 are deleted. But since everything else is deleted, those other
1137 interpreter and thread states should no longer be used.
1138
1139 (XXX We should do better, e.g. wipe out all interpreters and
1140 threads.)
1141
1142 Locking: as above.
1143
1144*/
1145
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001146int
1147Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001148{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001149 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001150
Victor Stinner8e91c242019-04-24 17:24:01 +02001151 _PyRuntimeState *runtime = &_PyRuntime;
1152 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001153 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001154 }
Nick Coghland6009512014-11-20 21:39:37 +10001155
Eric Snow842a2f02019-03-15 15:47:51 -06001156 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001157 wait_for_thread_shutdown();
1158
Eric Snow842a2f02019-03-15 15:47:51 -06001159 // Make any remaining pending calls.
Victor Stinner09532fe2019-05-10 23:39:09 +02001160 _Py_FinishPendingCalls(runtime);
Eric Snow842a2f02019-03-15 15:47:51 -06001161
Victor Stinner8e91c242019-04-24 17:24:01 +02001162 /* Get current thread state and interpreter pointer */
Victor Stinner09532fe2019-05-10 23:39:09 +02001163 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001164 PyInterpreterState *interp = tstate->interp;
1165
Nick Coghland6009512014-11-20 21:39:37 +10001166 /* The interpreter is still entirely intact at this point, and the
1167 * exit funcs may be relying on that. In particular, if some thread
1168 * or exit func is still waiting to do an import, the import machinery
1169 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001170 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001171 * Note that Threading.py uses an exit func to do a join on all the
1172 * threads created thru it, so this also protects pending imports in
1173 * the threads created via Threading.
1174 */
Nick Coghland6009512014-11-20 21:39:37 +10001175
Marcel Plch776407f2017-12-20 11:17:58 +01001176 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001177
Victor Stinnerda273412017-12-15 01:46:02 +01001178 /* Copy the core config, PyInterpreterState_Delete() free
1179 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001180#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001181 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001182#endif
1183#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001184 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001185#endif
1186#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001187 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001188#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001189
Nick Coghland6009512014-11-20 21:39:37 +10001190 /* Remaining threads (e.g. daemon threads) will automatically exit
1191 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001192 runtime->finalizing = tstate;
1193 runtime->initialized = 0;
1194 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001195
Victor Stinnere0deff32015-03-24 13:46:18 +01001196 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001197 if (flush_std_files() < 0) {
1198 status = -1;
1199 }
Nick Coghland6009512014-11-20 21:39:37 +10001200
1201 /* Disable signal handling */
1202 PyOS_FiniInterrupts();
1203
1204 /* Collect garbage. This may call finalizers; it's nice to call these
1205 * before all modules are destroyed.
1206 * XXX If a __del__ or weakref callback is triggered here, and tries to
1207 * XXX import a module, bad things can happen, because Python no
1208 * XXX longer believes it's initialized.
1209 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1210 * XXX is easy to provoke that way. I've also seen, e.g.,
1211 * XXX Exception exceptions.ImportError: 'No module named sha'
1212 * XXX in <function callback at 0x008F5718> ignored
1213 * XXX but I'm unclear on exactly how that one happens. In any case,
1214 * XXX I haven't seen a real-life report of either of these.
1215 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001216 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001217#ifdef COUNT_ALLOCS
1218 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1219 each collection might release some types from the type
1220 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001221 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001222 /* nothing */;
1223#endif
Eric Snowdae02762017-09-14 00:35:58 -07001224
Nick Coghland6009512014-11-20 21:39:37 +10001225 /* Destroy all modules */
1226 PyImport_Cleanup();
1227
Victor Stinnere0deff32015-03-24 13:46:18 +01001228 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001229 if (flush_std_files() < 0) {
1230 status = -1;
1231 }
Nick Coghland6009512014-11-20 21:39:37 +10001232
1233 /* Collect final garbage. This disposes of cycles created by
1234 * class definitions, for example.
1235 * XXX This is disabled because it caused too many problems. If
1236 * XXX a __del__ or weakref callback triggers here, Python code has
1237 * XXX a hard time running, because even the sys module has been
1238 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1239 * XXX One symptom is a sequence of information-free messages
1240 * XXX coming from threads (if a __del__ or callback is invoked,
1241 * XXX other threads can execute too, and any exception they encounter
1242 * XXX triggers a comedy of errors as subsystem after subsystem
1243 * XXX fails to find what it *expects* to find in sys to help report
1244 * XXX the exception and consequent unexpected failures). I've also
1245 * XXX seen segfaults then, after adding print statements to the
1246 * XXX Python code getting called.
1247 */
1248#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001249 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001250#endif
1251
1252 /* Disable tracemalloc after all Python objects have been destroyed,
1253 so it is possible to use tracemalloc in objects destructor. */
1254 _PyTraceMalloc_Fini();
1255
1256 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1257 _PyImport_Fini();
1258
1259 /* Cleanup typeobject.c's internal caches. */
1260 _PyType_Fini();
1261
1262 /* unload faulthandler module */
1263 _PyFaulthandler_Fini();
1264
1265 /* Debugging stuff */
1266#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001267 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001268#endif
1269 /* dump hash stats */
1270 _PyHash_Fini();
1271
Eric Snowdae02762017-09-14 00:35:58 -07001272#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001273 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001274 _PyDebug_PrintTotalRefs();
1275 }
Eric Snowdae02762017-09-14 00:35:58 -07001276#endif
Nick Coghland6009512014-11-20 21:39:37 +10001277
1278#ifdef Py_TRACE_REFS
1279 /* Display all objects still alive -- this can invoke arbitrary
1280 * __repr__ overrides, so requires a mostly-intact interpreter.
1281 * Alas, a lot of stuff may still be alive now that will be cleaned
1282 * up later.
1283 */
Victor Stinnerda273412017-12-15 01:46:02 +01001284 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001285 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001286 }
Nick Coghland6009512014-11-20 21:39:37 +10001287#endif /* Py_TRACE_REFS */
1288
1289 /* Clear interpreter state and all thread states. */
1290 PyInterpreterState_Clear(interp);
1291
1292 /* Now we decref the exception classes. After this point nothing
1293 can raise an exception. That's okay, because each Fini() method
1294 below has been checked to make sure no exceptions are ever
1295 raised.
1296 */
1297
1298 _PyExc_Fini();
1299
1300 /* Sundry finalizers */
1301 PyMethod_Fini();
1302 PyFrame_Fini();
1303 PyCFunction_Fini();
1304 PyTuple_Fini();
1305 PyList_Fini();
1306 PySet_Fini();
1307 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001308 PyLong_Fini();
1309 PyFloat_Fini();
1310 PyDict_Fini();
1311 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001312 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001313 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001314 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001315 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001316 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001317 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001318
1319 /* Cleanup Unicode implementation */
1320 _PyUnicode_Fini();
1321
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001322 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001323
1324 /* XXX Still allocated:
1325 - various static ad-hoc pointers to interned strings
1326 - int and float free list blocks
1327 - whatever various modules and libraries allocate
1328 */
1329
1330 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1331
1332 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001333 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001334
1335 /* Delete current thread. After this, many C API calls become crashy. */
1336 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001337
Nick Coghland6009512014-11-20 21:39:37 +10001338 PyInterpreterState_Delete(interp);
1339
1340#ifdef Py_TRACE_REFS
1341 /* Display addresses (& refcnts) of all objects still alive.
1342 * An address can be used to find the repr of the object, printed
1343 * above by _Py_PrintReferences.
1344 */
Victor Stinnerda273412017-12-15 01:46:02 +01001345 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001346 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001347 }
Nick Coghland6009512014-11-20 21:39:37 +10001348#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001349#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001350 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001351 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001352 }
Nick Coghland6009512014-11-20 21:39:37 +10001353#endif
1354
Victor Stinner8e91c242019-04-24 17:24:01 +02001355 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001356
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001357 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001358 return status;
1359}
1360
1361void
1362Py_Finalize(void)
1363{
1364 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001365}
1366
1367/* Create and initialize a new interpreter and thread, and return the
1368 new thread. This requires that Py_Initialize() has been called
1369 first.
1370
1371 Unsuccessful initialization yields a NULL pointer. Note that *no*
1372 exception information is available even in this case -- the
1373 exception information is held in the thread, and there is no
1374 thread.
1375
1376 Locking: as above.
1377
1378*/
1379
Victor Stinnera7368ac2017-11-15 18:11:45 -08001380static _PyInitError
1381new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001382{
Victor Stinner9316ee42017-11-25 03:17:57 +01001383 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001384
Victor Stinner43125222019-04-24 18:23:53 +02001385 err = _PyRuntime_Initialize();
1386 if (_Py_INIT_FAILED(err)) {
1387 return err;
1388 }
1389 _PyRuntimeState *runtime = &_PyRuntime;
1390
1391 if (!runtime->initialized) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001392 return _Py_INIT_ERR("Py_Initialize must be called first");
1393 }
Nick Coghland6009512014-11-20 21:39:37 +10001394
Victor Stinner8a1be612016-03-14 22:07:55 +01001395 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1396 interpreters: disable PyGILState_Check(). */
1397 _PyGILState_check_enabled = 0;
1398
Victor Stinner43125222019-04-24 18:23:53 +02001399 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001400 if (interp == NULL) {
1401 *tstate_p = NULL;
1402 return _Py_INIT_OK();
1403 }
Nick Coghland6009512014-11-20 21:39:37 +10001404
Victor Stinner43125222019-04-24 18:23:53 +02001405 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001406 if (tstate == NULL) {
1407 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001408 *tstate_p = NULL;
1409 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001410 }
1411
Victor Stinner43125222019-04-24 18:23:53 +02001412 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001413
Eric Snow1abcf672017-05-23 21:46:51 -07001414 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001415 _PyCoreConfig *core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001416 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001417 core_config = &save_tstate->interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001418 } else {
1419 /* No current thread state, copy from the main interpreter */
1420 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001421 core_config = &main_interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001422 }
1423
Victor Stinner1a9f0d82019-05-01 15:22:52 +02001424 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
1425 if (_Py_INIT_FAILED(err)) {
1426 return err;
Victor Stinnerda273412017-12-15 01:46:02 +01001427 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001428 core_config = &interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001429
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001430 err = _PyExc_Init();
1431 if (_Py_INIT_FAILED(err)) {
1432 return err;
1433 }
1434
Nick Coghland6009512014-11-20 21:39:37 +10001435 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001436 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001437 if (modules == NULL) {
1438 return _Py_INIT_ERR("can't make modules dictionary");
1439 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001440 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001441
Victor Stinner43125222019-04-24 18:23:53 +02001442 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001443 if (sysmod != NULL) {
1444 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001445 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001446 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001447 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001448 Py_INCREF(interp->sysdict);
1449 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner43125222019-04-24 18:23:53 +02001450 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerab672812019-01-23 15:04:40 +01001451 return _Py_INIT_ERR("can't finish initializing sys");
1452 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001453 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001454 else if (PyErr_Occurred()) {
1455 goto handle_error;
1456 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001457
Victor Stinner43125222019-04-24 18:23:53 +02001458 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001459 if (bimod != NULL) {
1460 interp->builtins = PyModule_GetDict(bimod);
1461 if (interp->builtins == NULL)
1462 goto handle_error;
1463 Py_INCREF(interp->builtins);
1464 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001465 else if (PyErr_Occurred()) {
1466 goto handle_error;
1467 }
Nick Coghland6009512014-11-20 21:39:37 +10001468
Nick Coghland6009512014-11-20 21:39:37 +10001469 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001470 err = _PyBuiltins_AddExceptions(bimod);
1471 if (_Py_INIT_FAILED(err)) {
1472 return err;
1473 }
Nick Coghland6009512014-11-20 21:39:37 +10001474
Victor Stinnerab672812019-01-23 15:04:40 +01001475 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1476 if (_Py_INIT_FAILED(err)) {
1477 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001478 }
Nick Coghland6009512014-11-20 21:39:37 +10001479
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001480 err = _PyImportHooks_Init();
1481 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001482 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001483 }
Nick Coghland6009512014-11-20 21:39:37 +10001484
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001485 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001486 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001487 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001488 }
Nick Coghland6009512014-11-20 21:39:37 +10001489
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001490 err = init_importlib_external(interp);
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 }
Nick Coghland6009512014-11-20 21:39:37 +10001494
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001495 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001496 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001497 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498 }
1499
Victor Stinner91106cd2017-12-13 12:29:09 +01001500 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001501 if (_Py_INIT_FAILED(err)) {
1502 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001503 }
1504
1505 err = add_main_module(interp);
1506 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001507 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001508 }
1509
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001510 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001511 err = init_import_size();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001512 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001513 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001514 }
1515 }
Nick Coghland6009512014-11-20 21:39:37 +10001516 }
1517
Victor Stinnera7368ac2017-11-15 18:11:45 -08001518 if (PyErr_Occurred()) {
1519 goto handle_error;
1520 }
Nick Coghland6009512014-11-20 21:39:37 +10001521
Victor Stinnera7368ac2017-11-15 18:11:45 -08001522 *tstate_p = tstate;
1523 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524
Nick Coghland6009512014-11-20 21:39:37 +10001525handle_error:
1526 /* Oops, it didn't work. Undo it all. */
1527
1528 PyErr_PrintEx(0);
1529 PyThreadState_Clear(tstate);
1530 PyThreadState_Swap(save_tstate);
1531 PyThreadState_Delete(tstate);
1532 PyInterpreterState_Delete(interp);
1533
Victor Stinnera7368ac2017-11-15 18:11:45 -08001534 *tstate_p = NULL;
1535 return _Py_INIT_OK();
1536}
1537
1538PyThreadState *
1539Py_NewInterpreter(void)
1540{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001541 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001542 _PyInitError err = new_interpreter(&tstate);
1543 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001544 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001545 }
1546 return tstate;
1547
Nick Coghland6009512014-11-20 21:39:37 +10001548}
1549
1550/* Delete an interpreter and its last thread. This requires that the
1551 given thread state is current, that the thread has no remaining
1552 frames, and that it is its interpreter's only remaining thread.
1553 It is a fatal error to violate these constraints.
1554
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001555 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001556 everything, regardless.)
1557
1558 Locking: as above.
1559
1560*/
1561
1562void
1563Py_EndInterpreter(PyThreadState *tstate)
1564{
1565 PyInterpreterState *interp = tstate->interp;
1566
Victor Stinner50b48572018-11-01 01:51:40 +01001567 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001568 Py_FatalError("Py_EndInterpreter: thread is not current");
1569 if (tstate->frame != NULL)
1570 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001571 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001572
Eric Snow842a2f02019-03-15 15:47:51 -06001573 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001574 wait_for_thread_shutdown();
1575
Marcel Plch776407f2017-12-20 11:17:58 +01001576 call_py_exitfuncs(interp);
1577
Nick Coghland6009512014-11-20 21:39:37 +10001578 if (tstate != interp->tstate_head || tstate->next != NULL)
1579 Py_FatalError("Py_EndInterpreter: not the last thread");
1580
1581 PyImport_Cleanup();
1582 PyInterpreterState_Clear(interp);
1583 PyThreadState_Swap(NULL);
1584 PyInterpreterState_Delete(interp);
1585}
1586
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001587/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001588
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001589static _PyInitError
1590add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001591{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001592 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001593 m = PyImport_AddModule("__main__");
1594 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001595 return _Py_INIT_ERR("can't create __main__ module");
1596
Nick Coghland6009512014-11-20 21:39:37 +10001597 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001598 ann_dict = PyDict_New();
1599 if ((ann_dict == NULL) ||
1600 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001601 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001602 }
1603 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001604
Nick Coghland6009512014-11-20 21:39:37 +10001605 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1606 PyObject *bimod = PyImport_ImportModule("builtins");
1607 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001608 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001609 }
1610 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001611 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001612 }
1613 Py_DECREF(bimod);
1614 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001615
Nick Coghland6009512014-11-20 21:39:37 +10001616 /* Main is a little special - imp.is_builtin("__main__") will return
1617 * False, but BuiltinImporter is still the most appropriate initial
1618 * setting for its __loader__ attribute. A more suitable value will
1619 * be set if __main__ gets further initialized later in the startup
1620 * process.
1621 */
1622 loader = PyDict_GetItemString(d, "__loader__");
1623 if (loader == NULL || loader == Py_None) {
1624 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1625 "BuiltinImporter");
1626 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001627 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001628 }
1629 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001630 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001631 }
1632 Py_DECREF(loader);
1633 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001634 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001635}
1636
Nick Coghland6009512014-11-20 21:39:37 +10001637/* Import the site module (not into __main__ though) */
1638
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001639static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001640init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001641{
1642 PyObject *m;
1643 m = PyImport_ImportModule("site");
1644 if (m == NULL) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001645 return _Py_INIT_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001646 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001647 Py_DECREF(m);
1648 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001649}
1650
Victor Stinner874dbe82015-09-04 17:29:57 +02001651/* Check if a file descriptor is valid or not.
1652 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1653static int
1654is_valid_fd(int fd)
1655{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001656/* dup() is faster than fstat(): fstat() can require input/output operations,
1657 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1658 startup. Problem: dup() doesn't check if the file descriptor is valid on
1659 some platforms.
1660
1661 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1662 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1663 EBADF. FreeBSD has similar issue (bpo-32849).
1664
1665 Only use dup() on platforms where dup() is enough to detect invalid FD in
1666 corner cases: on Linux and Windows (bpo-32849). */
1667#if defined(__linux__) || defined(MS_WINDOWS)
1668 if (fd < 0) {
1669 return 0;
1670 }
1671 int fd2;
1672
1673 _Py_BEGIN_SUPPRESS_IPH
1674 fd2 = dup(fd);
1675 if (fd2 >= 0) {
1676 close(fd2);
1677 }
1678 _Py_END_SUPPRESS_IPH
1679
1680 return (fd2 >= 0);
1681#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001682 struct stat st;
1683 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001684#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001685}
1686
1687/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001688static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001689create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001690 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001691 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001692{
1693 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1694 const char* mode;
1695 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001696 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001697 int buffering, isatty;
1698 _Py_IDENTIFIER(open);
1699 _Py_IDENTIFIER(isatty);
1700 _Py_IDENTIFIER(TextIOWrapper);
1701 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001702 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001703
Victor Stinner874dbe82015-09-04 17:29:57 +02001704 if (!is_valid_fd(fd))
1705 Py_RETURN_NONE;
1706
Nick Coghland6009512014-11-20 21:39:37 +10001707 /* stdin is always opened in buffered mode, first because it shouldn't
1708 make a difference in common use cases, second because TextIOWrapper
1709 depends on the presence of a read1() method which only exists on
1710 buffered streams.
1711 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001712 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001713 buffering = 0;
1714 else
1715 buffering = -1;
1716 if (write_mode)
1717 mode = "wb";
1718 else
1719 mode = "rb";
1720 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1721 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001722 Py_None, Py_None, /* encoding, errors */
1723 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001724 if (buf == NULL)
1725 goto error;
1726
1727 if (buffering) {
1728 _Py_IDENTIFIER(raw);
1729 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1730 if (raw == NULL)
1731 goto error;
1732 }
1733 else {
1734 raw = buf;
1735 Py_INCREF(raw);
1736 }
1737
Steve Dower39294992016-08-30 21:22:36 -07001738#ifdef MS_WINDOWS
1739 /* Windows console IO is always UTF-8 encoded */
1740 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001741 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001742#endif
1743
Nick Coghland6009512014-11-20 21:39:37 +10001744 text = PyUnicode_FromString(name);
1745 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1746 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001747 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001748 if (res == NULL)
1749 goto error;
1750 isatty = PyObject_IsTrue(res);
1751 Py_DECREF(res);
1752 if (isatty == -1)
1753 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001754 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001755 write_through = Py_True;
1756 else
1757 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001758 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001759 line_buffering = Py_True;
1760 else
1761 line_buffering = Py_False;
1762
1763 Py_CLEAR(raw);
1764 Py_CLEAR(text);
1765
1766#ifdef MS_WINDOWS
1767 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1768 newlines to "\n".
1769 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1770 newline = NULL;
1771#else
1772 /* sys.stdin: split lines at "\n".
1773 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1774 newline = "\n";
1775#endif
1776
Victor Stinner709d23d2019-05-02 14:56:30 -04001777 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1778 if (encoding_str == NULL) {
1779 Py_CLEAR(buf);
1780 goto error;
1781 }
1782
1783 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1784 if (errors_str == NULL) {
1785 Py_CLEAR(buf);
1786 Py_CLEAR(encoding_str);
1787 goto error;
1788 }
1789
1790 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1791 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001792 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001793 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001794 Py_CLEAR(encoding_str);
1795 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001796 if (stream == NULL)
1797 goto error;
1798
1799 if (write_mode)
1800 mode = "w";
1801 else
1802 mode = "r";
1803 text = PyUnicode_FromString(mode);
1804 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1805 goto error;
1806 Py_CLEAR(text);
1807 return stream;
1808
1809error:
1810 Py_XDECREF(buf);
1811 Py_XDECREF(stream);
1812 Py_XDECREF(text);
1813 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001814
Victor Stinner874dbe82015-09-04 17:29:57 +02001815 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1816 /* Issue #24891: the file descriptor was closed after the first
1817 is_valid_fd() check was called. Ignore the OSError and set the
1818 stream to None. */
1819 PyErr_Clear();
1820 Py_RETURN_NONE;
1821 }
1822 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001823}
1824
1825/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001826static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001827init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001828{
1829 PyObject *iomod = NULL, *wrapper;
1830 PyObject *bimod = NULL;
1831 PyObject *m;
1832 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001833 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001834 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001835 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001836 _PyCoreConfig *config = &interp->core_config;
1837
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001838 /* Check that stdin is not a directory
1839 Using shell redirection, you can redirect stdin to a directory,
1840 crashing the Python interpreter. Catch this common mistake here
1841 and output a useful error message. Note that under MS Windows,
1842 the shell already prevents that. */
1843#ifndef MS_WINDOWS
1844 struct _Py_stat_struct sb;
1845 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1846 S_ISDIR(sb.st_mode)) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001847 return _Py_INIT_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001848 }
1849#endif
1850
Nick Coghland6009512014-11-20 21:39:37 +10001851 /* Hack to avoid a nasty recursion issue when Python is invoked
1852 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1853 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1854 goto error;
1855 }
1856 Py_DECREF(m);
1857
1858 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1859 goto error;
1860 }
1861 Py_DECREF(m);
1862
1863 if (!(bimod = PyImport_ImportModule("builtins"))) {
1864 goto error;
1865 }
1866
1867 if (!(iomod = PyImport_ImportModule("io"))) {
1868 goto error;
1869 }
1870 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1871 goto error;
1872 }
1873
1874 /* Set builtins.open */
1875 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1876 Py_DECREF(wrapper);
1877 goto error;
1878 }
1879 Py_DECREF(wrapper);
1880
Nick Coghland6009512014-11-20 21:39:37 +10001881 /* Set sys.stdin */
1882 fd = fileno(stdin);
1883 /* Under some conditions stdin, stdout and stderr may not be connected
1884 * and fileno() may point to an invalid file descriptor. For example
1885 * GUI apps don't have valid standard streams by default.
1886 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001887 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001888 config->stdio_encoding,
1889 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001890 if (std == NULL)
1891 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001892 PySys_SetObject("__stdin__", std);
1893 _PySys_SetObjectId(&PyId_stdin, std);
1894 Py_DECREF(std);
1895
1896 /* Set sys.stdout */
1897 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001898 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001899 config->stdio_encoding,
1900 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001901 if (std == NULL)
1902 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001903 PySys_SetObject("__stdout__", std);
1904 _PySys_SetObjectId(&PyId_stdout, std);
1905 Py_DECREF(std);
1906
1907#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1908 /* Set sys.stderr, replaces the preliminary stderr */
1909 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001910 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001911 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001912 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001913 if (std == NULL)
1914 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001915
1916 /* Same as hack above, pre-import stderr's codec to avoid recursion
1917 when import.c tries to write to stderr in verbose mode. */
1918 encoding_attr = PyObject_GetAttrString(std, "encoding");
1919 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001920 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001921 if (std_encoding != NULL) {
1922 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1923 Py_XDECREF(codec_info);
1924 }
1925 Py_DECREF(encoding_attr);
1926 }
1927 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1928
1929 if (PySys_SetObject("__stderr__", std) < 0) {
1930 Py_DECREF(std);
1931 goto error;
1932 }
1933 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1934 Py_DECREF(std);
1935 goto error;
1936 }
1937 Py_DECREF(std);
1938#endif
1939
Victor Stinnera7368ac2017-11-15 18:11:45 -08001940 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001941
Victor Stinnera7368ac2017-11-15 18:11:45 -08001942error:
1943 res = _Py_INIT_ERR("can't initialize sys standard streams");
1944
1945done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001946 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001947
Nick Coghland6009512014-11-20 21:39:37 +10001948 Py_XDECREF(bimod);
1949 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001950 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001951}
1952
1953
Victor Stinner10dc4842015-03-24 12:01:30 +01001954static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001955_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001956{
Victor Stinner10dc4842015-03-24 12:01:30 +01001957 fputc('\n', stderr);
1958 fflush(stderr);
1959
1960 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001961 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001962}
Victor Stinner791da1c2016-03-14 16:53:12 +01001963
1964/* Print the current exception (if an exception is set) with its traceback,
1965 or display the current Python stack.
1966
1967 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1968 called on catastrophic cases.
1969
1970 Return 1 if the traceback was displayed, 0 otherwise. */
1971
1972static int
1973_Py_FatalError_PrintExc(int fd)
1974{
1975 PyObject *ferr, *res;
1976 PyObject *exception, *v, *tb;
1977 int has_tb;
1978
Victor Stinner791da1c2016-03-14 16:53:12 +01001979 PyErr_Fetch(&exception, &v, &tb);
1980 if (exception == NULL) {
1981 /* No current exception */
1982 return 0;
1983 }
1984
1985 ferr = _PySys_GetObjectId(&PyId_stderr);
1986 if (ferr == NULL || ferr == Py_None) {
1987 /* sys.stderr is not set yet or set to None,
1988 no need to try to display the exception */
1989 return 0;
1990 }
1991
1992 PyErr_NormalizeException(&exception, &v, &tb);
1993 if (tb == NULL) {
1994 tb = Py_None;
1995 Py_INCREF(tb);
1996 }
1997 PyException_SetTraceback(v, tb);
1998 if (exception == NULL) {
1999 /* PyErr_NormalizeException() failed */
2000 return 0;
2001 }
2002
2003 has_tb = (tb != Py_None);
2004 PyErr_Display(exception, v, tb);
2005 Py_XDECREF(exception);
2006 Py_XDECREF(v);
2007 Py_XDECREF(tb);
2008
2009 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002010 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002011 if (res == NULL)
2012 PyErr_Clear();
2013 else
2014 Py_DECREF(res);
2015
2016 return has_tb;
2017}
2018
Nick Coghland6009512014-11-20 21:39:37 +10002019/* Print fatal error message and abort */
2020
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002021#ifdef MS_WINDOWS
2022static void
2023fatal_output_debug(const char *msg)
2024{
2025 /* buffer of 256 bytes allocated on the stack */
2026 WCHAR buffer[256 / sizeof(WCHAR)];
2027 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2028 size_t msglen;
2029
2030 OutputDebugStringW(L"Fatal Python error: ");
2031
2032 msglen = strlen(msg);
2033 while (msglen) {
2034 size_t i;
2035
2036 if (buflen > msglen) {
2037 buflen = msglen;
2038 }
2039
2040 /* Convert the message to wchar_t. This uses a simple one-to-one
2041 conversion, assuming that the this error message actually uses
2042 ASCII only. If this ceases to be true, we will have to convert. */
2043 for (i=0; i < buflen; ++i) {
2044 buffer[i] = msg[i];
2045 }
2046 buffer[i] = L'\0';
2047 OutputDebugStringW(buffer);
2048
2049 msg += buflen;
2050 msglen -= buflen;
2051 }
2052 OutputDebugStringW(L"\n");
2053}
2054#endif
2055
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002056static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002057fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002058{
2059 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002060 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002061
2062 if (reentrant) {
2063 /* Py_FatalError() caused a second fatal error.
2064 Example: flush_std_files() raises a recursion error. */
2065 goto exit;
2066 }
2067 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002068
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002069 fprintf(stderr, "Fatal Python error: ");
2070 if (prefix) {
2071 fputs(prefix, stderr);
2072 fputs(": ", stderr);
2073 }
2074 if (msg) {
2075 fputs(msg, stderr);
2076 }
2077 else {
2078 fprintf(stderr, "<message not set>");
2079 }
2080 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002081 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002082
Victor Stinner3a228ab2018-11-01 00:26:41 +01002083 /* Check if the current thread has a Python thread state
2084 and holds the GIL */
2085 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2086 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002087 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002088 if (tss_tstate != tstate) {
2089 /* The Python thread does not hold the GIL */
2090 tss_tstate = NULL;
2091 }
2092 }
2093 else {
2094 /* Py_FatalError() has been called from a C thread
2095 which has no Python thread state. */
2096 }
2097 int has_tstate_and_gil = (tss_tstate != NULL);
2098
2099 if (has_tstate_and_gil) {
2100 /* If an exception is set, print the exception with its traceback */
2101 if (!_Py_FatalError_PrintExc(fd)) {
2102 /* No exception is set, or an exception is set without traceback */
2103 _Py_FatalError_DumpTracebacks(fd);
2104 }
2105 }
2106 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002107 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002108 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002109
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002110 /* The main purpose of faulthandler is to display the traceback.
2111 This function already did its best to display a traceback.
2112 Disable faulthandler to prevent writing a second traceback
2113 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002114 _PyFaulthandler_Fini();
2115
Victor Stinner791da1c2016-03-14 16:53:12 +01002116 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002117 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002118 /* Flush sys.stdout and sys.stderr */
2119 flush_std_files();
2120 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002121
Nick Coghland6009512014-11-20 21:39:37 +10002122#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002123 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002124#endif /* MS_WINDOWS */
2125
2126exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002127 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002128#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002129 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002130#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002131 abort();
2132 }
2133 else {
2134 exit(status);
2135 }
2136}
2137
Victor Stinner19760862017-12-20 01:41:59 +01002138void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002139Py_FatalError(const char *msg)
2140{
2141 fatal_error(NULL, msg, -1);
2142}
2143
Victor Stinner19760862017-12-20 01:41:59 +01002144void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002145_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002146{
Victor Stinnerdb719752019-05-01 05:35:33 +02002147 if (_Py_INIT_IS_EXIT(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01002148 exit(err.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002149 }
2150 else if (_Py_INIT_IS_ERROR(err)) {
2151 fatal_error(err._func, err.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002152 }
2153 else {
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002154 Py_FatalError("_Py_ExitInitError() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002155 }
Nick Coghland6009512014-11-20 21:39:37 +10002156}
2157
2158/* Clean up and exit */
2159
Victor Stinnerd7292b52016-06-17 12:29:00 +02002160# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002161
Nick Coghland6009512014-11-20 21:39:37 +10002162/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002163void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002164{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002165 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002166
Antoine Pitroufc5db952017-12-13 02:29:07 +01002167 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002168 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2169
2170 is->pyexitfunc = func;
2171 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002172}
2173
2174static void
Marcel Plch776407f2017-12-20 11:17:58 +01002175call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002176{
Marcel Plch776407f2017-12-20 11:17:58 +01002177 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002178 return;
2179
Marcel Plch776407f2017-12-20 11:17:58 +01002180 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002181 PyErr_Clear();
2182}
2183
2184/* Wait until threading._shutdown completes, provided
2185 the threading module was imported in the first place.
2186 The shutdown routine will wait until all non-daemon
2187 "threading" threads have completed. */
2188static void
2189wait_for_thread_shutdown(void)
2190{
Nick Coghland6009512014-11-20 21:39:37 +10002191 _Py_IDENTIFIER(_shutdown);
2192 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002193 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002194 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002195 if (PyErr_Occurred()) {
2196 PyErr_WriteUnraisable(NULL);
2197 }
2198 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002199 return;
2200 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002201 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002202 if (result == NULL) {
2203 PyErr_WriteUnraisable(threading);
2204 }
2205 else {
2206 Py_DECREF(result);
2207 }
2208 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002209}
2210
2211#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002212int Py_AtExit(void (*func)(void))
2213{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002214 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002215 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002216 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002217 return 0;
2218}
2219
2220static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002221call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002222{
Victor Stinner8e91c242019-04-24 17:24:01 +02002223 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002224 /* pop last function from the list */
2225 runtime->nexitfuncs--;
2226 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2227 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2228
2229 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002230 }
Nick Coghland6009512014-11-20 21:39:37 +10002231
2232 fflush(stdout);
2233 fflush(stderr);
2234}
2235
Victor Stinnercfc88312018-08-01 16:41:25 +02002236void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002237Py_Exit(int sts)
2238{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002239 if (Py_FinalizeEx() < 0) {
2240 sts = 120;
2241 }
Nick Coghland6009512014-11-20 21:39:37 +10002242
2243 exit(sts);
2244}
2245
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002246static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002247init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002248{
2249#ifdef SIGPIPE
2250 PyOS_setsig(SIGPIPE, SIG_IGN);
2251#endif
2252#ifdef SIGXFZ
2253 PyOS_setsig(SIGXFZ, SIG_IGN);
2254#endif
2255#ifdef SIGXFSZ
2256 PyOS_setsig(SIGXFSZ, SIG_IGN);
2257#endif
2258 PyOS_InitInterrupts(); /* May imply initsignal() */
2259 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002260 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002261 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002262 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002263}
2264
2265
2266/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2267 *
2268 * All of the code in this function must only use async-signal-safe functions,
2269 * listed at `man 7 signal` or
2270 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2271 */
2272void
2273_Py_RestoreSignals(void)
2274{
2275#ifdef SIGPIPE
2276 PyOS_setsig(SIGPIPE, SIG_DFL);
2277#endif
2278#ifdef SIGXFZ
2279 PyOS_setsig(SIGXFZ, SIG_DFL);
2280#endif
2281#ifdef SIGXFSZ
2282 PyOS_setsig(SIGXFSZ, SIG_DFL);
2283#endif
2284}
2285
2286
2287/*
2288 * The file descriptor fd is considered ``interactive'' if either
2289 * a) isatty(fd) is TRUE, or
2290 * b) the -i flag was given, and the filename associated with
2291 * the descriptor is NULL or "<stdin>" or "???".
2292 */
2293int
2294Py_FdIsInteractive(FILE *fp, const char *filename)
2295{
2296 if (isatty((int)fileno(fp)))
2297 return 1;
2298 if (!Py_InteractiveFlag)
2299 return 0;
2300 return (filename == NULL) ||
2301 (strcmp(filename, "<stdin>") == 0) ||
2302 (strcmp(filename, "???") == 0);
2303}
2304
2305
Nick Coghland6009512014-11-20 21:39:37 +10002306/* Wrappers around sigaction() or signal(). */
2307
2308PyOS_sighandler_t
2309PyOS_getsig(int sig)
2310{
2311#ifdef HAVE_SIGACTION
2312 struct sigaction context;
2313 if (sigaction(sig, NULL, &context) == -1)
2314 return SIG_ERR;
2315 return context.sa_handler;
2316#else
2317 PyOS_sighandler_t handler;
2318/* Special signal handling for the secure CRT in Visual Studio 2005 */
2319#if defined(_MSC_VER) && _MSC_VER >= 1400
2320 switch (sig) {
2321 /* Only these signals are valid */
2322 case SIGINT:
2323 case SIGILL:
2324 case SIGFPE:
2325 case SIGSEGV:
2326 case SIGTERM:
2327 case SIGBREAK:
2328 case SIGABRT:
2329 break;
2330 /* Don't call signal() with other values or it will assert */
2331 default:
2332 return SIG_ERR;
2333 }
2334#endif /* _MSC_VER && _MSC_VER >= 1400 */
2335 handler = signal(sig, SIG_IGN);
2336 if (handler != SIG_ERR)
2337 signal(sig, handler);
2338 return handler;
2339#endif
2340}
2341
2342/*
2343 * All of the code in this function must only use async-signal-safe functions,
2344 * listed at `man 7 signal` or
2345 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2346 */
2347PyOS_sighandler_t
2348PyOS_setsig(int sig, PyOS_sighandler_t handler)
2349{
2350#ifdef HAVE_SIGACTION
2351 /* Some code in Modules/signalmodule.c depends on sigaction() being
2352 * used here if HAVE_SIGACTION is defined. Fix that if this code
2353 * changes to invalidate that assumption.
2354 */
2355 struct sigaction context, ocontext;
2356 context.sa_handler = handler;
2357 sigemptyset(&context.sa_mask);
2358 context.sa_flags = 0;
2359 if (sigaction(sig, &context, &ocontext) == -1)
2360 return SIG_ERR;
2361 return ocontext.sa_handler;
2362#else
2363 PyOS_sighandler_t oldhandler;
2364 oldhandler = signal(sig, handler);
2365#ifdef HAVE_SIGINTERRUPT
2366 siginterrupt(sig, 1);
2367#endif
2368 return oldhandler;
2369#endif
2370}
2371
2372#ifdef __cplusplus
2373}
2374#endif