blob: 01f725f8f45a735ffd9aeb4d3016a0858a3f5c91 [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
Victor Stinner6d1c4672019-05-20 11:02:00 +0200694 if (src_config == NULL) {
695 return _Py_INIT_ERR("preinitialization config is NULL");
696 }
697
Victor Stinnerf29084d2019-03-20 02:20:13 +0100698 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100699 if (_Py_INIT_FAILED(err)) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100700 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100701 }
Victor Stinner43125222019-04-24 18:23:53 +0200702 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100703
Victor Stinner43125222019-04-24 18:23:53 +0200704 if (runtime->pre_initialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100705 /* If it's already configured: ignored the new configuration */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100706 return _Py_INIT_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100707 }
708
Victor Stinnercab5d072019-05-17 19:01:14 +0200709 _PyPreConfig config;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200710 _PyPreConfig_InitFromPreConfig(&config, src_config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100711
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 Stinner6d1c4672019-05-20 11:02:00 +0200754 assert(coreconfig != NULL);
755
756 _PyInitError err = _PyRuntime_Initialize();
757 if (_Py_INIT_FAILED(err)) {
758 return err;
759 }
760 _PyRuntimeState *runtime = &_PyRuntime;
761
762 if (runtime->pre_initialized) {
763 /* Already initialized: do nothing */
764 return _Py_INIT_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400765 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200766
Victor Stinner6d1c4672019-05-20 11:02:00 +0200767 _PyPreConfig preconfig;
768 _PyPreConfig_InitFromCoreConfig(&preconfig, coreconfig);
769
770 if (!coreconfig->parse_argv) {
771 return _Py_PreInitialize(&preconfig);
772 }
773 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200774 _PyArgv config_args = {
775 .use_bytes_argv = 0,
776 .argc = coreconfig->argv.length,
777 .wchar_argv = coreconfig->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200778 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200779 }
780 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200781 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200782 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100783}
784
785
786static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200787pyinit_coreconfig(_PyRuntimeState *runtime,
788 _PyCoreConfig *config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100789 const _PyCoreConfig *src_config,
790 const _PyArgv *args,
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100791 PyInterpreterState **interp_p)
792{
Victor Stinner6d1c4672019-05-20 11:02:00 +0200793 assert(src_config != NULL);
Victor Stinner5f38b842019-05-01 02:30:12 +0200794
Victor Stinner6d1c4672019-05-20 11:02:00 +0200795 _PyInitError err = _PyCoreConfig_Copy(config, src_config);
796 if (_Py_INIT_FAILED(err)) {
797 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100798 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100799
Victor Stinner5f38b842019-05-01 02:30:12 +0200800 if (args) {
801 err = _PyCoreConfig_SetPyArgv(config, args);
802 if (_Py_INIT_FAILED(err)) {
803 return err;
804 }
805 }
806
807 err = _PyCoreConfig_Read(config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100808 if (_Py_INIT_FAILED(err)) {
809 return err;
810 }
811
Victor Stinner43125222019-04-24 18:23:53 +0200812 if (!runtime->core_initialized) {
813 return _Py_InitializeCore_impl(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100814 }
815 else {
Victor Stinner43125222019-04-24 18:23:53 +0200816 return _Py_Initialize_ReconfigureCore(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100817 }
818}
819
820
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100821/* Begin interpreter initialization
822 *
823 * On return, the first thread and interpreter state have been created,
824 * but the compiler, signal handling, multithreading and
825 * multiple interpreter support, and codec infrastructure are not yet
826 * available.
827 *
828 * The import system will support builtin and frozen modules only.
829 * The only supported io is writing to sys.stderr
830 *
831 * If any operation invoked by this function fails, a fatal error is
832 * issued and the function does not return.
833 *
834 * Any code invoked from this function should *not* assume it has access
835 * to the Python C API (unless the API is explicitly listed as being
836 * safe to call without calling Py_Initialize first)
837 */
Victor Stinner484f20d2019-03-27 02:04:16 +0100838static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200839_Py_InitializeCore(_PyRuntimeState *runtime,
840 const _PyCoreConfig *src_config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100841 const _PyArgv *args,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100842 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200843{
Victor Stinnerd929f182019-03-27 18:28:46 +0100844 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200845
Victor Stinner70005ac2019-05-02 15:25:34 -0400846 err = _Py_PreInitializeFromCoreConfig(src_config, args);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200847 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100848 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200849 }
850
Victor Stinnercab5d072019-05-17 19:01:14 +0200851 _PyCoreConfig local_config;
852 _PyCoreConfig_Init(&local_config);
Victor Stinner43125222019-04-24 18:23:53 +0200853 err = pyinit_coreconfig(runtime, &local_config, src_config, args, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100854 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200855 return err;
856}
857
Victor Stinner5ac27a52019-03-27 13:40:14 +0100858
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200859/* Py_Initialize() has already been called: update the main interpreter
860 configuration. Example of bpo-34008: Py_Main() called after
861 Py_Initialize(). */
862static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100863_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200864{
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100865 _PyCoreConfig *core_config = &interp->core_config;
866
867 PyObject *argv = _PyWstrList_AsList(&core_config->argv);
868 if (argv == NULL) {
869 return _Py_INIT_NO_MEMORY(); \
870 }
871
872 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
873 Py_DECREF(argv);
874 if (res < 0) {
875 return _Py_INIT_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200876 }
877 return _Py_INIT_OK();
878}
879
Eric Snowc7ec9982017-05-23 23:00:52 -0700880/* Update interpreter state based on supplied configuration settings
881 *
882 * After calling this function, most of the restrictions on the interpreter
883 * are lifted. The only remaining incomplete settings are those related
884 * to the main module (sys.argv[0], __main__ metadata)
885 *
886 * Calling this when the interpreter is not initializing, is already
887 * initialized or without a valid current thread state is a fatal error.
888 * Other errors should be reported as normal Python exceptions with a
889 * non-zero return code.
890 */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100891static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200892_Py_InitializeMainInterpreter(_PyRuntimeState *runtime,
893 PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700894{
Victor Stinner43125222019-04-24 18:23:53 +0200895 if (!runtime->core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800896 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700897 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700898
Victor Stinner1dc6e392018-07-25 02:49:17 +0200899 /* Configure the main interpreter */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200900 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700901
Victor Stinner43125222019-04-24 18:23:53 +0200902 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100903 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200904 }
905
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200906 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700907 /* Special mode for freeze_importlib: run with no import system
908 *
909 * This means anything which needs support from extension modules
910 * or pure Python code in the standard library won't work.
911 */
Victor Stinner43125222019-04-24 18:23:53 +0200912 runtime->initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700914 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100915
Victor Stinner33c377e2017-12-05 15:12:41 +0100916 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800917 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100918 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200919
Victor Stinner43125222019-04-24 18:23:53 +0200920 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800921 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100922 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800923
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400924 _PyInitError err = init_importlib_external(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
929 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200930 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 if (_Py_INIT_FAILED(err)) {
932 return err;
933 }
Nick Coghland6009512014-11-20 21:39:37 +1000934
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400935 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800936 if (_Py_INIT_FAILED(err)) {
937 return err;
938 }
Nick Coghland6009512014-11-20 21:39:37 +1000939
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100940 if (core_config->install_signal_handlers) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400941 err = init_signals();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800942 if (_Py_INIT_FAILED(err)) {
943 return err;
944 }
945 }
Nick Coghland6009512014-11-20 21:39:37 +1000946
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200947 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800948 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200949 }
Nick Coghland6009512014-11-20 21:39:37 +1000950
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800951 err = add_main_module(interp);
952 if (_Py_INIT_FAILED(err)) {
953 return err;
954 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800955
Victor Stinner91106cd2017-12-13 12:29:09 +0100956 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800957 if (_Py_INIT_FAILED(err)) {
958 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800959 }
Nick Coghland6009512014-11-20 21:39:37 +1000960
961 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100962 PyObject *warnoptions = PySys_GetObject("warnoptions");
963 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100964 {
Nick Coghland6009512014-11-20 21:39:37 +1000965 PyObject *warnings_module = PyImport_ImportModule("warnings");
966 if (warnings_module == NULL) {
967 fprintf(stderr, "'import warnings' failed; traceback:\n");
968 PyErr_Print();
969 }
970 Py_XDECREF(warnings_module);
971 }
972
Victor Stinner43125222019-04-24 18:23:53 +0200973 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700974
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200975 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400976 err = init_import_size(); /* Module site */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800977 if (_Py_INIT_FAILED(err)) {
978 return err;
979 }
980 }
Victor Stinnercf215042018-08-29 22:56:06 +0200981
982#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200983 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200984#endif
985
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800986 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000987}
988
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200989
990_PyInitError
991_Py_InitializeMain(void)
992{
993 _PyInitError err = _PyRuntime_Initialize();
994 if (_Py_INIT_FAILED(err)) {
995 return err;
996 }
997 _PyRuntimeState *runtime = &_PyRuntime;
998 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
999
1000 return _Py_InitializeMainInterpreter(runtime, interp);
1001}
1002
1003
Eric Snowc7ec9982017-05-23 23:00:52 -07001004#undef _INIT_DEBUG_PRINT
1005
Victor Stinner5ac27a52019-03-27 13:40:14 +01001006static _PyInitError
1007init_python(const _PyCoreConfig *config, const _PyArgv *args)
Eric Snow1abcf672017-05-23 21:46:51 -07001008{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001009 if (config == NULL) {
1010 return _Py_INIT_ERR("initialization config is NULL");
1011 }
1012
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001013 _PyInitError err;
Victor Stinner43125222019-04-24 18:23:53 +02001014
1015 err = _PyRuntime_Initialize();
1016 if (_Py_INIT_FAILED(err)) {
1017 return err;
1018 }
1019 _PyRuntimeState *runtime = &_PyRuntime;
1020
1021 PyInterpreterState *interp = NULL;
1022 err = _Py_InitializeCore(runtime, config, args, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001023 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001024 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001025 }
Victor Stinner1dc6e392018-07-25 02:49:17 +02001026 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001027
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001028 if (config->_init_main) {
Victor Stinner43125222019-04-24 18:23:53 +02001029 err = _Py_InitializeMainInterpreter(runtime, interp);
Victor Stinner484f20d2019-03-27 02:04:16 +01001030 if (_Py_INIT_FAILED(err)) {
1031 return err;
1032 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001033 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001034
Victor Stinner1dc6e392018-07-25 02:49:17 +02001035 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001036}
1037
1038
Victor Stinner5ac27a52019-03-27 13:40:14 +01001039_PyInitError
Victor Stinner6d1c4672019-05-20 11:02:00 +02001040_Py_InitializeFromArgs(const _PyCoreConfig *config,
1041 Py_ssize_t argc, char * const *argv)
Victor Stinner5ac27a52019-03-27 13:40:14 +01001042{
1043 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1044 return init_python(config, &args);
1045}
1046
1047
1048_PyInitError
Victor Stinner6d1c4672019-05-20 11:02:00 +02001049_Py_InitializeFromWideArgs(const _PyCoreConfig *config,
1050 Py_ssize_t argc, wchar_t * const *argv)
Victor Stinner5ac27a52019-03-27 13:40:14 +01001051{
1052 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1053 return init_python(config, &args);
1054}
1055
1056
1057_PyInitError
1058_Py_InitializeFromConfig(const _PyCoreConfig *config)
1059{
1060 return init_python(config, NULL);
1061}
1062
1063
Eric Snow1abcf672017-05-23 21:46:51 -07001064void
Nick Coghland6009512014-11-20 21:39:37 +10001065Py_InitializeEx(int install_sigs)
1066{
Victor Stinner43125222019-04-24 18:23:53 +02001067 _PyInitError err;
1068
1069 err = _PyRuntime_Initialize();
1070 if (_Py_INIT_FAILED(err)) {
1071 _Py_ExitInitError(err);
1072 }
1073 _PyRuntimeState *runtime = &_PyRuntime;
1074
1075 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001076 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1077 return;
1078 }
1079
Victor Stinnercab5d072019-05-17 19:01:14 +02001080 _PyCoreConfig config;
1081 _PyCoreConfig_Init(&config);
Victor Stinner1dc6e392018-07-25 02:49:17 +02001082 config.install_signal_handlers = install_sigs;
1083
Victor Stinner43125222019-04-24 18:23:53 +02001084 err = _Py_InitializeFromConfig(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001085 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001086 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001087 }
Nick Coghland6009512014-11-20 21:39:37 +10001088}
1089
1090void
1091Py_Initialize(void)
1092{
1093 Py_InitializeEx(1);
1094}
1095
1096
1097#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001098extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001099#endif
1100
1101/* Flush stdout and stderr */
1102
1103static int
1104file_is_closed(PyObject *fobj)
1105{
1106 int r;
1107 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1108 if (tmp == NULL) {
1109 PyErr_Clear();
1110 return 0;
1111 }
1112 r = PyObject_IsTrue(tmp);
1113 Py_DECREF(tmp);
1114 if (r < 0)
1115 PyErr_Clear();
1116 return r > 0;
1117}
1118
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001119static int
Nick Coghland6009512014-11-20 21:39:37 +10001120flush_std_files(void)
1121{
1122 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1123 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1124 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001125 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001126
1127 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001128 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001129 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001130 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001131 status = -1;
1132 }
Nick Coghland6009512014-11-20 21:39:37 +10001133 else
1134 Py_DECREF(tmp);
1135 }
1136
1137 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001138 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001139 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001140 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001141 status = -1;
1142 }
Nick Coghland6009512014-11-20 21:39:37 +10001143 else
1144 Py_DECREF(tmp);
1145 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001146
1147 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001148}
1149
1150/* Undo the effect of Py_Initialize().
1151
1152 Beware: if multiple interpreter and/or thread states exist, these
1153 are not wiped out; only the current thread and interpreter state
1154 are deleted. But since everything else is deleted, those other
1155 interpreter and thread states should no longer be used.
1156
1157 (XXX We should do better, e.g. wipe out all interpreters and
1158 threads.)
1159
1160 Locking: as above.
1161
1162*/
1163
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001164int
1165Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001166{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001167 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001168
Victor Stinner8e91c242019-04-24 17:24:01 +02001169 _PyRuntimeState *runtime = &_PyRuntime;
1170 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001171 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001172 }
Nick Coghland6009512014-11-20 21:39:37 +10001173
Eric Snow842a2f02019-03-15 15:47:51 -06001174 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001175 wait_for_thread_shutdown();
1176
Eric Snow842a2f02019-03-15 15:47:51 -06001177 // Make any remaining pending calls.
Victor Stinner09532fe2019-05-10 23:39:09 +02001178 _Py_FinishPendingCalls(runtime);
Eric Snow842a2f02019-03-15 15:47:51 -06001179
Victor Stinner8e91c242019-04-24 17:24:01 +02001180 /* Get current thread state and interpreter pointer */
Victor Stinner09532fe2019-05-10 23:39:09 +02001181 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner8e91c242019-04-24 17:24:01 +02001182 PyInterpreterState *interp = tstate->interp;
1183
Nick Coghland6009512014-11-20 21:39:37 +10001184 /* The interpreter is still entirely intact at this point, and the
1185 * exit funcs may be relying on that. In particular, if some thread
1186 * or exit func is still waiting to do an import, the import machinery
1187 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001188 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001189 * Note that Threading.py uses an exit func to do a join on all the
1190 * threads created thru it, so this also protects pending imports in
1191 * the threads created via Threading.
1192 */
Nick Coghland6009512014-11-20 21:39:37 +10001193
Marcel Plch776407f2017-12-20 11:17:58 +01001194 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001195
Victor Stinnerda273412017-12-15 01:46:02 +01001196 /* Copy the core config, PyInterpreterState_Delete() free
1197 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001198#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001199 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001200#endif
1201#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001202 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001203#endif
1204#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001205 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001206#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001207
Nick Coghland6009512014-11-20 21:39:37 +10001208 /* Remaining threads (e.g. daemon threads) will automatically exit
1209 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001210 runtime->finalizing = tstate;
1211 runtime->initialized = 0;
1212 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001213
Victor Stinnere0deff32015-03-24 13:46:18 +01001214 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001215 if (flush_std_files() < 0) {
1216 status = -1;
1217 }
Nick Coghland6009512014-11-20 21:39:37 +10001218
1219 /* Disable signal handling */
1220 PyOS_FiniInterrupts();
1221
1222 /* Collect garbage. This may call finalizers; it's nice to call these
1223 * before all modules are destroyed.
1224 * XXX If a __del__ or weakref callback is triggered here, and tries to
1225 * XXX import a module, bad things can happen, because Python no
1226 * XXX longer believes it's initialized.
1227 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1228 * XXX is easy to provoke that way. I've also seen, e.g.,
1229 * XXX Exception exceptions.ImportError: 'No module named sha'
1230 * XXX in <function callback at 0x008F5718> ignored
1231 * XXX but I'm unclear on exactly how that one happens. In any case,
1232 * XXX I haven't seen a real-life report of either of these.
1233 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001234 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001235#ifdef COUNT_ALLOCS
1236 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1237 each collection might release some types from the type
1238 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001239 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001240 /* nothing */;
1241#endif
Eric Snowdae02762017-09-14 00:35:58 -07001242
Nick Coghland6009512014-11-20 21:39:37 +10001243 /* Destroy all modules */
1244 PyImport_Cleanup();
1245
Victor Stinnere0deff32015-03-24 13:46:18 +01001246 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001247 if (flush_std_files() < 0) {
1248 status = -1;
1249 }
Nick Coghland6009512014-11-20 21:39:37 +10001250
1251 /* Collect final garbage. This disposes of cycles created by
1252 * class definitions, for example.
1253 * XXX This is disabled because it caused too many problems. If
1254 * XXX a __del__ or weakref callback triggers here, Python code has
1255 * XXX a hard time running, because even the sys module has been
1256 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1257 * XXX One symptom is a sequence of information-free messages
1258 * XXX coming from threads (if a __del__ or callback is invoked,
1259 * XXX other threads can execute too, and any exception they encounter
1260 * XXX triggers a comedy of errors as subsystem after subsystem
1261 * XXX fails to find what it *expects* to find in sys to help report
1262 * XXX the exception and consequent unexpected failures). I've also
1263 * XXX seen segfaults then, after adding print statements to the
1264 * XXX Python code getting called.
1265 */
1266#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001267 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001268#endif
1269
1270 /* Disable tracemalloc after all Python objects have been destroyed,
1271 so it is possible to use tracemalloc in objects destructor. */
1272 _PyTraceMalloc_Fini();
1273
1274 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1275 _PyImport_Fini();
1276
1277 /* Cleanup typeobject.c's internal caches. */
1278 _PyType_Fini();
1279
1280 /* unload faulthandler module */
1281 _PyFaulthandler_Fini();
1282
1283 /* Debugging stuff */
1284#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001285 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001286#endif
1287 /* dump hash stats */
1288 _PyHash_Fini();
1289
Eric Snowdae02762017-09-14 00:35:58 -07001290#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001291 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001292 _PyDebug_PrintTotalRefs();
1293 }
Eric Snowdae02762017-09-14 00:35:58 -07001294#endif
Nick Coghland6009512014-11-20 21:39:37 +10001295
1296#ifdef Py_TRACE_REFS
1297 /* Display all objects still alive -- this can invoke arbitrary
1298 * __repr__ overrides, so requires a mostly-intact interpreter.
1299 * Alas, a lot of stuff may still be alive now that will be cleaned
1300 * up later.
1301 */
Victor Stinnerda273412017-12-15 01:46:02 +01001302 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001303 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001304 }
Nick Coghland6009512014-11-20 21:39:37 +10001305#endif /* Py_TRACE_REFS */
1306
1307 /* Clear interpreter state and all thread states. */
1308 PyInterpreterState_Clear(interp);
1309
1310 /* Now we decref the exception classes. After this point nothing
1311 can raise an exception. That's okay, because each Fini() method
1312 below has been checked to make sure no exceptions are ever
1313 raised.
1314 */
1315
1316 _PyExc_Fini();
1317
1318 /* Sundry finalizers */
1319 PyMethod_Fini();
1320 PyFrame_Fini();
1321 PyCFunction_Fini();
1322 PyTuple_Fini();
1323 PyList_Fini();
1324 PySet_Fini();
1325 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001326 PyLong_Fini();
1327 PyFloat_Fini();
1328 PyDict_Fini();
1329 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001330 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001331 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001332 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001333 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001334 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001335 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001336
1337 /* Cleanup Unicode implementation */
1338 _PyUnicode_Fini();
1339
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001340 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001341
1342 /* XXX Still allocated:
1343 - various static ad-hoc pointers to interned strings
1344 - int and float free list blocks
1345 - whatever various modules and libraries allocate
1346 */
1347
1348 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1349
1350 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001351 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001352
1353 /* Delete current thread. After this, many C API calls become crashy. */
1354 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001355
Nick Coghland6009512014-11-20 21:39:37 +10001356 PyInterpreterState_Delete(interp);
1357
1358#ifdef Py_TRACE_REFS
1359 /* Display addresses (& refcnts) of all objects still alive.
1360 * An address can be used to find the repr of the object, printed
1361 * above by _Py_PrintReferences.
1362 */
Victor Stinnerda273412017-12-15 01:46:02 +01001363 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001364 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001365 }
Nick Coghland6009512014-11-20 21:39:37 +10001366#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001367#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001368 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001369 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001370 }
Nick Coghland6009512014-11-20 21:39:37 +10001371#endif
1372
Victor Stinner8e91c242019-04-24 17:24:01 +02001373 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001374
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001375 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001376 return status;
1377}
1378
1379void
1380Py_Finalize(void)
1381{
1382 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001383}
1384
1385/* Create and initialize a new interpreter and thread, and return the
1386 new thread. This requires that Py_Initialize() has been called
1387 first.
1388
1389 Unsuccessful initialization yields a NULL pointer. Note that *no*
1390 exception information is available even in this case -- the
1391 exception information is held in the thread, and there is no
1392 thread.
1393
1394 Locking: as above.
1395
1396*/
1397
Victor Stinnera7368ac2017-11-15 18:11:45 -08001398static _PyInitError
1399new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001400{
Victor Stinner9316ee42017-11-25 03:17:57 +01001401 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001402
Victor Stinner43125222019-04-24 18:23:53 +02001403 err = _PyRuntime_Initialize();
1404 if (_Py_INIT_FAILED(err)) {
1405 return err;
1406 }
1407 _PyRuntimeState *runtime = &_PyRuntime;
1408
1409 if (!runtime->initialized) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001410 return _Py_INIT_ERR("Py_Initialize must be called first");
1411 }
Nick Coghland6009512014-11-20 21:39:37 +10001412
Victor Stinner8a1be612016-03-14 22:07:55 +01001413 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1414 interpreters: disable PyGILState_Check(). */
1415 _PyGILState_check_enabled = 0;
1416
Victor Stinner43125222019-04-24 18:23:53 +02001417 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001418 if (interp == NULL) {
1419 *tstate_p = NULL;
1420 return _Py_INIT_OK();
1421 }
Nick Coghland6009512014-11-20 21:39:37 +10001422
Victor Stinner43125222019-04-24 18:23:53 +02001423 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001424 if (tstate == NULL) {
1425 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001426 *tstate_p = NULL;
1427 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001428 }
1429
Victor Stinner43125222019-04-24 18:23:53 +02001430 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001431
Eric Snow1abcf672017-05-23 21:46:51 -07001432 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001433 _PyCoreConfig *core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001434 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001435 core_config = &save_tstate->interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001436 } else {
1437 /* No current thread state, copy from the main interpreter */
1438 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001439 core_config = &main_interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001440 }
1441
Victor Stinner1a9f0d82019-05-01 15:22:52 +02001442 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
1443 if (_Py_INIT_FAILED(err)) {
1444 return err;
Victor Stinnerda273412017-12-15 01:46:02 +01001445 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001446 core_config = &interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001447
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001448 err = _PyExc_Init();
1449 if (_Py_INIT_FAILED(err)) {
1450 return err;
1451 }
1452
Nick Coghland6009512014-11-20 21:39:37 +10001453 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001454 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001455 if (modules == NULL) {
1456 return _Py_INIT_ERR("can't make modules dictionary");
1457 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001458 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001459
Victor Stinner43125222019-04-24 18:23:53 +02001460 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001461 if (sysmod != NULL) {
1462 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001463 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001464 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001465 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001466 Py_INCREF(interp->sysdict);
1467 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner43125222019-04-24 18:23:53 +02001468 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerab672812019-01-23 15:04:40 +01001469 return _Py_INIT_ERR("can't finish initializing sys");
1470 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001471 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001472 else if (PyErr_Occurred()) {
1473 goto handle_error;
1474 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001475
Victor Stinner43125222019-04-24 18:23:53 +02001476 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001477 if (bimod != NULL) {
1478 interp->builtins = PyModule_GetDict(bimod);
1479 if (interp->builtins == NULL)
1480 goto handle_error;
1481 Py_INCREF(interp->builtins);
1482 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001483 else if (PyErr_Occurred()) {
1484 goto handle_error;
1485 }
Nick Coghland6009512014-11-20 21:39:37 +10001486
Nick Coghland6009512014-11-20 21:39:37 +10001487 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001488 err = _PyBuiltins_AddExceptions(bimod);
1489 if (_Py_INIT_FAILED(err)) {
1490 return err;
1491 }
Nick Coghland6009512014-11-20 21:39:37 +10001492
Victor Stinnerab672812019-01-23 15:04:40 +01001493 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1494 if (_Py_INIT_FAILED(err)) {
1495 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001496 }
Nick Coghland6009512014-11-20 21:39:37 +10001497
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498 err = _PyImportHooks_Init();
1499 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001500 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001501 }
Nick Coghland6009512014-11-20 21:39:37 +10001502
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001503 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001504 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001505 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001506 }
Nick Coghland6009512014-11-20 21:39:37 +10001507
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001508 err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001509 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001510 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001511 }
Nick Coghland6009512014-11-20 21:39:37 +10001512
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001513 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001514 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001515 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001516 }
1517
Victor Stinner91106cd2017-12-13 12:29:09 +01001518 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001519 if (_Py_INIT_FAILED(err)) {
1520 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001521 }
1522
1523 err = add_main_module(interp);
1524 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001525 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001526 }
1527
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001528 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001529 err = init_import_size();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001530 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001531 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001532 }
1533 }
Nick Coghland6009512014-11-20 21:39:37 +10001534 }
1535
Victor Stinnera7368ac2017-11-15 18:11:45 -08001536 if (PyErr_Occurred()) {
1537 goto handle_error;
1538 }
Nick Coghland6009512014-11-20 21:39:37 +10001539
Victor Stinnera7368ac2017-11-15 18:11:45 -08001540 *tstate_p = tstate;
1541 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001542
Nick Coghland6009512014-11-20 21:39:37 +10001543handle_error:
1544 /* Oops, it didn't work. Undo it all. */
1545
1546 PyErr_PrintEx(0);
1547 PyThreadState_Clear(tstate);
1548 PyThreadState_Swap(save_tstate);
1549 PyThreadState_Delete(tstate);
1550 PyInterpreterState_Delete(interp);
1551
Victor Stinnera7368ac2017-11-15 18:11:45 -08001552 *tstate_p = NULL;
1553 return _Py_INIT_OK();
1554}
1555
1556PyThreadState *
1557Py_NewInterpreter(void)
1558{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001559 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001560 _PyInitError err = new_interpreter(&tstate);
1561 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001562 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001563 }
1564 return tstate;
1565
Nick Coghland6009512014-11-20 21:39:37 +10001566}
1567
1568/* Delete an interpreter and its last thread. This requires that the
1569 given thread state is current, that the thread has no remaining
1570 frames, and that it is its interpreter's only remaining thread.
1571 It is a fatal error to violate these constraints.
1572
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001573 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001574 everything, regardless.)
1575
1576 Locking: as above.
1577
1578*/
1579
1580void
1581Py_EndInterpreter(PyThreadState *tstate)
1582{
1583 PyInterpreterState *interp = tstate->interp;
1584
Victor Stinner50b48572018-11-01 01:51:40 +01001585 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001586 Py_FatalError("Py_EndInterpreter: thread is not current");
1587 if (tstate->frame != NULL)
1588 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001589 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001590
Eric Snow842a2f02019-03-15 15:47:51 -06001591 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001592 wait_for_thread_shutdown();
1593
Marcel Plch776407f2017-12-20 11:17:58 +01001594 call_py_exitfuncs(interp);
1595
Nick Coghland6009512014-11-20 21:39:37 +10001596 if (tstate != interp->tstate_head || tstate->next != NULL)
1597 Py_FatalError("Py_EndInterpreter: not the last thread");
1598
1599 PyImport_Cleanup();
1600 PyInterpreterState_Clear(interp);
1601 PyThreadState_Swap(NULL);
1602 PyInterpreterState_Delete(interp);
1603}
1604
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001605/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001606
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001607static _PyInitError
1608add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001609{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001610 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001611 m = PyImport_AddModule("__main__");
1612 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001613 return _Py_INIT_ERR("can't create __main__ module");
1614
Nick Coghland6009512014-11-20 21:39:37 +10001615 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001616 ann_dict = PyDict_New();
1617 if ((ann_dict == NULL) ||
1618 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001619 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001620 }
1621 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001622
Nick Coghland6009512014-11-20 21:39:37 +10001623 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1624 PyObject *bimod = PyImport_ImportModule("builtins");
1625 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001626 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001627 }
1628 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001629 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001630 }
1631 Py_DECREF(bimod);
1632 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001633
Nick Coghland6009512014-11-20 21:39:37 +10001634 /* Main is a little special - imp.is_builtin("__main__") will return
1635 * False, but BuiltinImporter is still the most appropriate initial
1636 * setting for its __loader__ attribute. A more suitable value will
1637 * be set if __main__ gets further initialized later in the startup
1638 * process.
1639 */
1640 loader = PyDict_GetItemString(d, "__loader__");
1641 if (loader == NULL || loader == Py_None) {
1642 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1643 "BuiltinImporter");
1644 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001645 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001646 }
1647 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001648 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001649 }
1650 Py_DECREF(loader);
1651 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001652 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001653}
1654
Nick Coghland6009512014-11-20 21:39:37 +10001655/* Import the site module (not into __main__ though) */
1656
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001657static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001658init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001659{
1660 PyObject *m;
1661 m = PyImport_ImportModule("site");
1662 if (m == NULL) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001663 return _Py_INIT_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001664 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001665 Py_DECREF(m);
1666 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001667}
1668
Victor Stinner874dbe82015-09-04 17:29:57 +02001669/* Check if a file descriptor is valid or not.
1670 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1671static int
1672is_valid_fd(int fd)
1673{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001674/* dup() is faster than fstat(): fstat() can require input/output operations,
1675 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1676 startup. Problem: dup() doesn't check if the file descriptor is valid on
1677 some platforms.
1678
1679 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1680 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1681 EBADF. FreeBSD has similar issue (bpo-32849).
1682
1683 Only use dup() on platforms where dup() is enough to detect invalid FD in
1684 corner cases: on Linux and Windows (bpo-32849). */
1685#if defined(__linux__) || defined(MS_WINDOWS)
1686 if (fd < 0) {
1687 return 0;
1688 }
1689 int fd2;
1690
1691 _Py_BEGIN_SUPPRESS_IPH
1692 fd2 = dup(fd);
1693 if (fd2 >= 0) {
1694 close(fd2);
1695 }
1696 _Py_END_SUPPRESS_IPH
1697
1698 return (fd2 >= 0);
1699#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001700 struct stat st;
1701 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001702#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001703}
1704
1705/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001706static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001707create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001708 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001709 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001710{
1711 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1712 const char* mode;
1713 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001714 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001715 int buffering, isatty;
1716 _Py_IDENTIFIER(open);
1717 _Py_IDENTIFIER(isatty);
1718 _Py_IDENTIFIER(TextIOWrapper);
1719 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001720 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001721
Victor Stinner874dbe82015-09-04 17:29:57 +02001722 if (!is_valid_fd(fd))
1723 Py_RETURN_NONE;
1724
Nick Coghland6009512014-11-20 21:39:37 +10001725 /* stdin is always opened in buffered mode, first because it shouldn't
1726 make a difference in common use cases, second because TextIOWrapper
1727 depends on the presence of a read1() method which only exists on
1728 buffered streams.
1729 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001730 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001731 buffering = 0;
1732 else
1733 buffering = -1;
1734 if (write_mode)
1735 mode = "wb";
1736 else
1737 mode = "rb";
1738 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1739 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001740 Py_None, Py_None, /* encoding, errors */
1741 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001742 if (buf == NULL)
1743 goto error;
1744
1745 if (buffering) {
1746 _Py_IDENTIFIER(raw);
1747 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1748 if (raw == NULL)
1749 goto error;
1750 }
1751 else {
1752 raw = buf;
1753 Py_INCREF(raw);
1754 }
1755
Steve Dower39294992016-08-30 21:22:36 -07001756#ifdef MS_WINDOWS
1757 /* Windows console IO is always UTF-8 encoded */
1758 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001759 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001760#endif
1761
Nick Coghland6009512014-11-20 21:39:37 +10001762 text = PyUnicode_FromString(name);
1763 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1764 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001765 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001766 if (res == NULL)
1767 goto error;
1768 isatty = PyObject_IsTrue(res);
1769 Py_DECREF(res);
1770 if (isatty == -1)
1771 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001772 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001773 write_through = Py_True;
1774 else
1775 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001776 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001777 line_buffering = Py_True;
1778 else
1779 line_buffering = Py_False;
1780
1781 Py_CLEAR(raw);
1782 Py_CLEAR(text);
1783
1784#ifdef MS_WINDOWS
1785 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1786 newlines to "\n".
1787 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1788 newline = NULL;
1789#else
1790 /* sys.stdin: split lines at "\n".
1791 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1792 newline = "\n";
1793#endif
1794
Victor Stinner709d23d2019-05-02 14:56:30 -04001795 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1796 if (encoding_str == NULL) {
1797 Py_CLEAR(buf);
1798 goto error;
1799 }
1800
1801 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1802 if (errors_str == NULL) {
1803 Py_CLEAR(buf);
1804 Py_CLEAR(encoding_str);
1805 goto error;
1806 }
1807
1808 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1809 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001810 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001811 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001812 Py_CLEAR(encoding_str);
1813 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001814 if (stream == NULL)
1815 goto error;
1816
1817 if (write_mode)
1818 mode = "w";
1819 else
1820 mode = "r";
1821 text = PyUnicode_FromString(mode);
1822 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1823 goto error;
1824 Py_CLEAR(text);
1825 return stream;
1826
1827error:
1828 Py_XDECREF(buf);
1829 Py_XDECREF(stream);
1830 Py_XDECREF(text);
1831 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001832
Victor Stinner874dbe82015-09-04 17:29:57 +02001833 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1834 /* Issue #24891: the file descriptor was closed after the first
1835 is_valid_fd() check was called. Ignore the OSError and set the
1836 stream to None. */
1837 PyErr_Clear();
1838 Py_RETURN_NONE;
1839 }
1840 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001841}
1842
1843/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001844static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001845init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001846{
1847 PyObject *iomod = NULL, *wrapper;
1848 PyObject *bimod = NULL;
1849 PyObject *m;
1850 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001851 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001852 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001853 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001854 _PyCoreConfig *config = &interp->core_config;
1855
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001856 /* Check that stdin is not a directory
1857 Using shell redirection, you can redirect stdin to a directory,
1858 crashing the Python interpreter. Catch this common mistake here
1859 and output a useful error message. Note that under MS Windows,
1860 the shell already prevents that. */
1861#ifndef MS_WINDOWS
1862 struct _Py_stat_struct sb;
1863 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1864 S_ISDIR(sb.st_mode)) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001865 return _Py_INIT_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001866 }
1867#endif
1868
Nick Coghland6009512014-11-20 21:39:37 +10001869 /* Hack to avoid a nasty recursion issue when Python is invoked
1870 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1871 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1872 goto error;
1873 }
1874 Py_DECREF(m);
1875
1876 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1877 goto error;
1878 }
1879 Py_DECREF(m);
1880
1881 if (!(bimod = PyImport_ImportModule("builtins"))) {
1882 goto error;
1883 }
1884
1885 if (!(iomod = PyImport_ImportModule("io"))) {
1886 goto error;
1887 }
1888 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1889 goto error;
1890 }
1891
1892 /* Set builtins.open */
1893 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1894 Py_DECREF(wrapper);
1895 goto error;
1896 }
1897 Py_DECREF(wrapper);
1898
Nick Coghland6009512014-11-20 21:39:37 +10001899 /* Set sys.stdin */
1900 fd = fileno(stdin);
1901 /* Under some conditions stdin, stdout and stderr may not be connected
1902 * and fileno() may point to an invalid file descriptor. For example
1903 * GUI apps don't have valid standard streams by default.
1904 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001905 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001906 config->stdio_encoding,
1907 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001908 if (std == NULL)
1909 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001910 PySys_SetObject("__stdin__", std);
1911 _PySys_SetObjectId(&PyId_stdin, std);
1912 Py_DECREF(std);
1913
1914 /* Set sys.stdout */
1915 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001916 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001917 config->stdio_encoding,
1918 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001919 if (std == NULL)
1920 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001921 PySys_SetObject("__stdout__", std);
1922 _PySys_SetObjectId(&PyId_stdout, std);
1923 Py_DECREF(std);
1924
1925#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1926 /* Set sys.stderr, replaces the preliminary stderr */
1927 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001928 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001929 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001930 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001931 if (std == NULL)
1932 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001933
1934 /* Same as hack above, pre-import stderr's codec to avoid recursion
1935 when import.c tries to write to stderr in verbose mode. */
1936 encoding_attr = PyObject_GetAttrString(std, "encoding");
1937 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001938 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001939 if (std_encoding != NULL) {
1940 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1941 Py_XDECREF(codec_info);
1942 }
1943 Py_DECREF(encoding_attr);
1944 }
1945 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1946
1947 if (PySys_SetObject("__stderr__", std) < 0) {
1948 Py_DECREF(std);
1949 goto error;
1950 }
1951 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1952 Py_DECREF(std);
1953 goto error;
1954 }
1955 Py_DECREF(std);
1956#endif
1957
Victor Stinnera7368ac2017-11-15 18:11:45 -08001958 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001959
Victor Stinnera7368ac2017-11-15 18:11:45 -08001960error:
1961 res = _Py_INIT_ERR("can't initialize sys standard streams");
1962
1963done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001964 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001965
Nick Coghland6009512014-11-20 21:39:37 +10001966 Py_XDECREF(bimod);
1967 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001968 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001969}
1970
1971
Victor Stinner10dc4842015-03-24 12:01:30 +01001972static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001973_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001974{
Victor Stinner10dc4842015-03-24 12:01:30 +01001975 fputc('\n', stderr);
1976 fflush(stderr);
1977
1978 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001979 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001980}
Victor Stinner791da1c2016-03-14 16:53:12 +01001981
1982/* Print the current exception (if an exception is set) with its traceback,
1983 or display the current Python stack.
1984
1985 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1986 called on catastrophic cases.
1987
1988 Return 1 if the traceback was displayed, 0 otherwise. */
1989
1990static int
1991_Py_FatalError_PrintExc(int fd)
1992{
1993 PyObject *ferr, *res;
1994 PyObject *exception, *v, *tb;
1995 int has_tb;
1996
Victor Stinner791da1c2016-03-14 16:53:12 +01001997 PyErr_Fetch(&exception, &v, &tb);
1998 if (exception == NULL) {
1999 /* No current exception */
2000 return 0;
2001 }
2002
2003 ferr = _PySys_GetObjectId(&PyId_stderr);
2004 if (ferr == NULL || ferr == Py_None) {
2005 /* sys.stderr is not set yet or set to None,
2006 no need to try to display the exception */
2007 return 0;
2008 }
2009
2010 PyErr_NormalizeException(&exception, &v, &tb);
2011 if (tb == NULL) {
2012 tb = Py_None;
2013 Py_INCREF(tb);
2014 }
2015 PyException_SetTraceback(v, tb);
2016 if (exception == NULL) {
2017 /* PyErr_NormalizeException() failed */
2018 return 0;
2019 }
2020
2021 has_tb = (tb != Py_None);
2022 PyErr_Display(exception, v, tb);
2023 Py_XDECREF(exception);
2024 Py_XDECREF(v);
2025 Py_XDECREF(tb);
2026
2027 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002028 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002029 if (res == NULL)
2030 PyErr_Clear();
2031 else
2032 Py_DECREF(res);
2033
2034 return has_tb;
2035}
2036
Nick Coghland6009512014-11-20 21:39:37 +10002037/* Print fatal error message and abort */
2038
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002039#ifdef MS_WINDOWS
2040static void
2041fatal_output_debug(const char *msg)
2042{
2043 /* buffer of 256 bytes allocated on the stack */
2044 WCHAR buffer[256 / sizeof(WCHAR)];
2045 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2046 size_t msglen;
2047
2048 OutputDebugStringW(L"Fatal Python error: ");
2049
2050 msglen = strlen(msg);
2051 while (msglen) {
2052 size_t i;
2053
2054 if (buflen > msglen) {
2055 buflen = msglen;
2056 }
2057
2058 /* Convert the message to wchar_t. This uses a simple one-to-one
2059 conversion, assuming that the this error message actually uses
2060 ASCII only. If this ceases to be true, we will have to convert. */
2061 for (i=0; i < buflen; ++i) {
2062 buffer[i] = msg[i];
2063 }
2064 buffer[i] = L'\0';
2065 OutputDebugStringW(buffer);
2066
2067 msg += buflen;
2068 msglen -= buflen;
2069 }
2070 OutputDebugStringW(L"\n");
2071}
2072#endif
2073
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002074static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002075fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002076{
2077 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002078 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002079
2080 if (reentrant) {
2081 /* Py_FatalError() caused a second fatal error.
2082 Example: flush_std_files() raises a recursion error. */
2083 goto exit;
2084 }
2085 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002086
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002087 fprintf(stderr, "Fatal Python error: ");
2088 if (prefix) {
2089 fputs(prefix, stderr);
2090 fputs(": ", stderr);
2091 }
2092 if (msg) {
2093 fputs(msg, stderr);
2094 }
2095 else {
2096 fprintf(stderr, "<message not set>");
2097 }
2098 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002099 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002100
Victor Stinner3a228ab2018-11-01 00:26:41 +01002101 /* Check if the current thread has a Python thread state
2102 and holds the GIL */
2103 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2104 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002105 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002106 if (tss_tstate != tstate) {
2107 /* The Python thread does not hold the GIL */
2108 tss_tstate = NULL;
2109 }
2110 }
2111 else {
2112 /* Py_FatalError() has been called from a C thread
2113 which has no Python thread state. */
2114 }
2115 int has_tstate_and_gil = (tss_tstate != NULL);
2116
2117 if (has_tstate_and_gil) {
2118 /* If an exception is set, print the exception with its traceback */
2119 if (!_Py_FatalError_PrintExc(fd)) {
2120 /* No exception is set, or an exception is set without traceback */
2121 _Py_FatalError_DumpTracebacks(fd);
2122 }
2123 }
2124 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002125 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002126 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002127
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002128 /* The main purpose of faulthandler is to display the traceback.
2129 This function already did its best to display a traceback.
2130 Disable faulthandler to prevent writing a second traceback
2131 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002132 _PyFaulthandler_Fini();
2133
Victor Stinner791da1c2016-03-14 16:53:12 +01002134 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002135 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002136 /* Flush sys.stdout and sys.stderr */
2137 flush_std_files();
2138 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002139
Nick Coghland6009512014-11-20 21:39:37 +10002140#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002141 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002142#endif /* MS_WINDOWS */
2143
2144exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002145 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002146#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002147 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002148#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002149 abort();
2150 }
2151 else {
2152 exit(status);
2153 }
2154}
2155
Victor Stinner19760862017-12-20 01:41:59 +01002156void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002157Py_FatalError(const char *msg)
2158{
2159 fatal_error(NULL, msg, -1);
2160}
2161
Victor Stinner19760862017-12-20 01:41:59 +01002162void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002163_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002164{
Victor Stinnerdb719752019-05-01 05:35:33 +02002165 if (_Py_INIT_IS_EXIT(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01002166 exit(err.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002167 }
2168 else if (_Py_INIT_IS_ERROR(err)) {
2169 fatal_error(err._func, err.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002170 }
2171 else {
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002172 Py_FatalError("_Py_ExitInitError() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002173 }
Nick Coghland6009512014-11-20 21:39:37 +10002174}
2175
2176/* Clean up and exit */
2177
Victor Stinnerd7292b52016-06-17 12:29:00 +02002178# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002179
Nick Coghland6009512014-11-20 21:39:37 +10002180/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002181void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002182{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002183 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002184
Antoine Pitroufc5db952017-12-13 02:29:07 +01002185 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002186 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2187
2188 is->pyexitfunc = func;
2189 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002190}
2191
2192static void
Marcel Plch776407f2017-12-20 11:17:58 +01002193call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002194{
Marcel Plch776407f2017-12-20 11:17:58 +01002195 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002196 return;
2197
Marcel Plch776407f2017-12-20 11:17:58 +01002198 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002199 PyErr_Clear();
2200}
2201
2202/* Wait until threading._shutdown completes, provided
2203 the threading module was imported in the first place.
2204 The shutdown routine will wait until all non-daemon
2205 "threading" threads have completed. */
2206static void
2207wait_for_thread_shutdown(void)
2208{
Nick Coghland6009512014-11-20 21:39:37 +10002209 _Py_IDENTIFIER(_shutdown);
2210 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002211 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002212 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002213 if (PyErr_Occurred()) {
2214 PyErr_WriteUnraisable(NULL);
2215 }
2216 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002217 return;
2218 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002219 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002220 if (result == NULL) {
2221 PyErr_WriteUnraisable(threading);
2222 }
2223 else {
2224 Py_DECREF(result);
2225 }
2226 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002227}
2228
2229#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002230int Py_AtExit(void (*func)(void))
2231{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002232 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002233 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002234 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002235 return 0;
2236}
2237
2238static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002239call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002240{
Victor Stinner8e91c242019-04-24 17:24:01 +02002241 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002242 /* pop last function from the list */
2243 runtime->nexitfuncs--;
2244 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2245 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2246
2247 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002248 }
Nick Coghland6009512014-11-20 21:39:37 +10002249
2250 fflush(stdout);
2251 fflush(stderr);
2252}
2253
Victor Stinnercfc88312018-08-01 16:41:25 +02002254void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002255Py_Exit(int sts)
2256{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002257 if (Py_FinalizeEx() < 0) {
2258 sts = 120;
2259 }
Nick Coghland6009512014-11-20 21:39:37 +10002260
2261 exit(sts);
2262}
2263
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002264static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002265init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002266{
2267#ifdef SIGPIPE
2268 PyOS_setsig(SIGPIPE, SIG_IGN);
2269#endif
2270#ifdef SIGXFZ
2271 PyOS_setsig(SIGXFZ, SIG_IGN);
2272#endif
2273#ifdef SIGXFSZ
2274 PyOS_setsig(SIGXFSZ, SIG_IGN);
2275#endif
2276 PyOS_InitInterrupts(); /* May imply initsignal() */
2277 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002278 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002279 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002280 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002281}
2282
2283
2284/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2285 *
2286 * All of the code in this function must only use async-signal-safe functions,
2287 * listed at `man 7 signal` or
2288 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2289 */
2290void
2291_Py_RestoreSignals(void)
2292{
2293#ifdef SIGPIPE
2294 PyOS_setsig(SIGPIPE, SIG_DFL);
2295#endif
2296#ifdef SIGXFZ
2297 PyOS_setsig(SIGXFZ, SIG_DFL);
2298#endif
2299#ifdef SIGXFSZ
2300 PyOS_setsig(SIGXFSZ, SIG_DFL);
2301#endif
2302}
2303
2304
2305/*
2306 * The file descriptor fd is considered ``interactive'' if either
2307 * a) isatty(fd) is TRUE, or
2308 * b) the -i flag was given, and the filename associated with
2309 * the descriptor is NULL or "<stdin>" or "???".
2310 */
2311int
2312Py_FdIsInteractive(FILE *fp, const char *filename)
2313{
2314 if (isatty((int)fileno(fp)))
2315 return 1;
2316 if (!Py_InteractiveFlag)
2317 return 0;
2318 return (filename == NULL) ||
2319 (strcmp(filename, "<stdin>") == 0) ||
2320 (strcmp(filename, "???") == 0);
2321}
2322
2323
Nick Coghland6009512014-11-20 21:39:37 +10002324/* Wrappers around sigaction() or signal(). */
2325
2326PyOS_sighandler_t
2327PyOS_getsig(int sig)
2328{
2329#ifdef HAVE_SIGACTION
2330 struct sigaction context;
2331 if (sigaction(sig, NULL, &context) == -1)
2332 return SIG_ERR;
2333 return context.sa_handler;
2334#else
2335 PyOS_sighandler_t handler;
2336/* Special signal handling for the secure CRT in Visual Studio 2005 */
2337#if defined(_MSC_VER) && _MSC_VER >= 1400
2338 switch (sig) {
2339 /* Only these signals are valid */
2340 case SIGINT:
2341 case SIGILL:
2342 case SIGFPE:
2343 case SIGSEGV:
2344 case SIGTERM:
2345 case SIGBREAK:
2346 case SIGABRT:
2347 break;
2348 /* Don't call signal() with other values or it will assert */
2349 default:
2350 return SIG_ERR;
2351 }
2352#endif /* _MSC_VER && _MSC_VER >= 1400 */
2353 handler = signal(sig, SIG_IGN);
2354 if (handler != SIG_ERR)
2355 signal(sig, handler);
2356 return handler;
2357#endif
2358}
2359
2360/*
2361 * All of the code in this function must only use async-signal-safe functions,
2362 * listed at `man 7 signal` or
2363 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2364 */
2365PyOS_sighandler_t
2366PyOS_setsig(int sig, PyOS_sighandler_t handler)
2367{
2368#ifdef HAVE_SIGACTION
2369 /* Some code in Modules/signalmodule.c depends on sigaction() being
2370 * used here if HAVE_SIGACTION is defined. Fix that if this code
2371 * changes to invalidate that assumption.
2372 */
2373 struct sigaction context, ocontext;
2374 context.sa_handler = handler;
2375 sigemptyset(&context.sa_mask);
2376 context.sa_flags = 0;
2377 if (sigaction(sig, &context, &ocontext) == -1)
2378 return SIG_ERR;
2379 return ocontext.sa_handler;
2380#else
2381 PyOS_sighandler_t oldhandler;
2382 oldhandler = signal(sig, handler);
2383#ifdef HAVE_SIGINTERRUPT
2384 siginterrupt(sig, 1);
2385#endif
2386 return oldhandler;
2387#endif
2388}
2389
2390#ifdef __cplusplus
2391}
2392#endif