blob: 0781dc8046b1069e5bc8c3f41ef53f54e727e9ac [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner09532fe2019-05-10 23:39:09 +02007#include "pycore_ceval.h"
Victor Stinner99fcc612019-04-29 13:04:07 +02008#include "pycore_context.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02009#include "pycore_coreconfig.h"
Victor Stinner353933e2018-11-23 13:08:26 +010010#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010011#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010012#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010013#include "pycore_pylifecycle.h"
14#include "pycore_pymem.h"
15#include "pycore_pystate.h"
Victor Stinnered488662019-05-20 00:14:57 +020016#include "pycore_traceback.h"
Nick Coghland6009512014-11-20 21:39:37 +100017#include "grammar.h"
18#include "node.h"
19#include "token.h"
20#include "parsetok.h"
21#include "errcode.h"
22#include "code.h"
23#include "symtable.h"
24#include "ast.h"
25#include "marshal.h"
26#include "osdefs.h"
27#include <locale.h>
28
29#ifdef HAVE_SIGNAL_H
30#include <signal.h>
31#endif
32
33#ifdef MS_WINDOWS
34#include "malloc.h" /* for alloca */
35#endif
36
37#ifdef HAVE_LANGINFO_H
38#include <langinfo.h>
39#endif
40
41#ifdef MS_WINDOWS
42#undef BYTE
43#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070044
45extern PyTypeObject PyWindowsConsoleIO_Type;
46#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100047#endif
48
49_Py_IDENTIFIER(flush);
50_Py_IDENTIFIER(name);
51_Py_IDENTIFIER(stdin);
52_Py_IDENTIFIER(stdout);
53_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060054_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100055
56#ifdef __cplusplus
57extern "C" {
58#endif
59
Nick Coghland6009512014-11-20 21:39:37 +100060extern grammar _PyParser_Grammar; /* From graminit.c */
61
62/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080063static _PyInitError add_main_module(PyInterpreterState *interp);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040064static _PyInitError init_import_size(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010065static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040066static _PyInitError init_signals(void);
Marcel Plch776407f2017-12-20 11:17:58 +010067static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100068static void wait_for_thread_shutdown(void);
Victor Stinner8e91c242019-04-24 17:24:01 +020069static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100070
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080071int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080072_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010073static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060074
Victor Stinnerf7e5b562017-11-15 15:48:08 -080075_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076_PyRuntime_Initialize(void)
77{
78 /* XXX We only initialize once in the process, which aligns with
79 the static initialization of the former globals now found in
80 _PyRuntime. However, _PyRuntime *should* be initialized with
81 every Py_Initialize() call, but doing so breaks the runtime.
82 This is because the runtime state is not properly finalized
83 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010084 if (runtime_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080085 return _Py_INIT_OK();
86 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010087 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080088
89 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060090}
91
92void
93_PyRuntime_Finalize(void)
94{
95 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010096 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99int
100_Py_IsFinalizing(void)
101{
102 return _PyRuntime.finalizing != NULL;
103}
104
Nick Coghland6009512014-11-20 21:39:37 +1000105/* Hack to force loading of object files */
106int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
107 PyOS_mystrnicmp; /* Python/pystrcmp.o */
108
109/* PyModule_GetWarningsModule is no longer necessary as of 2.6
110since _warnings is builtin. This API should not be used. */
111PyObject *
112PyModule_GetWarningsModule(void)
113{
114 return PyImport_ImportModule("warnings");
115}
116
Eric Snowc7ec9982017-05-23 23:00:52 -0700117
Eric Snow1abcf672017-05-23 21:46:51 -0700118/* APIs to access the initialization flags
119 *
120 * Can be called prior to Py_Initialize.
121 */
Nick Coghland6009512014-11-20 21:39:37 +1000122
Eric Snow1abcf672017-05-23 21:46:51 -0700123int
124_Py_IsCoreInitialized(void)
125{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600126 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700127}
Nick Coghland6009512014-11-20 21:39:37 +1000128
129int
130Py_IsInitialized(void)
131{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600132 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000133}
134
Nick Coghlan6ea41862017-06-11 13:16:15 +1000135
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000136/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
137 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000138 initializations fail, a fatal error is issued and the function does
139 not return. On return, the first thread and interpreter state have
140 been created.
141
142 Locking: you must hold the interpreter lock while calling this.
143 (If the lock has not yet been initialized, that's equivalent to
144 having the lock, but you cannot use multiple threads.)
145
146*/
147
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800148static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400149init_importlib(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000150{
151 PyObject *importlib;
152 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000153 PyObject *value;
Victor Stinnerc96be812019-05-14 17:34:56 +0200154 int verbose = interp->core_config.verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000155
156 /* Import _importlib through its frozen version, _frozen_importlib. */
157 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800158 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000159 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200160 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000161 PySys_FormatStderr("import _frozen_importlib # frozen\n");
162 }
163 importlib = PyImport_AddModule("_frozen_importlib");
164 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800165 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000166 }
167 interp->importlib = importlib;
168 Py_INCREF(interp->importlib);
169
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300170 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
171 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800172 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300173 Py_INCREF(interp->import_func);
174
Victor Stinnercd6e6942015-09-18 09:11:57 +0200175 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800176 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000177 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800178 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000179 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200180 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200181 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000182 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600183 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800184 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000185 }
186
Victor Stinnercd6e6942015-09-18 09:11:57 +0200187 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000188 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
189 if (value == NULL) {
190 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800191 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000192 }
193 Py_DECREF(value);
194 Py_DECREF(impmod);
195
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800196 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000197}
198
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800199static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400200init_importlib_external(PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700201{
202 PyObject *value;
203 value = PyObject_CallMethod(interp->importlib,
204 "_install_external_importers", "");
205 if (value == NULL) {
206 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800207 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700208 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200209 Py_DECREF(value);
Victor Stinner410b85a2019-05-13 17:12:45 +0200210 return _PyImportZip_Init(interp);
Eric Snow1abcf672017-05-23 21:46:51 -0700211}
Nick Coghland6009512014-11-20 21:39:37 +1000212
Nick Coghlan6ea41862017-06-11 13:16:15 +1000213/* Helper functions to better handle the legacy C locale
214 *
215 * The legacy C locale assumes ASCII as the default text encoding, which
216 * causes problems not only for the CPython runtime, but also other
217 * components like GNU readline.
218 *
219 * Accordingly, when the CLI detects it, it attempts to coerce it to a
220 * more capable UTF-8 based alternative as follows:
221 *
222 * if (_Py_LegacyLocaleDetected()) {
223 * _Py_CoerceLegacyLocale();
224 * }
225 *
226 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
227 *
228 * Locale coercion also impacts the default error handler for the standard
229 * streams: while the usual default is "strict", the default for the legacy
230 * C locale and for any of the coercion target locales is "surrogateescape".
231 */
232
233int
234_Py_LegacyLocaleDetected(void)
235{
236#ifndef MS_WINDOWS
237 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000238 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
239 * the POSIX locale as a simple alias for the C locale, so
240 * we may also want to check for that explicitly.
241 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000242 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
243 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
244#else
245 /* Windows uses code pages instead of locales, so no locale is legacy */
246 return 0;
247#endif
248}
249
Nick Coghlaneb817952017-06-18 12:29:42 +1000250static const char *_C_LOCALE_WARNING =
251 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
252 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
253 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
254 "locales is recommended.\n";
255
Nick Coghlaneb817952017-06-18 12:29:42 +1000256static void
Victor Stinner43125222019-04-24 18:23:53 +0200257emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000258{
Victor Stinner43125222019-04-24 18:23:53 +0200259 const _PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner20004952019-03-26 02:31:11 +0100260 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200261 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000262 }
263}
264
Nick Coghlan6ea41862017-06-11 13:16:15 +1000265typedef struct _CandidateLocale {
266 const char *locale_name; /* The locale to try as a coercion target */
267} _LocaleCoercionTarget;
268
269static _LocaleCoercionTarget _TARGET_LOCALES[] = {
270 {"C.UTF-8"},
271 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000272 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000273 {NULL}
274};
275
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200276
277int
278_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000279{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200280 const _LocaleCoercionTarget *target = NULL;
281 for (target = _TARGET_LOCALES; target->locale_name; target++) {
282 if (strcmp(ctype_loc, target->locale_name) == 0) {
283 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000284 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200285 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200286 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000287}
288
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200289
Nick Coghlan6ea41862017-06-11 13:16:15 +1000290#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100291static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000292 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
293 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
294
295static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200296_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000297{
298 const char *newloc = target->locale_name;
299
300 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100301 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302
303 /* Set the relevant locale environment variable */
304 if (setenv("LC_CTYPE", newloc, 1)) {
305 fprintf(stderr,
306 "Error setting LC_CTYPE, skipping C locale coercion\n");
307 return;
308 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200309 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100310 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000311 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312
313 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100314 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315}
316#endif
317
318void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200319_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000320{
321#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200322 char *oldloc = NULL;
323
324 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
325 if (oldloc == NULL) {
326 return;
327 }
328
Victor Stinner94540602017-12-16 04:54:22 +0100329 const char *locale_override = getenv("LC_ALL");
330 if (locale_override == NULL || *locale_override == '\0') {
331 /* LC_ALL is also not set (or is set to an empty string) */
332 const _LocaleCoercionTarget *target = NULL;
333 for (target = _TARGET_LOCALES; target->locale_name; target++) {
334 const char *new_locale = setlocale(LC_CTYPE,
335 target->locale_name);
336 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400337#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100338 /* Also ensure that nl_langinfo works in this locale */
339 char *codeset = nl_langinfo(CODESET);
340 if (!codeset || *codeset == '\0') {
341 /* CODESET is not set or empty, so skip coercion */
342 new_locale = NULL;
343 _Py_SetLocaleFromEnv(LC_CTYPE);
344 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000345 }
Victor Stinner94540602017-12-16 04:54:22 +0100346#endif
347 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200348 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200349 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350 }
351 }
352 }
353 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200354
355 setlocale(LC_CTYPE, oldloc);
356
357done:
358 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000359#endif
360}
361
xdegaye1588be62017-11-12 12:45:59 +0100362/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
363 * isolate the idiosyncrasies of different libc implementations. It reads the
364 * appropriate environment variable and uses its value to select the locale for
365 * 'category'. */
366char *
367_Py_SetLocaleFromEnv(int category)
368{
Victor Stinner353933e2018-11-23 13:08:26 +0100369 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100370#ifdef __ANDROID__
371 const char *locale;
372 const char **pvar;
373#ifdef PY_COERCE_C_LOCALE
374 const char *coerce_c_locale;
375#endif
376 const char *utf8_locale = "C.UTF-8";
377 const char *env_var_set[] = {
378 "LC_ALL",
379 "LC_CTYPE",
380 "LANG",
381 NULL,
382 };
383
384 /* Android setlocale(category, "") doesn't check the environment variables
385 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
386 * check the environment variables listed in env_var_set. */
387 for (pvar=env_var_set; *pvar; pvar++) {
388 locale = getenv(*pvar);
389 if (locale != NULL && *locale != '\0') {
390 if (strcmp(locale, utf8_locale) == 0 ||
391 strcmp(locale, "en_US.UTF-8") == 0) {
392 return setlocale(category, utf8_locale);
393 }
394 return setlocale(category, "C");
395 }
396 }
397
398 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
399 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
400 * Quote from POSIX section "8.2 Internationalization Variables":
401 * "4. If the LANG environment variable is not set or is set to the empty
402 * string, the implementation-defined default locale shall be used." */
403
404#ifdef PY_COERCE_C_LOCALE
405 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
406 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
407 /* Some other ported code may check the environment variables (e.g. in
408 * extension modules), so we make sure that they match the locale
409 * configuration */
410 if (setenv("LC_CTYPE", utf8_locale, 1)) {
411 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
412 "environment variable to %s\n", utf8_locale);
413 }
414 }
415#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100416 res = setlocale(category, utf8_locale);
417#else /* !defined(__ANDROID__) */
418 res = setlocale(category, "");
419#endif
420 _Py_ResetForceASCII();
421 return res;
xdegaye1588be62017-11-12 12:45:59 +0100422}
423
Nick Coghlan6ea41862017-06-11 13:16:15 +1000424
Eric Snow1abcf672017-05-23 21:46:51 -0700425/* Global initializations. Can be undone by Py_Finalize(). Don't
426 call this twice without an intervening Py_Finalize() call.
427
Victor Stinner484f20d2019-03-27 02:04:16 +0100428 Every call to _Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700429 must have a corresponding call to Py_Finalize.
430
431 Locking: you must hold the interpreter lock while calling these APIs.
432 (If the lock has not yet been initialized, that's equivalent to
433 having the lock, but you cannot use multiple threads.)
434
435*/
436
Victor Stinner1dc6e392018-07-25 02:49:17 +0200437static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200438_Py_Initialize_ReconfigureCore(_PyRuntimeState *runtime,
439 PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200440 const _PyCoreConfig *core_config)
441{
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200442 _PyInitError err;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100443 PyThreadState *tstate = _PyThreadState_GET();
444 if (!tstate) {
445 return _Py_INIT_ERR("failed to read thread state");
446 }
447
448 PyInterpreterState *interp = tstate->interp;
449 if (interp == NULL) {
450 return _Py_INIT_ERR("can't make main interpreter");
451 }
452 *interp_p = interp;
453
Victor Stinner43125222019-04-24 18:23:53 +0200454 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200455
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200456 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
457 if (_Py_INIT_FAILED(err)) {
458 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200459 }
460 core_config = &interp->core_config;
461
462 if (core_config->_install_importlib) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200463 err = _PyCoreConfig_SetPathConfig(core_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200464 if (_Py_INIT_FAILED(err)) {
465 return err;
466 }
467 }
468 return _Py_INIT_OK();
469}
470
471
Victor Stinner1dc6e392018-07-25 02:49:17 +0200472static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200473pycore_init_runtime(_PyRuntimeState *runtime,
474 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000475{
Victor Stinner43125222019-04-24 18:23:53 +0200476 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200477 return _Py_INIT_ERR("main interpreter already initialized");
478 }
Victor Stinnerda273412017-12-15 01:46:02 +0100479
Victor Stinner43125222019-04-24 18:23:53 +0200480 _PyCoreConfig_Write(core_config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600481
Eric Snow1abcf672017-05-23 21:46:51 -0700482 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
483 * threads behave a little more gracefully at interpreter shutdown.
484 * We clobber it here so the new interpreter can start with a clean
485 * slate.
486 *
487 * However, this may still lead to misbehaviour if there are daemon
488 * threads still hanging around from a previous Py_Initialize/Finalize
489 * pair :(
490 */
Victor Stinner43125222019-04-24 18:23:53 +0200491 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600492
Victor Stinner43125222019-04-24 18:23:53 +0200493 _PyInitError err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800494 if (_Py_INIT_FAILED(err)) {
495 return err;
496 }
497
Victor Stinner43125222019-04-24 18:23:53 +0200498 err = _PyInterpreterState_Enable(runtime);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800499 if (_Py_INIT_FAILED(err)) {
500 return err;
501 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100502 return _Py_INIT_OK();
503}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800504
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100505
506static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200507pycore_create_interpreter(_PyRuntimeState *runtime,
508 const _PyCoreConfig *core_config,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100509 PyInterpreterState **interp_p)
510{
511 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100512 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800513 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100514 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200515 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100516
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200517 _PyInitError err = _PyCoreConfig_Copy(&interp->core_config, core_config);
518 if (_Py_INIT_FAILED(err)) {
519 return err;
Victor Stinnerda273412017-12-15 01:46:02 +0100520 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200521 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000522
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200523 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000524 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800525 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000526 (void) PyThreadState_Swap(tstate);
527
Victor Stinner99fcc612019-04-29 13:04:07 +0200528 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
529 destroying the GIL might fail when it is being referenced from
530 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000531 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000532 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner09532fe2019-05-10 23:39:09 +0200533 _PyEval_FiniThreads(&runtime->ceval);
Victor Stinner2914bb32018-01-29 11:57:45 +0100534
Nick Coghland6009512014-11-20 21:39:37 +1000535 /* Auto-thread-state API */
Victor Stinner43125222019-04-24 18:23:53 +0200536 _PyGILState_Init(runtime, interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000537
Victor Stinner2914bb32018-01-29 11:57:45 +0100538 /* Create the GIL */
539 PyEval_InitThreads();
540
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100541 return _Py_INIT_OK();
542}
Nick Coghland6009512014-11-20 21:39:37 +1000543
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100544
545static _PyInitError
546pycore_init_types(void)
547{
Victor Stinnerab672812019-01-23 15:04:40 +0100548 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100549 if (_Py_INIT_FAILED(err)) {
550 return err;
551 }
552
553 err = _PyUnicode_Init();
554 if (_Py_INIT_FAILED(err)) {
555 return err;
556 }
557
558 if (_PyStructSequence_Init() < 0) {
559 return _Py_INIT_ERR("can't initialize structseq");
560 }
561
562 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800563 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100564 }
Nick Coghland6009512014-11-20 21:39:37 +1000565
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100566 err = _PyExc_Init();
567 if (_Py_INIT_FAILED(err)) {
568 return err;
569 }
570
571 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800572 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573 }
Nick Coghland6009512014-11-20 21:39:37 +1000574
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100575 if (!_PyContext_Init()) {
576 return _Py_INIT_ERR("can't init context");
577 }
578 return _Py_INIT_OK();
579}
580
581
582static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100583pycore_init_builtins(PyInterpreterState *interp)
584{
585 PyObject *bimod = _PyBuiltin_Init();
586 if (bimod == NULL) {
587 return _Py_INIT_ERR("can't initialize builtins modules");
588 }
589 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
590
591 interp->builtins = PyModule_GetDict(bimod);
592 if (interp->builtins == NULL) {
593 return _Py_INIT_ERR("can't initialize builtins dict");
594 }
595 Py_INCREF(interp->builtins);
596
597 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
598 if (_Py_INIT_FAILED(err)) {
599 return err;
600 }
601 return _Py_INIT_OK();
602}
603
604
605static _PyInitError
606pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
607{
608 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800609 if (_Py_INIT_FAILED(err)) {
610 return err;
611 }
Nick Coghland6009512014-11-20 21:39:37 +1000612
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800613 err = _PyImportHooks_Init();
614 if (_Py_INIT_FAILED(err)) {
615 return err;
616 }
Nick Coghland6009512014-11-20 21:39:37 +1000617
618 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100619 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100620 return _Py_INIT_ERR("can't initialize warnings");
621 }
Nick Coghland6009512014-11-20 21:39:37 +1000622
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100623 if (interp->core_config._install_importlib) {
624 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200625 if (_Py_INIT_FAILED(err)) {
626 return err;
627 }
628 }
629
Eric Snow1abcf672017-05-23 21:46:51 -0700630 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100631 if (interp->core_config._install_importlib) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400632 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800633 if (_Py_INIT_FAILED(err)) {
634 return err;
635 }
Eric Snow1abcf672017-05-23 21:46:51 -0700636 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100637 return _Py_INIT_OK();
638}
639
640
641static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200642_Py_InitializeCore_impl(_PyRuntimeState *runtime,
643 PyInterpreterState **interp_p,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100644 const _PyCoreConfig *core_config)
645{
646 PyInterpreterState *interp;
647
Victor Stinner43125222019-04-24 18:23:53 +0200648 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100649
Victor Stinner43125222019-04-24 18:23:53 +0200650 _PyInitError err = pycore_init_runtime(runtime, core_config);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100651 if (_Py_INIT_FAILED(err)) {
652 return err;
653 }
654
Victor Stinner43125222019-04-24 18:23:53 +0200655 err = pycore_create_interpreter(runtime, core_config, &interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100656 if (_Py_INIT_FAILED(err)) {
657 return err;
658 }
659 core_config = &interp->core_config;
660 *interp_p = interp;
661
662 err = pycore_init_types();
663 if (_Py_INIT_FAILED(err)) {
664 return err;
665 }
666
667 PyObject *sysmod;
Victor Stinner43125222019-04-24 18:23:53 +0200668 err = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100669 if (_Py_INIT_FAILED(err)) {
670 return err;
671 }
672
673 err = pycore_init_builtins(interp);
674 if (_Py_INIT_FAILED(err)) {
675 return err;
676 }
677
678 err = pycore_init_import_warnings(interp, sysmod);
679 if (_Py_INIT_FAILED(err)) {
680 return err;
681 }
Eric Snow1abcf672017-05-23 21:46:51 -0700682
683 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200684 runtime->core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800685 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700686}
687
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100688
Victor Stinner70005ac2019-05-02 15:25:34 -0400689_PyInitError
690_Py_PreInitializeFromPyArgv(const _PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100691{
692 _PyInitError err;
693
694 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100695 if (_Py_INIT_FAILED(err)) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100696 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100697 }
Victor Stinner43125222019-04-24 18:23:53 +0200698 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100699
Victor Stinner43125222019-04-24 18:23:53 +0200700 if (runtime->pre_initialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100701 /* If it's already configured: ignored the new configuration */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100702 return _Py_INIT_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100703 }
704
Victor Stinnercab5d072019-05-17 19:01:14 +0200705 _PyPreConfig config;
706 _PyPreConfig_Init(&config);
Victor Stinner5ac27a52019-03-27 13:40:14 +0100707
Victor Stinnerf72346c2019-03-25 17:54:58 +0100708 if (src_config) {
Victor Stinnerb5947842019-05-18 00:38:16 +0200709 _PyPreConfig_Copy(&config, src_config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100710 }
711
Victor Stinner5ac27a52019-03-27 13:40:14 +0100712 err = _PyPreConfig_Read(&config, args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100713 if (_Py_INIT_FAILED(err)) {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200714 return err;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100715 }
716
Victor Stinner5ac27a52019-03-27 13:40:14 +0100717 err = _PyPreConfig_Write(&config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100718 if (_Py_INIT_FAILED(err)) {
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200719 return err;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100720 }
721
Victor Stinner43125222019-04-24 18:23:53 +0200722 runtime->pre_initialized = 1;
Victor Stinnerb16b4e42019-05-17 15:20:52 +0200723 return _Py_INIT_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100724}
725
Victor Stinner70005ac2019-05-02 15:25:34 -0400726
Victor Stinnerf72346c2019-03-25 17:54:58 +0100727_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +0200728_Py_PreInitializeFromArgs(const _PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100729{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100730 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400731 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100732}
733
734
735_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +0200736_Py_PreInitializeFromWideArgs(const _PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100737{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100738 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400739 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100740}
741
742
743_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100744_Py_PreInitialize(const _PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100745{
Victor Stinner70005ac2019-05-02 15:25:34 -0400746 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100747}
748
749
750_PyInitError
Victor Stinner70005ac2019-05-02 15:25:34 -0400751_Py_PreInitializeFromCoreConfig(const _PyCoreConfig *coreconfig,
752 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100753{
Victor Stinnercab5d072019-05-17 19:01:14 +0200754 _PyPreConfig config;
755 _PyPreConfig_Init(&config);
Victor Stinner70005ac2019-05-02 15:25:34 -0400756 if (coreconfig != NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200757 _PyPreConfig_GetCoreConfig(&config, coreconfig);
Victor Stinner70005ac2019-05-02 15:25:34 -0400758 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200759
760 if (args == NULL && coreconfig != NULL && coreconfig->parse_argv) {
761 _PyArgv config_args = {
762 .use_bytes_argv = 0,
763 .argc = coreconfig->argv.length,
764 .wchar_argv = coreconfig->argv.items};
765 return _Py_PreInitializeFromPyArgv(&config, &config_args);
766 }
767 else {
768 return _Py_PreInitializeFromPyArgv(&config, args);
769 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100770}
771
772
773static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200774pyinit_coreconfig(_PyRuntimeState *runtime,
775 _PyCoreConfig *config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100776 const _PyCoreConfig *src_config,
777 const _PyArgv *args,
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100778 PyInterpreterState **interp_p)
779{
Victor Stinner5f38b842019-05-01 02:30:12 +0200780 _PyInitError err;
781
Victor Stinnerd929f182019-03-27 18:28:46 +0100782 if (src_config) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200783 err = _PyCoreConfig_Copy(config, src_config);
784 if (_Py_INIT_FAILED(err)) {
785 return err;
Victor Stinnerd929f182019-03-27 18:28:46 +0100786 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100787 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100788
Victor Stinner5f38b842019-05-01 02:30:12 +0200789 if (args) {
790 err = _PyCoreConfig_SetPyArgv(config, args);
791 if (_Py_INIT_FAILED(err)) {
792 return err;
793 }
794 }
795
796 err = _PyCoreConfig_Read(config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100797 if (_Py_INIT_FAILED(err)) {
798 return err;
799 }
800
Victor Stinner43125222019-04-24 18:23:53 +0200801 if (!runtime->core_initialized) {
802 return _Py_InitializeCore_impl(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100803 }
804 else {
Victor Stinner43125222019-04-24 18:23:53 +0200805 return _Py_Initialize_ReconfigureCore(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100806 }
807}
808
809
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100810/* Begin interpreter initialization
811 *
812 * On return, the first thread and interpreter state have been created,
813 * but the compiler, signal handling, multithreading and
814 * multiple interpreter support, and codec infrastructure are not yet
815 * available.
816 *
817 * The import system will support builtin and frozen modules only.
818 * The only supported io is writing to sys.stderr
819 *
820 * If any operation invoked by this function fails, a fatal error is
821 * issued and the function does not return.
822 *
823 * Any code invoked from this function should *not* assume it has access
824 * to the Python C API (unless the API is explicitly listed as being
825 * safe to call without calling Py_Initialize first)
826 */
Victor Stinner484f20d2019-03-27 02:04:16 +0100827static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200828_Py_InitializeCore(_PyRuntimeState *runtime,
829 const _PyCoreConfig *src_config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100830 const _PyArgv *args,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100831 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200832{
Victor Stinnerd929f182019-03-27 18:28:46 +0100833 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200834
Victor Stinner70005ac2019-05-02 15:25:34 -0400835 err = _Py_PreInitializeFromCoreConfig(src_config, args);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200836 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100837 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200838 }
839
Victor Stinnercab5d072019-05-17 19:01:14 +0200840 _PyCoreConfig local_config;
841 _PyCoreConfig_Init(&local_config);
Victor Stinner43125222019-04-24 18:23:53 +0200842 err = pyinit_coreconfig(runtime, &local_config, src_config, args, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100843 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200844 return err;
845}
846
Victor Stinner5ac27a52019-03-27 13:40:14 +0100847
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200848/* Py_Initialize() has already been called: update the main interpreter
849 configuration. Example of bpo-34008: Py_Main() called after
850 Py_Initialize(). */
851static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100852_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200853{
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100854 _PyCoreConfig *core_config = &interp->core_config;
855
856 PyObject *argv = _PyWstrList_AsList(&core_config->argv);
857 if (argv == NULL) {
858 return _Py_INIT_NO_MEMORY(); \
859 }
860
861 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
862 Py_DECREF(argv);
863 if (res < 0) {
864 return _Py_INIT_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200865 }
866 return _Py_INIT_OK();
867}
868
Eric Snowc7ec9982017-05-23 23:00:52 -0700869/* Update interpreter state based on supplied configuration settings
870 *
871 * After calling this function, most of the restrictions on the interpreter
872 * are lifted. The only remaining incomplete settings are those related
873 * to the main module (sys.argv[0], __main__ metadata)
874 *
875 * Calling this when the interpreter is not initializing, is already
876 * initialized or without a valid current thread state is a fatal error.
877 * Other errors should be reported as normal Python exceptions with a
878 * non-zero return code.
879 */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100880static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200881_Py_InitializeMainInterpreter(_PyRuntimeState *runtime,
882 PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700883{
Victor Stinner43125222019-04-24 18:23:53 +0200884 if (!runtime->core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800885 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700886 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700887
Victor Stinner1dc6e392018-07-25 02:49:17 +0200888 /* Configure the main interpreter */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200889 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700890
Victor Stinner43125222019-04-24 18:23:53 +0200891 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100892 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200893 }
894
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200895 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700896 /* Special mode for freeze_importlib: run with no import system
897 *
898 * This means anything which needs support from extension modules
899 * or pure Python code in the standard library won't work.
900 */
Victor Stinner43125222019-04-24 18:23:53 +0200901 runtime->initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800902 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700903 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100904
Victor Stinner33c377e2017-12-05 15:12:41 +0100905 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800906 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100907 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200908
Victor Stinner43125222019-04-24 18:23:53 +0200909 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800910 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100911 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800912
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400913 _PyInitError err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800914 if (_Py_INIT_FAILED(err)) {
915 return err;
916 }
Nick Coghland6009512014-11-20 21:39:37 +1000917
918 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200919 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800920 if (_Py_INIT_FAILED(err)) {
921 return err;
922 }
Nick Coghland6009512014-11-20 21:39:37 +1000923
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400924 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800925 if (_Py_INIT_FAILED(err)) {
926 return err;
927 }
Nick Coghland6009512014-11-20 21:39:37 +1000928
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100929 if (core_config->install_signal_handlers) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400930 err = init_signals();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 if (_Py_INIT_FAILED(err)) {
932 return err;
933 }
934 }
Nick Coghland6009512014-11-20 21:39:37 +1000935
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200936 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800937 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200938 }
Nick Coghland6009512014-11-20 21:39:37 +1000939
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800940 err = add_main_module(interp);
941 if (_Py_INIT_FAILED(err)) {
942 return err;
943 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800944
Victor Stinner91106cd2017-12-13 12:29:09 +0100945 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800946 if (_Py_INIT_FAILED(err)) {
947 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800948 }
Nick Coghland6009512014-11-20 21:39:37 +1000949
950 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100951 PyObject *warnoptions = PySys_GetObject("warnoptions");
952 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100953 {
Nick Coghland6009512014-11-20 21:39:37 +1000954 PyObject *warnings_module = PyImport_ImportModule("warnings");
955 if (warnings_module == NULL) {
956 fprintf(stderr, "'import warnings' failed; traceback:\n");
957 PyErr_Print();
958 }
959 Py_XDECREF(warnings_module);
960 }
961
Victor Stinner43125222019-04-24 18:23:53 +0200962 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700963
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200964 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400965 err = init_import_size(); /* Module site */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800966 if (_Py_INIT_FAILED(err)) {
967 return err;
968 }
969 }
Victor Stinnercf215042018-08-29 22:56:06 +0200970
971#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200972 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200973#endif
974
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800975 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000976}
977
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200978
979_PyInitError
980_Py_InitializeMain(void)
981{
982 _PyInitError err = _PyRuntime_Initialize();
983 if (_Py_INIT_FAILED(err)) {
984 return err;
985 }
986 _PyRuntimeState *runtime = &_PyRuntime;
987 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
988
989 return _Py_InitializeMainInterpreter(runtime, interp);
990}
991
992
Eric Snowc7ec9982017-05-23 23:00:52 -0700993#undef _INIT_DEBUG_PRINT
994
Victor Stinner5ac27a52019-03-27 13:40:14 +0100995static _PyInitError
996init_python(const _PyCoreConfig *config, const _PyArgv *args)
Eric Snow1abcf672017-05-23 21:46:51 -0700997{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800998 _PyInitError err;
Victor Stinner43125222019-04-24 18:23:53 +0200999
1000 err = _PyRuntime_Initialize();
1001 if (_Py_INIT_FAILED(err)) {
1002 return err;
1003 }
1004 _PyRuntimeState *runtime = &_PyRuntime;
1005
1006 PyInterpreterState *interp = NULL;
1007 err = _Py_InitializeCore(runtime, config, args, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001008 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001009 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001010 }
Victor Stinner1dc6e392018-07-25 02:49:17 +02001011 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001012
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001013 if (config->_init_main) {
Victor Stinner43125222019-04-24 18:23:53 +02001014 err = _Py_InitializeMainInterpreter(runtime, interp);
Victor Stinner484f20d2019-03-27 02:04:16 +01001015 if (_Py_INIT_FAILED(err)) {
1016 return err;
1017 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001018 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001019
Victor Stinner1dc6e392018-07-25 02:49:17 +02001020 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001021}
1022
1023
Victor Stinner5ac27a52019-03-27 13:40:14 +01001024_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +02001025_Py_InitializeFromArgs(const _PyCoreConfig *config, Py_ssize_t argc, char **argv)
Victor Stinner5ac27a52019-03-27 13:40:14 +01001026{
1027 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1028 return init_python(config, &args);
1029}
1030
1031
1032_PyInitError
Victor Stinnerb5947842019-05-18 00:38:16 +02001033_Py_InitializeFromWideArgs(const _PyCoreConfig *config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner5ac27a52019-03-27 13:40:14 +01001034{
1035 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1036 return init_python(config, &args);
1037}
1038
1039
1040_PyInitError
1041_Py_InitializeFromConfig(const _PyCoreConfig *config)
1042{
1043 return init_python(config, NULL);
1044}
1045
1046
Eric Snow1abcf672017-05-23 21:46:51 -07001047void
Nick Coghland6009512014-11-20 21:39:37 +10001048Py_InitializeEx(int install_sigs)
1049{
Victor Stinner43125222019-04-24 18:23:53 +02001050 _PyInitError err;
1051
1052 err = _PyRuntime_Initialize();
1053 if (_Py_INIT_FAILED(err)) {
1054 _Py_ExitInitError(err);
1055 }
1056 _PyRuntimeState *runtime = &_PyRuntime;
1057
1058 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001059 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1060 return;
1061 }
1062
Victor Stinnercab5d072019-05-17 19:01:14 +02001063 _PyCoreConfig config;
1064 _PyCoreConfig_Init(&config);
Victor Stinner1dc6e392018-07-25 02:49:17 +02001065 config.install_signal_handlers = install_sigs;
1066
Victor Stinner43125222019-04-24 18:23:53 +02001067 err = _Py_InitializeFromConfig(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001068 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001069 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001070 }
Nick Coghland6009512014-11-20 21:39:37 +10001071}
1072
1073void
1074Py_Initialize(void)
1075{
1076 Py_InitializeEx(1);
1077}
1078
1079
1080#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001081extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001082#endif
1083
1084/* Flush stdout and stderr */
1085
1086static int
1087file_is_closed(PyObject *fobj)
1088{
1089 int r;
1090 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1091 if (tmp == NULL) {
1092 PyErr_Clear();
1093 return 0;
1094 }
1095 r = PyObject_IsTrue(tmp);
1096 Py_DECREF(tmp);
1097 if (r < 0)
1098 PyErr_Clear();
1099 return r > 0;
1100}
1101
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001102static int
Nick Coghland6009512014-11-20 21:39:37 +10001103flush_std_files(void)
1104{
1105 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1106 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1107 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001108 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001109
1110 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001111 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001112 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001113 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001114 status = -1;
1115 }
Nick Coghland6009512014-11-20 21:39:37 +10001116 else
1117 Py_DECREF(tmp);
1118 }
1119
1120 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001121 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001122 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001123 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001124 status = -1;
1125 }
Nick Coghland6009512014-11-20 21:39:37 +10001126 else
1127 Py_DECREF(tmp);
1128 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001129
1130 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001131}
1132
1133/* Undo the effect of Py_Initialize().
1134
1135 Beware: if multiple interpreter and/or thread states exist, these
1136 are not wiped out; only the current thread and interpreter state
1137 are deleted. But since everything else is deleted, those other
1138 interpreter and thread states should no longer be used.
1139
1140 (XXX We should do better, e.g. wipe out all interpreters and
1141 threads.)
1142
1143 Locking: as above.
1144
1145*/
1146
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001147int
1148Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001149{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001150 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001151
Victor Stinner8e91c242019-04-24 17:24:01 +02001152 _PyRuntimeState *runtime = &_PyRuntime;
1153 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001154 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001155 }
Nick Coghland6009512014-11-20 21:39:37 +10001156
Eric Snow842a2f02019-03-15 15:47:51 -06001157 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001158 wait_for_thread_shutdown();
1159
Eric Snow842a2f02019-03-15 15:47:51 -06001160 // Make any remaining pending calls.
Victor Stinner09532fe2019-05-10 23:39:09 +02001161 _Py_FinishPendingCalls(runtime);
Eric Snow842a2f02019-03-15 15:47:51 -06001162
Victor Stinner8e91c242019-04-24 17:24:01 +02001163 /* Get current thread state and interpreter pointer */
Victor Stinner09532fe2019-05-10 23:39:09 +02001164 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001165 PyInterpreterState *interp = tstate->interp;
1166
Nick Coghland6009512014-11-20 21:39:37 +10001167 /* The interpreter is still entirely intact at this point, and the
1168 * exit funcs may be relying on that. In particular, if some thread
1169 * or exit func is still waiting to do an import, the import machinery
1170 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001171 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001172 * Note that Threading.py uses an exit func to do a join on all the
1173 * threads created thru it, so this also protects pending imports in
1174 * the threads created via Threading.
1175 */
Nick Coghland6009512014-11-20 21:39:37 +10001176
Marcel Plch776407f2017-12-20 11:17:58 +01001177 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001178
Victor Stinnerda273412017-12-15 01:46:02 +01001179 /* Copy the core config, PyInterpreterState_Delete() free
1180 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001181#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001182 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001183#endif
1184#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001185 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001186#endif
1187#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001188 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001189#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001190
Nick Coghland6009512014-11-20 21:39:37 +10001191 /* Remaining threads (e.g. daemon threads) will automatically exit
1192 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001193 runtime->finalizing = tstate;
1194 runtime->initialized = 0;
1195 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001196
Victor Stinnere0deff32015-03-24 13:46:18 +01001197 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001198 if (flush_std_files() < 0) {
1199 status = -1;
1200 }
Nick Coghland6009512014-11-20 21:39:37 +10001201
1202 /* Disable signal handling */
1203 PyOS_FiniInterrupts();
1204
1205 /* Collect garbage. This may call finalizers; it's nice to call these
1206 * before all modules are destroyed.
1207 * XXX If a __del__ or weakref callback is triggered here, and tries to
1208 * XXX import a module, bad things can happen, because Python no
1209 * XXX longer believes it's initialized.
1210 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1211 * XXX is easy to provoke that way. I've also seen, e.g.,
1212 * XXX Exception exceptions.ImportError: 'No module named sha'
1213 * XXX in <function callback at 0x008F5718> ignored
1214 * XXX but I'm unclear on exactly how that one happens. In any case,
1215 * XXX I haven't seen a real-life report of either of these.
1216 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001217 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001218#ifdef COUNT_ALLOCS
1219 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1220 each collection might release some types from the type
1221 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001222 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001223 /* nothing */;
1224#endif
Eric Snowdae02762017-09-14 00:35:58 -07001225
Nick Coghland6009512014-11-20 21:39:37 +10001226 /* Destroy all modules */
1227 PyImport_Cleanup();
1228
Victor Stinnere0deff32015-03-24 13:46:18 +01001229 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001230 if (flush_std_files() < 0) {
1231 status = -1;
1232 }
Nick Coghland6009512014-11-20 21:39:37 +10001233
1234 /* Collect final garbage. This disposes of cycles created by
1235 * class definitions, for example.
1236 * XXX This is disabled because it caused too many problems. If
1237 * XXX a __del__ or weakref callback triggers here, Python code has
1238 * XXX a hard time running, because even the sys module has been
1239 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1240 * XXX One symptom is a sequence of information-free messages
1241 * XXX coming from threads (if a __del__ or callback is invoked,
1242 * XXX other threads can execute too, and any exception they encounter
1243 * XXX triggers a comedy of errors as subsystem after subsystem
1244 * XXX fails to find what it *expects* to find in sys to help report
1245 * XXX the exception and consequent unexpected failures). I've also
1246 * XXX seen segfaults then, after adding print statements to the
1247 * XXX Python code getting called.
1248 */
1249#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001250 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001251#endif
1252
1253 /* Disable tracemalloc after all Python objects have been destroyed,
1254 so it is possible to use tracemalloc in objects destructor. */
1255 _PyTraceMalloc_Fini();
1256
1257 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1258 _PyImport_Fini();
1259
1260 /* Cleanup typeobject.c's internal caches. */
1261 _PyType_Fini();
1262
1263 /* unload faulthandler module */
1264 _PyFaulthandler_Fini();
1265
1266 /* Debugging stuff */
1267#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001268 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001269#endif
1270 /* dump hash stats */
1271 _PyHash_Fini();
1272
Eric Snowdae02762017-09-14 00:35:58 -07001273#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001274 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001275 _PyDebug_PrintTotalRefs();
1276 }
Eric Snowdae02762017-09-14 00:35:58 -07001277#endif
Nick Coghland6009512014-11-20 21:39:37 +10001278
1279#ifdef Py_TRACE_REFS
1280 /* Display all objects still alive -- this can invoke arbitrary
1281 * __repr__ overrides, so requires a mostly-intact interpreter.
1282 * Alas, a lot of stuff may still be alive now that will be cleaned
1283 * up later.
1284 */
Victor Stinnerda273412017-12-15 01:46:02 +01001285 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001286 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001287 }
Nick Coghland6009512014-11-20 21:39:37 +10001288#endif /* Py_TRACE_REFS */
1289
1290 /* Clear interpreter state and all thread states. */
1291 PyInterpreterState_Clear(interp);
1292
1293 /* Now we decref the exception classes. After this point nothing
1294 can raise an exception. That's okay, because each Fini() method
1295 below has been checked to make sure no exceptions are ever
1296 raised.
1297 */
1298
1299 _PyExc_Fini();
1300
1301 /* Sundry finalizers */
1302 PyMethod_Fini();
1303 PyFrame_Fini();
1304 PyCFunction_Fini();
1305 PyTuple_Fini();
1306 PyList_Fini();
1307 PySet_Fini();
1308 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001309 PyLong_Fini();
1310 PyFloat_Fini();
1311 PyDict_Fini();
1312 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001313 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001314 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001315 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001316 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001317 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001318 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001319
1320 /* Cleanup Unicode implementation */
1321 _PyUnicode_Fini();
1322
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001323 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001324
1325 /* XXX Still allocated:
1326 - various static ad-hoc pointers to interned strings
1327 - int and float free list blocks
1328 - whatever various modules and libraries allocate
1329 */
1330
1331 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1332
1333 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001334 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001335
1336 /* Delete current thread. After this, many C API calls become crashy. */
1337 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001338
Nick Coghland6009512014-11-20 21:39:37 +10001339 PyInterpreterState_Delete(interp);
1340
1341#ifdef Py_TRACE_REFS
1342 /* Display addresses (& refcnts) of all objects still alive.
1343 * An address can be used to find the repr of the object, printed
1344 * above by _Py_PrintReferences.
1345 */
Victor Stinnerda273412017-12-15 01:46:02 +01001346 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001347 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001348 }
Nick Coghland6009512014-11-20 21:39:37 +10001349#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001350#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001351 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001352 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001353 }
Nick Coghland6009512014-11-20 21:39:37 +10001354#endif
1355
Victor Stinner8e91c242019-04-24 17:24:01 +02001356 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001357
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001358 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001359 return status;
1360}
1361
1362void
1363Py_Finalize(void)
1364{
1365 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001366}
1367
1368/* Create and initialize a new interpreter and thread, and return the
1369 new thread. This requires that Py_Initialize() has been called
1370 first.
1371
1372 Unsuccessful initialization yields a NULL pointer. Note that *no*
1373 exception information is available even in this case -- the
1374 exception information is held in the thread, and there is no
1375 thread.
1376
1377 Locking: as above.
1378
1379*/
1380
Victor Stinnera7368ac2017-11-15 18:11:45 -08001381static _PyInitError
1382new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001383{
Victor Stinner9316ee42017-11-25 03:17:57 +01001384 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001385
Victor Stinner43125222019-04-24 18:23:53 +02001386 err = _PyRuntime_Initialize();
1387 if (_Py_INIT_FAILED(err)) {
1388 return err;
1389 }
1390 _PyRuntimeState *runtime = &_PyRuntime;
1391
1392 if (!runtime->initialized) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001393 return _Py_INIT_ERR("Py_Initialize must be called first");
1394 }
Nick Coghland6009512014-11-20 21:39:37 +10001395
Victor Stinner8a1be612016-03-14 22:07:55 +01001396 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1397 interpreters: disable PyGILState_Check(). */
1398 _PyGILState_check_enabled = 0;
1399
Victor Stinner43125222019-04-24 18:23:53 +02001400 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001401 if (interp == NULL) {
1402 *tstate_p = NULL;
1403 return _Py_INIT_OK();
1404 }
Nick Coghland6009512014-11-20 21:39:37 +10001405
Victor Stinner43125222019-04-24 18:23:53 +02001406 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001407 if (tstate == NULL) {
1408 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001409 *tstate_p = NULL;
1410 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001411 }
1412
Victor Stinner43125222019-04-24 18:23:53 +02001413 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001414
Eric Snow1abcf672017-05-23 21:46:51 -07001415 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001416 _PyCoreConfig *core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001417 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001418 core_config = &save_tstate->interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001419 } else {
1420 /* No current thread state, copy from the main interpreter */
1421 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001422 core_config = &main_interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001423 }
1424
Victor Stinner1a9f0d82019-05-01 15:22:52 +02001425 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
1426 if (_Py_INIT_FAILED(err)) {
1427 return err;
Victor Stinnerda273412017-12-15 01:46:02 +01001428 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001429 core_config = &interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001430
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001431 err = _PyExc_Init();
1432 if (_Py_INIT_FAILED(err)) {
1433 return err;
1434 }
1435
Nick Coghland6009512014-11-20 21:39:37 +10001436 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001437 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001438 if (modules == NULL) {
1439 return _Py_INIT_ERR("can't make modules dictionary");
1440 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001441 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001442
Victor Stinner43125222019-04-24 18:23:53 +02001443 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001444 if (sysmod != NULL) {
1445 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001446 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001447 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001448 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001449 Py_INCREF(interp->sysdict);
1450 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner43125222019-04-24 18:23:53 +02001451 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerab672812019-01-23 15:04:40 +01001452 return _Py_INIT_ERR("can't finish initializing sys");
1453 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001454 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001455 else if (PyErr_Occurred()) {
1456 goto handle_error;
1457 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001458
Victor Stinner43125222019-04-24 18:23:53 +02001459 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001460 if (bimod != NULL) {
1461 interp->builtins = PyModule_GetDict(bimod);
1462 if (interp->builtins == NULL)
1463 goto handle_error;
1464 Py_INCREF(interp->builtins);
1465 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001466 else if (PyErr_Occurred()) {
1467 goto handle_error;
1468 }
Nick Coghland6009512014-11-20 21:39:37 +10001469
Nick Coghland6009512014-11-20 21:39:37 +10001470 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001471 err = _PyBuiltins_AddExceptions(bimod);
1472 if (_Py_INIT_FAILED(err)) {
1473 return err;
1474 }
Nick Coghland6009512014-11-20 21:39:37 +10001475
Victor Stinnerab672812019-01-23 15:04:40 +01001476 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1477 if (_Py_INIT_FAILED(err)) {
1478 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001479 }
Nick Coghland6009512014-11-20 21:39:37 +10001480
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001481 err = _PyImportHooks_Init();
1482 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001483 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001484 }
Nick Coghland6009512014-11-20 21:39:37 +10001485
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001486 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001487 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001488 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001489 }
Nick Coghland6009512014-11-20 21:39:37 +10001490
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001491 err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001492 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001493 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001494 }
Nick Coghland6009512014-11-20 21:39:37 +10001495
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001496 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001497 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001498 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001499 }
1500
Victor Stinner91106cd2017-12-13 12:29:09 +01001501 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001502 if (_Py_INIT_FAILED(err)) {
1503 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001504 }
1505
1506 err = add_main_module(interp);
1507 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001508 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001509 }
1510
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001511 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001512 err = init_import_size();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001513 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001514 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515 }
1516 }
Nick Coghland6009512014-11-20 21:39:37 +10001517 }
1518
Victor Stinnera7368ac2017-11-15 18:11:45 -08001519 if (PyErr_Occurred()) {
1520 goto handle_error;
1521 }
Nick Coghland6009512014-11-20 21:39:37 +10001522
Victor Stinnera7368ac2017-11-15 18:11:45 -08001523 *tstate_p = tstate;
1524 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001525
Nick Coghland6009512014-11-20 21:39:37 +10001526handle_error:
1527 /* Oops, it didn't work. Undo it all. */
1528
1529 PyErr_PrintEx(0);
1530 PyThreadState_Clear(tstate);
1531 PyThreadState_Swap(save_tstate);
1532 PyThreadState_Delete(tstate);
1533 PyInterpreterState_Delete(interp);
1534
Victor Stinnera7368ac2017-11-15 18:11:45 -08001535 *tstate_p = NULL;
1536 return _Py_INIT_OK();
1537}
1538
1539PyThreadState *
1540Py_NewInterpreter(void)
1541{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001542 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001543 _PyInitError err = new_interpreter(&tstate);
1544 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001545 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001546 }
1547 return tstate;
1548
Nick Coghland6009512014-11-20 21:39:37 +10001549}
1550
1551/* Delete an interpreter and its last thread. This requires that the
1552 given thread state is current, that the thread has no remaining
1553 frames, and that it is its interpreter's only remaining thread.
1554 It is a fatal error to violate these constraints.
1555
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001556 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001557 everything, regardless.)
1558
1559 Locking: as above.
1560
1561*/
1562
1563void
1564Py_EndInterpreter(PyThreadState *tstate)
1565{
1566 PyInterpreterState *interp = tstate->interp;
1567
Victor Stinner50b48572018-11-01 01:51:40 +01001568 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001569 Py_FatalError("Py_EndInterpreter: thread is not current");
1570 if (tstate->frame != NULL)
1571 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001572 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001573
Eric Snow842a2f02019-03-15 15:47:51 -06001574 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001575 wait_for_thread_shutdown();
1576
Marcel Plch776407f2017-12-20 11:17:58 +01001577 call_py_exitfuncs(interp);
1578
Nick Coghland6009512014-11-20 21:39:37 +10001579 if (tstate != interp->tstate_head || tstate->next != NULL)
1580 Py_FatalError("Py_EndInterpreter: not the last thread");
1581
1582 PyImport_Cleanup();
1583 PyInterpreterState_Clear(interp);
1584 PyThreadState_Swap(NULL);
1585 PyInterpreterState_Delete(interp);
1586}
1587
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001588/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001589
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001590static _PyInitError
1591add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001592{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001593 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001594 m = PyImport_AddModule("__main__");
1595 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001596 return _Py_INIT_ERR("can't create __main__ module");
1597
Nick Coghland6009512014-11-20 21:39:37 +10001598 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001599 ann_dict = PyDict_New();
1600 if ((ann_dict == NULL) ||
1601 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001602 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001603 }
1604 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001605
Nick Coghland6009512014-11-20 21:39:37 +10001606 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1607 PyObject *bimod = PyImport_ImportModule("builtins");
1608 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001609 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001610 }
1611 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001612 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001613 }
1614 Py_DECREF(bimod);
1615 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001616
Nick Coghland6009512014-11-20 21:39:37 +10001617 /* Main is a little special - imp.is_builtin("__main__") will return
1618 * False, but BuiltinImporter is still the most appropriate initial
1619 * setting for its __loader__ attribute. A more suitable value will
1620 * be set if __main__ gets further initialized later in the startup
1621 * process.
1622 */
1623 loader = PyDict_GetItemString(d, "__loader__");
1624 if (loader == NULL || loader == Py_None) {
1625 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1626 "BuiltinImporter");
1627 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001628 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001629 }
1630 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001631 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001632 }
1633 Py_DECREF(loader);
1634 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001635 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001636}
1637
Nick Coghland6009512014-11-20 21:39:37 +10001638/* Import the site module (not into __main__ though) */
1639
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001640static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001641init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001642{
1643 PyObject *m;
1644 m = PyImport_ImportModule("site");
1645 if (m == NULL) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001646 return _Py_INIT_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001647 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001648 Py_DECREF(m);
1649 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001650}
1651
Victor Stinner874dbe82015-09-04 17:29:57 +02001652/* Check if a file descriptor is valid or not.
1653 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1654static int
1655is_valid_fd(int fd)
1656{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001657/* dup() is faster than fstat(): fstat() can require input/output operations,
1658 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1659 startup. Problem: dup() doesn't check if the file descriptor is valid on
1660 some platforms.
1661
1662 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1663 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1664 EBADF. FreeBSD has similar issue (bpo-32849).
1665
1666 Only use dup() on platforms where dup() is enough to detect invalid FD in
1667 corner cases: on Linux and Windows (bpo-32849). */
1668#if defined(__linux__) || defined(MS_WINDOWS)
1669 if (fd < 0) {
1670 return 0;
1671 }
1672 int fd2;
1673
1674 _Py_BEGIN_SUPPRESS_IPH
1675 fd2 = dup(fd);
1676 if (fd2 >= 0) {
1677 close(fd2);
1678 }
1679 _Py_END_SUPPRESS_IPH
1680
1681 return (fd2 >= 0);
1682#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001683 struct stat st;
1684 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001685#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001686}
1687
1688/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001689static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001690create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001691 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001692 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001693{
1694 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1695 const char* mode;
1696 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001697 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001698 int buffering, isatty;
1699 _Py_IDENTIFIER(open);
1700 _Py_IDENTIFIER(isatty);
1701 _Py_IDENTIFIER(TextIOWrapper);
1702 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001703 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001704
Victor Stinner874dbe82015-09-04 17:29:57 +02001705 if (!is_valid_fd(fd))
1706 Py_RETURN_NONE;
1707
Nick Coghland6009512014-11-20 21:39:37 +10001708 /* stdin is always opened in buffered mode, first because it shouldn't
1709 make a difference in common use cases, second because TextIOWrapper
1710 depends on the presence of a read1() method which only exists on
1711 buffered streams.
1712 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001713 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001714 buffering = 0;
1715 else
1716 buffering = -1;
1717 if (write_mode)
1718 mode = "wb";
1719 else
1720 mode = "rb";
1721 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1722 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001723 Py_None, Py_None, /* encoding, errors */
1724 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001725 if (buf == NULL)
1726 goto error;
1727
1728 if (buffering) {
1729 _Py_IDENTIFIER(raw);
1730 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1731 if (raw == NULL)
1732 goto error;
1733 }
1734 else {
1735 raw = buf;
1736 Py_INCREF(raw);
1737 }
1738
Steve Dower39294992016-08-30 21:22:36 -07001739#ifdef MS_WINDOWS
1740 /* Windows console IO is always UTF-8 encoded */
1741 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001742 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001743#endif
1744
Nick Coghland6009512014-11-20 21:39:37 +10001745 text = PyUnicode_FromString(name);
1746 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1747 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001748 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001749 if (res == NULL)
1750 goto error;
1751 isatty = PyObject_IsTrue(res);
1752 Py_DECREF(res);
1753 if (isatty == -1)
1754 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001755 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001756 write_through = Py_True;
1757 else
1758 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001759 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001760 line_buffering = Py_True;
1761 else
1762 line_buffering = Py_False;
1763
1764 Py_CLEAR(raw);
1765 Py_CLEAR(text);
1766
1767#ifdef MS_WINDOWS
1768 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1769 newlines to "\n".
1770 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1771 newline = NULL;
1772#else
1773 /* sys.stdin: split lines at "\n".
1774 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1775 newline = "\n";
1776#endif
1777
Victor Stinner709d23d2019-05-02 14:56:30 -04001778 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1779 if (encoding_str == NULL) {
1780 Py_CLEAR(buf);
1781 goto error;
1782 }
1783
1784 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1785 if (errors_str == NULL) {
1786 Py_CLEAR(buf);
1787 Py_CLEAR(encoding_str);
1788 goto error;
1789 }
1790
1791 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1792 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001793 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001794 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001795 Py_CLEAR(encoding_str);
1796 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001797 if (stream == NULL)
1798 goto error;
1799
1800 if (write_mode)
1801 mode = "w";
1802 else
1803 mode = "r";
1804 text = PyUnicode_FromString(mode);
1805 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1806 goto error;
1807 Py_CLEAR(text);
1808 return stream;
1809
1810error:
1811 Py_XDECREF(buf);
1812 Py_XDECREF(stream);
1813 Py_XDECREF(text);
1814 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001815
Victor Stinner874dbe82015-09-04 17:29:57 +02001816 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1817 /* Issue #24891: the file descriptor was closed after the first
1818 is_valid_fd() check was called. Ignore the OSError and set the
1819 stream to None. */
1820 PyErr_Clear();
1821 Py_RETURN_NONE;
1822 }
1823 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001824}
1825
1826/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001827static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001828init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001829{
1830 PyObject *iomod = NULL, *wrapper;
1831 PyObject *bimod = NULL;
1832 PyObject *m;
1833 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001834 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001835 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001836 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001837 _PyCoreConfig *config = &interp->core_config;
1838
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001839 /* Check that stdin is not a directory
1840 Using shell redirection, you can redirect stdin to a directory,
1841 crashing the Python interpreter. Catch this common mistake here
1842 and output a useful error message. Note that under MS Windows,
1843 the shell already prevents that. */
1844#ifndef MS_WINDOWS
1845 struct _Py_stat_struct sb;
1846 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1847 S_ISDIR(sb.st_mode)) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001848 return _Py_INIT_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001849 }
1850#endif
1851
Nick Coghland6009512014-11-20 21:39:37 +10001852 /* Hack to avoid a nasty recursion issue when Python is invoked
1853 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1854 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1855 goto error;
1856 }
1857 Py_DECREF(m);
1858
1859 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1860 goto error;
1861 }
1862 Py_DECREF(m);
1863
1864 if (!(bimod = PyImport_ImportModule("builtins"))) {
1865 goto error;
1866 }
1867
1868 if (!(iomod = PyImport_ImportModule("io"))) {
1869 goto error;
1870 }
1871 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1872 goto error;
1873 }
1874
1875 /* Set builtins.open */
1876 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1877 Py_DECREF(wrapper);
1878 goto error;
1879 }
1880 Py_DECREF(wrapper);
1881
Nick Coghland6009512014-11-20 21:39:37 +10001882 /* Set sys.stdin */
1883 fd = fileno(stdin);
1884 /* Under some conditions stdin, stdout and stderr may not be connected
1885 * and fileno() may point to an invalid file descriptor. For example
1886 * GUI apps don't have valid standard streams by default.
1887 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001888 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001889 config->stdio_encoding,
1890 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001891 if (std == NULL)
1892 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001893 PySys_SetObject("__stdin__", std);
1894 _PySys_SetObjectId(&PyId_stdin, std);
1895 Py_DECREF(std);
1896
1897 /* Set sys.stdout */
1898 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001899 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001900 config->stdio_encoding,
1901 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001902 if (std == NULL)
1903 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001904 PySys_SetObject("__stdout__", std);
1905 _PySys_SetObjectId(&PyId_stdout, std);
1906 Py_DECREF(std);
1907
1908#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1909 /* Set sys.stderr, replaces the preliminary stderr */
1910 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001911 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001912 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001913 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001914 if (std == NULL)
1915 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001916
1917 /* Same as hack above, pre-import stderr's codec to avoid recursion
1918 when import.c tries to write to stderr in verbose mode. */
1919 encoding_attr = PyObject_GetAttrString(std, "encoding");
1920 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001921 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001922 if (std_encoding != NULL) {
1923 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1924 Py_XDECREF(codec_info);
1925 }
1926 Py_DECREF(encoding_attr);
1927 }
1928 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1929
1930 if (PySys_SetObject("__stderr__", std) < 0) {
1931 Py_DECREF(std);
1932 goto error;
1933 }
1934 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1935 Py_DECREF(std);
1936 goto error;
1937 }
1938 Py_DECREF(std);
1939#endif
1940
Victor Stinnera7368ac2017-11-15 18:11:45 -08001941 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001942
Victor Stinnera7368ac2017-11-15 18:11:45 -08001943error:
1944 res = _Py_INIT_ERR("can't initialize sys standard streams");
1945
1946done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001947 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001948
Nick Coghland6009512014-11-20 21:39:37 +10001949 Py_XDECREF(bimod);
1950 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001951 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001952}
1953
1954
Victor Stinner10dc4842015-03-24 12:01:30 +01001955static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001956_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001957{
Victor Stinner10dc4842015-03-24 12:01:30 +01001958 fputc('\n', stderr);
1959 fflush(stderr);
1960
1961 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001962 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001963}
Victor Stinner791da1c2016-03-14 16:53:12 +01001964
1965/* Print the current exception (if an exception is set) with its traceback,
1966 or display the current Python stack.
1967
1968 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1969 called on catastrophic cases.
1970
1971 Return 1 if the traceback was displayed, 0 otherwise. */
1972
1973static int
1974_Py_FatalError_PrintExc(int fd)
1975{
1976 PyObject *ferr, *res;
1977 PyObject *exception, *v, *tb;
1978 int has_tb;
1979
Victor Stinner791da1c2016-03-14 16:53:12 +01001980 PyErr_Fetch(&exception, &v, &tb);
1981 if (exception == NULL) {
1982 /* No current exception */
1983 return 0;
1984 }
1985
1986 ferr = _PySys_GetObjectId(&PyId_stderr);
1987 if (ferr == NULL || ferr == Py_None) {
1988 /* sys.stderr is not set yet or set to None,
1989 no need to try to display the exception */
1990 return 0;
1991 }
1992
1993 PyErr_NormalizeException(&exception, &v, &tb);
1994 if (tb == NULL) {
1995 tb = Py_None;
1996 Py_INCREF(tb);
1997 }
1998 PyException_SetTraceback(v, tb);
1999 if (exception == NULL) {
2000 /* PyErr_NormalizeException() failed */
2001 return 0;
2002 }
2003
2004 has_tb = (tb != Py_None);
2005 PyErr_Display(exception, v, tb);
2006 Py_XDECREF(exception);
2007 Py_XDECREF(v);
2008 Py_XDECREF(tb);
2009
2010 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002011 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002012 if (res == NULL)
2013 PyErr_Clear();
2014 else
2015 Py_DECREF(res);
2016
2017 return has_tb;
2018}
2019
Nick Coghland6009512014-11-20 21:39:37 +10002020/* Print fatal error message and abort */
2021
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002022#ifdef MS_WINDOWS
2023static void
2024fatal_output_debug(const char *msg)
2025{
2026 /* buffer of 256 bytes allocated on the stack */
2027 WCHAR buffer[256 / sizeof(WCHAR)];
2028 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2029 size_t msglen;
2030
2031 OutputDebugStringW(L"Fatal Python error: ");
2032
2033 msglen = strlen(msg);
2034 while (msglen) {
2035 size_t i;
2036
2037 if (buflen > msglen) {
2038 buflen = msglen;
2039 }
2040
2041 /* Convert the message to wchar_t. This uses a simple one-to-one
2042 conversion, assuming that the this error message actually uses
2043 ASCII only. If this ceases to be true, we will have to convert. */
2044 for (i=0; i < buflen; ++i) {
2045 buffer[i] = msg[i];
2046 }
2047 buffer[i] = L'\0';
2048 OutputDebugStringW(buffer);
2049
2050 msg += buflen;
2051 msglen -= buflen;
2052 }
2053 OutputDebugStringW(L"\n");
2054}
2055#endif
2056
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002057static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002058fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002059{
2060 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002061 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002062
2063 if (reentrant) {
2064 /* Py_FatalError() caused a second fatal error.
2065 Example: flush_std_files() raises a recursion error. */
2066 goto exit;
2067 }
2068 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002069
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002070 fprintf(stderr, "Fatal Python error: ");
2071 if (prefix) {
2072 fputs(prefix, stderr);
2073 fputs(": ", stderr);
2074 }
2075 if (msg) {
2076 fputs(msg, stderr);
2077 }
2078 else {
2079 fprintf(stderr, "<message not set>");
2080 }
2081 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002082 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002083
Victor Stinner3a228ab2018-11-01 00:26:41 +01002084 /* Check if the current thread has a Python thread state
2085 and holds the GIL */
2086 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2087 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002088 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002089 if (tss_tstate != tstate) {
2090 /* The Python thread does not hold the GIL */
2091 tss_tstate = NULL;
2092 }
2093 }
2094 else {
2095 /* Py_FatalError() has been called from a C thread
2096 which has no Python thread state. */
2097 }
2098 int has_tstate_and_gil = (tss_tstate != NULL);
2099
2100 if (has_tstate_and_gil) {
2101 /* If an exception is set, print the exception with its traceback */
2102 if (!_Py_FatalError_PrintExc(fd)) {
2103 /* No exception is set, or an exception is set without traceback */
2104 _Py_FatalError_DumpTracebacks(fd);
2105 }
2106 }
2107 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002108 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002109 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002110
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002111 /* The main purpose of faulthandler is to display the traceback.
2112 This function already did its best to display a traceback.
2113 Disable faulthandler to prevent writing a second traceback
2114 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002115 _PyFaulthandler_Fini();
2116
Victor Stinner791da1c2016-03-14 16:53:12 +01002117 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002118 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002119 /* Flush sys.stdout and sys.stderr */
2120 flush_std_files();
2121 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002122
Nick Coghland6009512014-11-20 21:39:37 +10002123#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002124 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002125#endif /* MS_WINDOWS */
2126
2127exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002128 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002129#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002130 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002131#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002132 abort();
2133 }
2134 else {
2135 exit(status);
2136 }
2137}
2138
Victor Stinner19760862017-12-20 01:41:59 +01002139void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002140Py_FatalError(const char *msg)
2141{
2142 fatal_error(NULL, msg, -1);
2143}
2144
Victor Stinner19760862017-12-20 01:41:59 +01002145void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002146_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002147{
Victor Stinnerdb719752019-05-01 05:35:33 +02002148 if (_Py_INIT_IS_EXIT(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01002149 exit(err.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002150 }
2151 else if (_Py_INIT_IS_ERROR(err)) {
2152 fatal_error(err._func, err.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002153 }
2154 else {
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002155 Py_FatalError("_Py_ExitInitError() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002156 }
Nick Coghland6009512014-11-20 21:39:37 +10002157}
2158
2159/* Clean up and exit */
2160
Victor Stinnerd7292b52016-06-17 12:29:00 +02002161# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002162
Nick Coghland6009512014-11-20 21:39:37 +10002163/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002164void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002165{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002166 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002167
Antoine Pitroufc5db952017-12-13 02:29:07 +01002168 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002169 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2170
2171 is->pyexitfunc = func;
2172 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002173}
2174
2175static void
Marcel Plch776407f2017-12-20 11:17:58 +01002176call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002177{
Marcel Plch776407f2017-12-20 11:17:58 +01002178 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002179 return;
2180
Marcel Plch776407f2017-12-20 11:17:58 +01002181 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002182 PyErr_Clear();
2183}
2184
2185/* Wait until threading._shutdown completes, provided
2186 the threading module was imported in the first place.
2187 The shutdown routine will wait until all non-daemon
2188 "threading" threads have completed. */
2189static void
2190wait_for_thread_shutdown(void)
2191{
Nick Coghland6009512014-11-20 21:39:37 +10002192 _Py_IDENTIFIER(_shutdown);
2193 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002194 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002195 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002196 if (PyErr_Occurred()) {
2197 PyErr_WriteUnraisable(NULL);
2198 }
2199 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002200 return;
2201 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002202 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002203 if (result == NULL) {
2204 PyErr_WriteUnraisable(threading);
2205 }
2206 else {
2207 Py_DECREF(result);
2208 }
2209 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002210}
2211
2212#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002213int Py_AtExit(void (*func)(void))
2214{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002215 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002216 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002217 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002218 return 0;
2219}
2220
2221static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002222call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002223{
Victor Stinner8e91c242019-04-24 17:24:01 +02002224 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002225 /* pop last function from the list */
2226 runtime->nexitfuncs--;
2227 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2228 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2229
2230 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002231 }
Nick Coghland6009512014-11-20 21:39:37 +10002232
2233 fflush(stdout);
2234 fflush(stderr);
2235}
2236
Victor Stinnercfc88312018-08-01 16:41:25 +02002237void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002238Py_Exit(int sts)
2239{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002240 if (Py_FinalizeEx() < 0) {
2241 sts = 120;
2242 }
Nick Coghland6009512014-11-20 21:39:37 +10002243
2244 exit(sts);
2245}
2246
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002247static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002248init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002249{
2250#ifdef SIGPIPE
2251 PyOS_setsig(SIGPIPE, SIG_IGN);
2252#endif
2253#ifdef SIGXFZ
2254 PyOS_setsig(SIGXFZ, SIG_IGN);
2255#endif
2256#ifdef SIGXFSZ
2257 PyOS_setsig(SIGXFSZ, SIG_IGN);
2258#endif
2259 PyOS_InitInterrupts(); /* May imply initsignal() */
2260 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002261 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002262 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002263 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002264}
2265
2266
2267/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2268 *
2269 * All of the code in this function must only use async-signal-safe functions,
2270 * listed at `man 7 signal` or
2271 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2272 */
2273void
2274_Py_RestoreSignals(void)
2275{
2276#ifdef SIGPIPE
2277 PyOS_setsig(SIGPIPE, SIG_DFL);
2278#endif
2279#ifdef SIGXFZ
2280 PyOS_setsig(SIGXFZ, SIG_DFL);
2281#endif
2282#ifdef SIGXFSZ
2283 PyOS_setsig(SIGXFSZ, SIG_DFL);
2284#endif
2285}
2286
2287
2288/*
2289 * The file descriptor fd is considered ``interactive'' if either
2290 * a) isatty(fd) is TRUE, or
2291 * b) the -i flag was given, and the filename associated with
2292 * the descriptor is NULL or "<stdin>" or "???".
2293 */
2294int
2295Py_FdIsInteractive(FILE *fp, const char *filename)
2296{
2297 if (isatty((int)fileno(fp)))
2298 return 1;
2299 if (!Py_InteractiveFlag)
2300 return 0;
2301 return (filename == NULL) ||
2302 (strcmp(filename, "<stdin>") == 0) ||
2303 (strcmp(filename, "???") == 0);
2304}
2305
2306
Nick Coghland6009512014-11-20 21:39:37 +10002307/* Wrappers around sigaction() or signal(). */
2308
2309PyOS_sighandler_t
2310PyOS_getsig(int sig)
2311{
2312#ifdef HAVE_SIGACTION
2313 struct sigaction context;
2314 if (sigaction(sig, NULL, &context) == -1)
2315 return SIG_ERR;
2316 return context.sa_handler;
2317#else
2318 PyOS_sighandler_t handler;
2319/* Special signal handling for the secure CRT in Visual Studio 2005 */
2320#if defined(_MSC_VER) && _MSC_VER >= 1400
2321 switch (sig) {
2322 /* Only these signals are valid */
2323 case SIGINT:
2324 case SIGILL:
2325 case SIGFPE:
2326 case SIGSEGV:
2327 case SIGTERM:
2328 case SIGBREAK:
2329 case SIGABRT:
2330 break;
2331 /* Don't call signal() with other values or it will assert */
2332 default:
2333 return SIG_ERR;
2334 }
2335#endif /* _MSC_VER && _MSC_VER >= 1400 */
2336 handler = signal(sig, SIG_IGN);
2337 if (handler != SIG_ERR)
2338 signal(sig, handler);
2339 return handler;
2340#endif
2341}
2342
2343/*
2344 * All of the code in this function must only use async-signal-safe functions,
2345 * listed at `man 7 signal` or
2346 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2347 */
2348PyOS_sighandler_t
2349PyOS_setsig(int sig, PyOS_sighandler_t handler)
2350{
2351#ifdef HAVE_SIGACTION
2352 /* Some code in Modules/signalmodule.c depends on sigaction() being
2353 * used here if HAVE_SIGACTION is defined. Fix that if this code
2354 * changes to invalidate that assumption.
2355 */
2356 struct sigaction context, ocontext;
2357 context.sa_handler = handler;
2358 sigemptyset(&context.sa_mask);
2359 context.sa_flags = 0;
2360 if (sigaction(sig, &context, &ocontext) == -1)
2361 return SIG_ERR;
2362 return ocontext.sa_handler;
2363#else
2364 PyOS_sighandler_t oldhandler;
2365 oldhandler = signal(sig, handler);
2366#ifdef HAVE_SIGINTERRUPT
2367 siginterrupt(sig, 1);
2368#endif
2369 return oldhandler;
2370#endif
2371}
2372
2373#ifdef __cplusplus
2374}
2375#endif