blob: 32902aa0d597d028c0626f6ca4a8a47134f69cd4 [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 Stinnerb36e5d62019-04-29 11:15:56 +02007#include "pycore_coreconfig.h"
Victor Stinner99fcc612019-04-29 13:04:07 +02008#include "pycore_context.h"
Victor Stinner353933e2018-11-23 13:08:26 +01009#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010010#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010011#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010012#include "pycore_pylifecycle.h"
13#include "pycore_pymem.h"
14#include "pycore_pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100015#include "grammar.h"
16#include "node.h"
17#include "token.h"
18#include "parsetok.h"
19#include "errcode.h"
20#include "code.h"
21#include "symtable.h"
22#include "ast.h"
23#include "marshal.h"
24#include "osdefs.h"
25#include <locale.h>
26
27#ifdef HAVE_SIGNAL_H
28#include <signal.h>
29#endif
30
31#ifdef MS_WINDOWS
32#include "malloc.h" /* for alloca */
33#endif
34
35#ifdef HAVE_LANGINFO_H
36#include <langinfo.h>
37#endif
38
39#ifdef MS_WINDOWS
40#undef BYTE
41#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070042
43extern PyTypeObject PyWindowsConsoleIO_Type;
44#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100045#endif
46
47_Py_IDENTIFIER(flush);
48_Py_IDENTIFIER(name);
49_Py_IDENTIFIER(stdin);
50_Py_IDENTIFIER(stdout);
51_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060052_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100053
54#ifdef __cplusplus
55extern "C" {
56#endif
57
Nick Coghland6009512014-11-20 21:39:37 +100058extern grammar _PyParser_Grammar; /* From graminit.c */
59
60/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080061static _PyInitError add_main_module(PyInterpreterState *interp);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040062static _PyInitError init_import_size(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010063static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040064static _PyInitError init_signals(void);
Marcel Plch776407f2017-12-20 11:17:58 +010065static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100066static void wait_for_thread_shutdown(void);
Victor Stinner8e91c242019-04-24 17:24:01 +020067static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100068
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080069int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080070_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010071static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060072
Victor Stinnerf7e5b562017-11-15 15:48:08 -080073_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060074_PyRuntime_Initialize(void)
75{
76 /* XXX We only initialize once in the process, which aligns with
77 the static initialization of the former globals now found in
78 _PyRuntime. However, _PyRuntime *should* be initialized with
79 every Py_Initialize() call, but doing so breaks the runtime.
80 This is because the runtime state is not properly finalized
81 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010082 if (runtime_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080083 return _Py_INIT_OK();
84 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010085 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080086
87 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
89
90void
91_PyRuntime_Finalize(void)
92{
93 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010094 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095}
96
97int
98_Py_IsFinalizing(void)
99{
100 return _PyRuntime.finalizing != NULL;
101}
102
Nick Coghland6009512014-11-20 21:39:37 +1000103/* Hack to force loading of object files */
104int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
105 PyOS_mystrnicmp; /* Python/pystrcmp.o */
106
107/* PyModule_GetWarningsModule is no longer necessary as of 2.6
108since _warnings is builtin. This API should not be used. */
109PyObject *
110PyModule_GetWarningsModule(void)
111{
112 return PyImport_ImportModule("warnings");
113}
114
Eric Snowc7ec9982017-05-23 23:00:52 -0700115
Eric Snow1abcf672017-05-23 21:46:51 -0700116/* APIs to access the initialization flags
117 *
118 * Can be called prior to Py_Initialize.
119 */
Nick Coghland6009512014-11-20 21:39:37 +1000120
Eric Snow1abcf672017-05-23 21:46:51 -0700121int
122_Py_IsCoreInitialized(void)
123{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600124 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700125}
Nick Coghland6009512014-11-20 21:39:37 +1000126
127int
128Py_IsInitialized(void)
129{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600130 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000131}
132
Nick Coghlan6ea41862017-06-11 13:16:15 +1000133
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000134/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
135 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000136 initializations fail, a fatal error is issued and the function does
137 not return. On return, the first thread and interpreter state have
138 been created.
139
140 Locking: you must hold the interpreter lock while calling this.
141 (If the lock has not yet been initialized, that's equivalent to
142 having the lock, but you cannot use multiple threads.)
143
144*/
145
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800146static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400147init_importlib(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000148{
149 PyObject *importlib;
150 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000151 PyObject *value;
152
153 /* Import _importlib through its frozen version, _frozen_importlib. */
154 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800155 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000156 }
157 else if (Py_VerboseFlag) {
158 PySys_FormatStderr("import _frozen_importlib # frozen\n");
159 }
160 importlib = PyImport_AddModule("_frozen_importlib");
161 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800162 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000163 }
164 interp->importlib = importlib;
165 Py_INCREF(interp->importlib);
166
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300167 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
168 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800169 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300170 Py_INCREF(interp->import_func);
171
Victor Stinnercd6e6942015-09-18 09:11:57 +0200172 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800173 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000174 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800175 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000176 }
177 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200178 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000179 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600180 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800181 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000182 }
183
Victor Stinnercd6e6942015-09-18 09:11:57 +0200184 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000185 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
186 if (value == NULL) {
187 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800188 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000189 }
190 Py_DECREF(value);
191 Py_DECREF(impmod);
192
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800193 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000194}
195
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800196static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400197init_importlib_external(PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700198{
199 PyObject *value;
200 value = PyObject_CallMethod(interp->importlib,
201 "_install_external_importers", "");
202 if (value == NULL) {
203 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800204 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700205 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200206 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300207 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700208}
Nick Coghland6009512014-11-20 21:39:37 +1000209
Nick Coghlan6ea41862017-06-11 13:16:15 +1000210/* Helper functions to better handle the legacy C locale
211 *
212 * The legacy C locale assumes ASCII as the default text encoding, which
213 * causes problems not only for the CPython runtime, but also other
214 * components like GNU readline.
215 *
216 * Accordingly, when the CLI detects it, it attempts to coerce it to a
217 * more capable UTF-8 based alternative as follows:
218 *
219 * if (_Py_LegacyLocaleDetected()) {
220 * _Py_CoerceLegacyLocale();
221 * }
222 *
223 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
224 *
225 * Locale coercion also impacts the default error handler for the standard
226 * streams: while the usual default is "strict", the default for the legacy
227 * C locale and for any of the coercion target locales is "surrogateescape".
228 */
229
230int
231_Py_LegacyLocaleDetected(void)
232{
233#ifndef MS_WINDOWS
234 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000235 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
236 * the POSIX locale as a simple alias for the C locale, so
237 * we may also want to check for that explicitly.
238 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000239 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
240 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
241#else
242 /* Windows uses code pages instead of locales, so no locale is legacy */
243 return 0;
244#endif
245}
246
Nick Coghlaneb817952017-06-18 12:29:42 +1000247static const char *_C_LOCALE_WARNING =
248 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
249 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
250 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
251 "locales is recommended.\n";
252
Nick Coghlaneb817952017-06-18 12:29:42 +1000253static void
Victor Stinner43125222019-04-24 18:23:53 +0200254emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000255{
Victor Stinner43125222019-04-24 18:23:53 +0200256 const _PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner20004952019-03-26 02:31:11 +0100257 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200258 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000259 }
260}
261
Nick Coghlan6ea41862017-06-11 13:16:15 +1000262typedef struct _CandidateLocale {
263 const char *locale_name; /* The locale to try as a coercion target */
264} _LocaleCoercionTarget;
265
266static _LocaleCoercionTarget _TARGET_LOCALES[] = {
267 {"C.UTF-8"},
268 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000269 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000270 {NULL}
271};
272
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200273
274int
275_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000276{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200277 const _LocaleCoercionTarget *target = NULL;
278 for (target = _TARGET_LOCALES; target->locale_name; target++) {
279 if (strcmp(ctype_loc, target->locale_name) == 0) {
280 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000281 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200282 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200283 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000284}
285
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200286
Nick Coghlan6ea41862017-06-11 13:16:15 +1000287#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100288static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000289 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
290 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
291
292static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200293_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294{
295 const char *newloc = target->locale_name;
296
297 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100298 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000299
300 /* Set the relevant locale environment variable */
301 if (setenv("LC_CTYPE", newloc, 1)) {
302 fprintf(stderr,
303 "Error setting LC_CTYPE, skipping C locale coercion\n");
304 return;
305 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200306 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100307 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000308 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000309
310 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100311 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312}
313#endif
314
315void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200316_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317{
318#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200319 char *oldloc = NULL;
320
321 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
322 if (oldloc == NULL) {
323 return;
324 }
325
Victor Stinner94540602017-12-16 04:54:22 +0100326 const char *locale_override = getenv("LC_ALL");
327 if (locale_override == NULL || *locale_override == '\0') {
328 /* LC_ALL is also not set (or is set to an empty string) */
329 const _LocaleCoercionTarget *target = NULL;
330 for (target = _TARGET_LOCALES; target->locale_name; target++) {
331 const char *new_locale = setlocale(LC_CTYPE,
332 target->locale_name);
333 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400334#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100335 /* Also ensure that nl_langinfo works in this locale */
336 char *codeset = nl_langinfo(CODESET);
337 if (!codeset || *codeset == '\0') {
338 /* CODESET is not set or empty, so skip coercion */
339 new_locale = NULL;
340 _Py_SetLocaleFromEnv(LC_CTYPE);
341 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000342 }
Victor Stinner94540602017-12-16 04:54:22 +0100343#endif
344 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200345 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200346 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000347 }
348 }
349 }
350 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200351
352 setlocale(LC_CTYPE, oldloc);
353
354done:
355 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000356#endif
357}
358
xdegaye1588be62017-11-12 12:45:59 +0100359/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
360 * isolate the idiosyncrasies of different libc implementations. It reads the
361 * appropriate environment variable and uses its value to select the locale for
362 * 'category'. */
363char *
364_Py_SetLocaleFromEnv(int category)
365{
Victor Stinner353933e2018-11-23 13:08:26 +0100366 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100367#ifdef __ANDROID__
368 const char *locale;
369 const char **pvar;
370#ifdef PY_COERCE_C_LOCALE
371 const char *coerce_c_locale;
372#endif
373 const char *utf8_locale = "C.UTF-8";
374 const char *env_var_set[] = {
375 "LC_ALL",
376 "LC_CTYPE",
377 "LANG",
378 NULL,
379 };
380
381 /* Android setlocale(category, "") doesn't check the environment variables
382 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
383 * check the environment variables listed in env_var_set. */
384 for (pvar=env_var_set; *pvar; pvar++) {
385 locale = getenv(*pvar);
386 if (locale != NULL && *locale != '\0') {
387 if (strcmp(locale, utf8_locale) == 0 ||
388 strcmp(locale, "en_US.UTF-8") == 0) {
389 return setlocale(category, utf8_locale);
390 }
391 return setlocale(category, "C");
392 }
393 }
394
395 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
396 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
397 * Quote from POSIX section "8.2 Internationalization Variables":
398 * "4. If the LANG environment variable is not set or is set to the empty
399 * string, the implementation-defined default locale shall be used." */
400
401#ifdef PY_COERCE_C_LOCALE
402 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
403 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
404 /* Some other ported code may check the environment variables (e.g. in
405 * extension modules), so we make sure that they match the locale
406 * configuration */
407 if (setenv("LC_CTYPE", utf8_locale, 1)) {
408 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
409 "environment variable to %s\n", utf8_locale);
410 }
411 }
412#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100413 res = setlocale(category, utf8_locale);
414#else /* !defined(__ANDROID__) */
415 res = setlocale(category, "");
416#endif
417 _Py_ResetForceASCII();
418 return res;
xdegaye1588be62017-11-12 12:45:59 +0100419}
420
Nick Coghlan6ea41862017-06-11 13:16:15 +1000421
Eric Snow1abcf672017-05-23 21:46:51 -0700422/* Global initializations. Can be undone by Py_Finalize(). Don't
423 call this twice without an intervening Py_Finalize() call.
424
Victor Stinner484f20d2019-03-27 02:04:16 +0100425 Every call to _Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700426 must have a corresponding call to Py_Finalize.
427
428 Locking: you must hold the interpreter lock while calling these APIs.
429 (If the lock has not yet been initialized, that's equivalent to
430 having the lock, but you cannot use multiple threads.)
431
432*/
433
Victor Stinner1dc6e392018-07-25 02:49:17 +0200434static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200435_Py_Initialize_ReconfigureCore(_PyRuntimeState *runtime,
436 PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200437 const _PyCoreConfig *core_config)
438{
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200439 _PyInitError err;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100440 PyThreadState *tstate = _PyThreadState_GET();
441 if (!tstate) {
442 return _Py_INIT_ERR("failed to read thread state");
443 }
444
445 PyInterpreterState *interp = tstate->interp;
446 if (interp == NULL) {
447 return _Py_INIT_ERR("can't make main interpreter");
448 }
449 *interp_p = interp;
450
Victor Stinner43125222019-04-24 18:23:53 +0200451 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200452
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200453 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
454 if (_Py_INIT_FAILED(err)) {
455 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200456 }
457 core_config = &interp->core_config;
458
459 if (core_config->_install_importlib) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200460 err = _PyCoreConfig_SetPathConfig(core_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200461 if (_Py_INIT_FAILED(err)) {
462 return err;
463 }
464 }
465 return _Py_INIT_OK();
466}
467
468
Victor Stinner1dc6e392018-07-25 02:49:17 +0200469static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200470pycore_init_runtime(_PyRuntimeState *runtime,
471 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000472{
Victor Stinner43125222019-04-24 18:23:53 +0200473 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200474 return _Py_INIT_ERR("main interpreter already initialized");
475 }
Victor Stinnerda273412017-12-15 01:46:02 +0100476
Victor Stinner43125222019-04-24 18:23:53 +0200477 _PyCoreConfig_Write(core_config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600478
Eric Snow1abcf672017-05-23 21:46:51 -0700479 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
480 * threads behave a little more gracefully at interpreter shutdown.
481 * We clobber it here so the new interpreter can start with a clean
482 * slate.
483 *
484 * However, this may still lead to misbehaviour if there are daemon
485 * threads still hanging around from a previous Py_Initialize/Finalize
486 * pair :(
487 */
Victor Stinner43125222019-04-24 18:23:53 +0200488 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600489
Victor Stinner43125222019-04-24 18:23:53 +0200490 _PyInitError err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800491 if (_Py_INIT_FAILED(err)) {
492 return err;
493 }
494
Victor Stinner43125222019-04-24 18:23:53 +0200495 err = _PyInterpreterState_Enable(runtime);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800496 if (_Py_INIT_FAILED(err)) {
497 return err;
498 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100499 return _Py_INIT_OK();
500}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800501
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100502
503static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200504pycore_create_interpreter(_PyRuntimeState *runtime,
505 const _PyCoreConfig *core_config,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100506 PyInterpreterState **interp_p)
507{
508 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100509 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800510 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100511 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200512 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100513
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200514 _PyInitError err = _PyCoreConfig_Copy(&interp->core_config, core_config);
515 if (_Py_INIT_FAILED(err)) {
516 return err;
Victor Stinnerda273412017-12-15 01:46:02 +0100517 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200518 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000519
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200520 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000521 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800522 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000523 (void) PyThreadState_Swap(tstate);
524
Victor Stinner99fcc612019-04-29 13:04:07 +0200525 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
526 destroying the GIL might fail when it is being referenced from
527 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000528 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000529 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner99fcc612019-04-29 13:04:07 +0200530 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100531
Nick Coghland6009512014-11-20 21:39:37 +1000532 /* Auto-thread-state API */
Victor Stinner43125222019-04-24 18:23:53 +0200533 _PyGILState_Init(runtime, interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000534
Victor Stinner2914bb32018-01-29 11:57:45 +0100535 /* Create the GIL */
536 PyEval_InitThreads();
537
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100538 return _Py_INIT_OK();
539}
Nick Coghland6009512014-11-20 21:39:37 +1000540
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100541
542static _PyInitError
543pycore_init_types(void)
544{
Victor Stinnerab672812019-01-23 15:04:40 +0100545 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100546 if (_Py_INIT_FAILED(err)) {
547 return err;
548 }
549
550 err = _PyUnicode_Init();
551 if (_Py_INIT_FAILED(err)) {
552 return err;
553 }
554
555 if (_PyStructSequence_Init() < 0) {
556 return _Py_INIT_ERR("can't initialize structseq");
557 }
558
559 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800560 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100561 }
Nick Coghland6009512014-11-20 21:39:37 +1000562
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100563 err = _PyExc_Init();
564 if (_Py_INIT_FAILED(err)) {
565 return err;
566 }
567
568 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800569 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100570 }
Nick Coghland6009512014-11-20 21:39:37 +1000571
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100572 if (!_PyContext_Init()) {
573 return _Py_INIT_ERR("can't init context");
574 }
575 return _Py_INIT_OK();
576}
577
578
579static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100580pycore_init_builtins(PyInterpreterState *interp)
581{
582 PyObject *bimod = _PyBuiltin_Init();
583 if (bimod == NULL) {
584 return _Py_INIT_ERR("can't initialize builtins modules");
585 }
586 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
587
588 interp->builtins = PyModule_GetDict(bimod);
589 if (interp->builtins == NULL) {
590 return _Py_INIT_ERR("can't initialize builtins dict");
591 }
592 Py_INCREF(interp->builtins);
593
594 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
595 if (_Py_INIT_FAILED(err)) {
596 return err;
597 }
598 return _Py_INIT_OK();
599}
600
601
602static _PyInitError
603pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
604{
605 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800606 if (_Py_INIT_FAILED(err)) {
607 return err;
608 }
Nick Coghland6009512014-11-20 21:39:37 +1000609
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800610 err = _PyImportHooks_Init();
611 if (_Py_INIT_FAILED(err)) {
612 return err;
613 }
Nick Coghland6009512014-11-20 21:39:37 +1000614
615 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100616 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100617 return _Py_INIT_ERR("can't initialize warnings");
618 }
Nick Coghland6009512014-11-20 21:39:37 +1000619
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100620 if (interp->core_config._install_importlib) {
621 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200622 if (_Py_INIT_FAILED(err)) {
623 return err;
624 }
625 }
626
Eric Snow1abcf672017-05-23 21:46:51 -0700627 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100628 if (interp->core_config._install_importlib) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400629 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800630 if (_Py_INIT_FAILED(err)) {
631 return err;
632 }
Eric Snow1abcf672017-05-23 21:46:51 -0700633 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100634 return _Py_INIT_OK();
635}
636
637
638static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200639_Py_InitializeCore_impl(_PyRuntimeState *runtime,
640 PyInterpreterState **interp_p,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100641 const _PyCoreConfig *core_config)
642{
643 PyInterpreterState *interp;
644
Victor Stinner43125222019-04-24 18:23:53 +0200645 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100646
Victor Stinner43125222019-04-24 18:23:53 +0200647 _PyInitError err = pycore_init_runtime(runtime, core_config);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100648 if (_Py_INIT_FAILED(err)) {
649 return err;
650 }
651
Victor Stinner43125222019-04-24 18:23:53 +0200652 err = pycore_create_interpreter(runtime, core_config, &interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100653 if (_Py_INIT_FAILED(err)) {
654 return err;
655 }
656 core_config = &interp->core_config;
657 *interp_p = interp;
658
659 err = pycore_init_types();
660 if (_Py_INIT_FAILED(err)) {
661 return err;
662 }
663
664 PyObject *sysmod;
Victor Stinner43125222019-04-24 18:23:53 +0200665 err = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100666 if (_Py_INIT_FAILED(err)) {
667 return err;
668 }
669
670 err = pycore_init_builtins(interp);
671 if (_Py_INIT_FAILED(err)) {
672 return err;
673 }
674
675 err = pycore_init_import_warnings(interp, sysmod);
676 if (_Py_INIT_FAILED(err)) {
677 return err;
678 }
Eric Snow1abcf672017-05-23 21:46:51 -0700679
680 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200681 runtime->core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800682 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700683}
684
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100685
Victor Stinner70005ac2019-05-02 15:25:34 -0400686_PyInitError
687_Py_PreInitializeFromPyArgv(const _PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100688{
689 _PyInitError err;
690
691 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100692 if (_Py_INIT_FAILED(err)) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100693 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100694 }
Victor Stinner43125222019-04-24 18:23:53 +0200695 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100696
Victor Stinner43125222019-04-24 18:23:53 +0200697 if (runtime->pre_initialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100698 /* If it's already configured: ignored the new configuration */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100699 return _Py_INIT_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100700 }
701
Victor Stinner5ac27a52019-03-27 13:40:14 +0100702 _PyPreConfig config = _PyPreConfig_INIT;
703
Victor Stinnerf72346c2019-03-25 17:54:58 +0100704 if (src_config) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100705 if (_PyPreConfig_Copy(&config, src_config) < 0) {
706 err = _Py_INIT_NO_MEMORY();
Victor Stinner20004952019-03-26 02:31:11 +0100707 goto done;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100708 }
709 }
710
Victor Stinner5ac27a52019-03-27 13:40:14 +0100711 err = _PyPreConfig_Read(&config, args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100712 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100713 goto done;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100714 }
715
Victor Stinner5ac27a52019-03-27 13:40:14 +0100716 err = _PyPreConfig_Write(&config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100717 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100718 goto done;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100719 }
720
Victor Stinner43125222019-04-24 18:23:53 +0200721 runtime->pre_initialized = 1;
Victor Stinner20004952019-03-26 02:31:11 +0100722 err = _Py_INIT_OK();
723
724done:
Victor Stinner5ac27a52019-03-27 13:40:14 +0100725 _PyPreConfig_Clear(&config);
Victor Stinner20004952019-03-26 02:31:11 +0100726 return err;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100727}
728
Victor Stinner70005ac2019-05-02 15:25:34 -0400729
Victor Stinnerf72346c2019-03-25 17:54:58 +0100730_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100731_Py_PreInitializeFromArgs(const _PyPreConfig *src_config, int argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100732{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100733 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400734 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100735}
736
737
738_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100739_Py_PreInitializeFromWideArgs(const _PyPreConfig *src_config, int argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100740{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100741 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400742 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100743}
744
745
746_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100747_Py_PreInitialize(const _PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100748{
Victor Stinner70005ac2019-05-02 15:25:34 -0400749 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100750}
751
752
753_PyInitError
Victor Stinner70005ac2019-05-02 15:25:34 -0400754_Py_PreInitializeFromCoreConfig(const _PyCoreConfig *coreconfig,
755 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100756{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100757 _PyPreConfig config = _PyPreConfig_INIT;
Victor Stinner70005ac2019-05-02 15:25:34 -0400758 if (coreconfig != NULL) {
759 _PyCoreConfig_GetCoreConfig(&config, coreconfig);
760 }
761 return _Py_PreInitializeFromPyArgv(&config, args);
Victor Stinner5ac27a52019-03-27 13:40:14 +0100762 /* No need to clear config:
763 _PyCoreConfig_GetCoreConfig() doesn't allocate memory */
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100764}
765
766
767static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200768pyinit_coreconfig(_PyRuntimeState *runtime,
769 _PyCoreConfig *config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100770 const _PyCoreConfig *src_config,
771 const _PyArgv *args,
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100772 PyInterpreterState **interp_p)
773{
Victor Stinner5f38b842019-05-01 02:30:12 +0200774 _PyInitError err;
775
Victor Stinnerd929f182019-03-27 18:28:46 +0100776 if (src_config) {
Victor Stinner1a9f0d82019-05-01 15:22:52 +0200777 err = _PyCoreConfig_Copy(config, src_config);
778 if (_Py_INIT_FAILED(err)) {
779 return err;
Victor Stinnerd929f182019-03-27 18:28:46 +0100780 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100781 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100782
Victor Stinner5f38b842019-05-01 02:30:12 +0200783 if (args) {
784 err = _PyCoreConfig_SetPyArgv(config, args);
785 if (_Py_INIT_FAILED(err)) {
786 return err;
787 }
788 }
789
790 err = _PyCoreConfig_Read(config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100791 if (_Py_INIT_FAILED(err)) {
792 return err;
793 }
794
Victor Stinner43125222019-04-24 18:23:53 +0200795 if (!runtime->core_initialized) {
796 return _Py_InitializeCore_impl(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100797 }
798 else {
Victor Stinner43125222019-04-24 18:23:53 +0200799 return _Py_Initialize_ReconfigureCore(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100800 }
801}
802
803
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100804/* Begin interpreter initialization
805 *
806 * On return, the first thread and interpreter state have been created,
807 * but the compiler, signal handling, multithreading and
808 * multiple interpreter support, and codec infrastructure are not yet
809 * available.
810 *
811 * The import system will support builtin and frozen modules only.
812 * The only supported io is writing to sys.stderr
813 *
814 * If any operation invoked by this function fails, a fatal error is
815 * issued and the function does not return.
816 *
817 * Any code invoked from this function should *not* assume it has access
818 * to the Python C API (unless the API is explicitly listed as being
819 * safe to call without calling Py_Initialize first)
820 */
Victor Stinner484f20d2019-03-27 02:04:16 +0100821static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200822_Py_InitializeCore(_PyRuntimeState *runtime,
823 const _PyCoreConfig *src_config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100824 const _PyArgv *args,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100825 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200826{
Victor Stinnerd929f182019-03-27 18:28:46 +0100827 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200828
Victor Stinner70005ac2019-05-02 15:25:34 -0400829 err = _Py_PreInitializeFromCoreConfig(src_config, args);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200830 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100831 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200832 }
833
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100834 _PyCoreConfig local_config = _PyCoreConfig_INIT;
Victor Stinner43125222019-04-24 18:23:53 +0200835 err = pyinit_coreconfig(runtime, &local_config, src_config, args, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100836 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200837 return err;
838}
839
Victor Stinner5ac27a52019-03-27 13:40:14 +0100840
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200841/* Py_Initialize() has already been called: update the main interpreter
842 configuration. Example of bpo-34008: Py_Main() called after
843 Py_Initialize(). */
844static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100845_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200846{
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100847 _PyCoreConfig *core_config = &interp->core_config;
848
849 PyObject *argv = _PyWstrList_AsList(&core_config->argv);
850 if (argv == NULL) {
851 return _Py_INIT_NO_MEMORY(); \
852 }
853
854 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
855 Py_DECREF(argv);
856 if (res < 0) {
857 return _Py_INIT_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200858 }
859 return _Py_INIT_OK();
860}
861
Eric Snowc7ec9982017-05-23 23:00:52 -0700862/* Update interpreter state based on supplied configuration settings
863 *
864 * After calling this function, most of the restrictions on the interpreter
865 * are lifted. The only remaining incomplete settings are those related
866 * to the main module (sys.argv[0], __main__ metadata)
867 *
868 * Calling this when the interpreter is not initializing, is already
869 * initialized or without a valid current thread state is a fatal error.
870 * Other errors should be reported as normal Python exceptions with a
871 * non-zero return code.
872 */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100873static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200874_Py_InitializeMainInterpreter(_PyRuntimeState *runtime,
875 PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700876{
Victor Stinner43125222019-04-24 18:23:53 +0200877 if (!runtime->core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800878 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700879 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700880
Victor Stinner1dc6e392018-07-25 02:49:17 +0200881 /* Configure the main interpreter */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200882 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700883
Victor Stinner43125222019-04-24 18:23:53 +0200884 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100885 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200886 }
887
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200888 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700889 /* Special mode for freeze_importlib: run with no import system
890 *
891 * This means anything which needs support from extension modules
892 * or pure Python code in the standard library won't work.
893 */
Victor Stinner43125222019-04-24 18:23:53 +0200894 runtime->initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800895 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700896 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100897
Victor Stinner33c377e2017-12-05 15:12:41 +0100898 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800899 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100900 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200901
Victor Stinner43125222019-04-24 18:23:53 +0200902 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800903 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100904 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800905
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400906 _PyInitError err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800907 if (_Py_INIT_FAILED(err)) {
908 return err;
909 }
Nick Coghland6009512014-11-20 21:39:37 +1000910
911 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200912 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 if (_Py_INIT_FAILED(err)) {
914 return err;
915 }
Nick Coghland6009512014-11-20 21:39:37 +1000916
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400917 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800918 if (_Py_INIT_FAILED(err)) {
919 return err;
920 }
Nick Coghland6009512014-11-20 21:39:37 +1000921
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100922 if (core_config->install_signal_handlers) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400923 err = init_signals();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800924 if (_Py_INIT_FAILED(err)) {
925 return err;
926 }
927 }
Nick Coghland6009512014-11-20 21:39:37 +1000928
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200929 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800930 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200931 }
Nick Coghland6009512014-11-20 21:39:37 +1000932
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800933 err = add_main_module(interp);
934 if (_Py_INIT_FAILED(err)) {
935 return err;
936 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800937
Victor Stinner91106cd2017-12-13 12:29:09 +0100938 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800939 if (_Py_INIT_FAILED(err)) {
940 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800941 }
Nick Coghland6009512014-11-20 21:39:37 +1000942
943 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100944 PyObject *warnoptions = PySys_GetObject("warnoptions");
945 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100946 {
Nick Coghland6009512014-11-20 21:39:37 +1000947 PyObject *warnings_module = PyImport_ImportModule("warnings");
948 if (warnings_module == NULL) {
949 fprintf(stderr, "'import warnings' failed; traceback:\n");
950 PyErr_Print();
951 }
952 Py_XDECREF(warnings_module);
953 }
954
Victor Stinner43125222019-04-24 18:23:53 +0200955 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700956
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200957 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400958 err = init_import_size(); /* Module site */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800959 if (_Py_INIT_FAILED(err)) {
960 return err;
961 }
962 }
Victor Stinnercf215042018-08-29 22:56:06 +0200963
964#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200965 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200966#endif
967
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800968 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000969}
970
Eric Snowc7ec9982017-05-23 23:00:52 -0700971#undef _INIT_DEBUG_PRINT
972
Victor Stinner5ac27a52019-03-27 13:40:14 +0100973static _PyInitError
974init_python(const _PyCoreConfig *config, const _PyArgv *args)
Eric Snow1abcf672017-05-23 21:46:51 -0700975{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800976 _PyInitError err;
Victor Stinner43125222019-04-24 18:23:53 +0200977
978 err = _PyRuntime_Initialize();
979 if (_Py_INIT_FAILED(err)) {
980 return err;
981 }
982 _PyRuntimeState *runtime = &_PyRuntime;
983
984 PyInterpreterState *interp = NULL;
985 err = _Py_InitializeCore(runtime, config, args, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800986 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200987 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800988 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200989 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100990
Victor Stinner4631da12019-05-02 15:30:21 -0400991 if (!config->_frozen) {
Victor Stinner43125222019-04-24 18:23:53 +0200992 err = _Py_InitializeMainInterpreter(runtime, interp);
Victor Stinner484f20d2019-03-27 02:04:16 +0100993 if (_Py_INIT_FAILED(err)) {
994 return err;
995 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800996 }
Victor Stinner484f20d2019-03-27 02:04:16 +0100997
Victor Stinner1dc6e392018-07-25 02:49:17 +0200998 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700999}
1000
1001
Victor Stinner5ac27a52019-03-27 13:40:14 +01001002_PyInitError
1003_Py_InitializeFromArgs(const _PyCoreConfig *config, int argc, char **argv)
1004{
1005 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1006 return init_python(config, &args);
1007}
1008
1009
1010_PyInitError
1011_Py_InitializeFromWideArgs(const _PyCoreConfig *config, int argc, wchar_t **argv)
1012{
1013 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1014 return init_python(config, &args);
1015}
1016
1017
1018_PyInitError
1019_Py_InitializeFromConfig(const _PyCoreConfig *config)
1020{
1021 return init_python(config, NULL);
1022}
1023
1024
Eric Snow1abcf672017-05-23 21:46:51 -07001025void
Nick Coghland6009512014-11-20 21:39:37 +10001026Py_InitializeEx(int install_sigs)
1027{
Victor Stinner43125222019-04-24 18:23:53 +02001028 _PyInitError err;
1029
1030 err = _PyRuntime_Initialize();
1031 if (_Py_INIT_FAILED(err)) {
1032 _Py_ExitInitError(err);
1033 }
1034 _PyRuntimeState *runtime = &_PyRuntime;
1035
1036 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001037 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1038 return;
1039 }
1040
Victor Stinner1dc6e392018-07-25 02:49:17 +02001041 _PyCoreConfig config = _PyCoreConfig_INIT;
1042 config.install_signal_handlers = install_sigs;
1043
Victor Stinner43125222019-04-24 18:23:53 +02001044 err = _Py_InitializeFromConfig(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001045 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001046 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001047 }
Nick Coghland6009512014-11-20 21:39:37 +10001048}
1049
1050void
1051Py_Initialize(void)
1052{
1053 Py_InitializeEx(1);
1054}
1055
1056
1057#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001058extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001059#endif
1060
1061/* Flush stdout and stderr */
1062
1063static int
1064file_is_closed(PyObject *fobj)
1065{
1066 int r;
1067 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1068 if (tmp == NULL) {
1069 PyErr_Clear();
1070 return 0;
1071 }
1072 r = PyObject_IsTrue(tmp);
1073 Py_DECREF(tmp);
1074 if (r < 0)
1075 PyErr_Clear();
1076 return r > 0;
1077}
1078
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001079static int
Nick Coghland6009512014-11-20 21:39:37 +10001080flush_std_files(void)
1081{
1082 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1083 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1084 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001085 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001086
1087 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001088 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001089 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001090 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001091 status = -1;
1092 }
Nick Coghland6009512014-11-20 21:39:37 +10001093 else
1094 Py_DECREF(tmp);
1095 }
1096
1097 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001098 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001099 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001100 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001101 status = -1;
1102 }
Nick Coghland6009512014-11-20 21:39:37 +10001103 else
1104 Py_DECREF(tmp);
1105 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001106
1107 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001108}
1109
1110/* Undo the effect of Py_Initialize().
1111
1112 Beware: if multiple interpreter and/or thread states exist, these
1113 are not wiped out; only the current thread and interpreter state
1114 are deleted. But since everything else is deleted, those other
1115 interpreter and thread states should no longer be used.
1116
1117 (XXX We should do better, e.g. wipe out all interpreters and
1118 threads.)
1119
1120 Locking: as above.
1121
1122*/
1123
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001124int
1125Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001126{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001127 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001128
Victor Stinner8e91c242019-04-24 17:24:01 +02001129 _PyRuntimeState *runtime = &_PyRuntime;
1130 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001131 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001132 }
Nick Coghland6009512014-11-20 21:39:37 +10001133
Eric Snow842a2f02019-03-15 15:47:51 -06001134 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001135 wait_for_thread_shutdown();
1136
Eric Snow842a2f02019-03-15 15:47:51 -06001137 // Make any remaining pending calls.
Eric Snowb75b1a352019-04-12 10:20:10 -06001138 _Py_FinishPendingCalls();
Eric Snow842a2f02019-03-15 15:47:51 -06001139
Victor Stinner8e91c242019-04-24 17:24:01 +02001140 /* Get current thread state and interpreter pointer */
1141 PyThreadState *tstate = _PyThreadState_GET();
1142 PyInterpreterState *interp = tstate->interp;
1143
Nick Coghland6009512014-11-20 21:39:37 +10001144 /* The interpreter is still entirely intact at this point, and the
1145 * exit funcs may be relying on that. In particular, if some thread
1146 * or exit func is still waiting to do an import, the import machinery
1147 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001148 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001149 * Note that Threading.py uses an exit func to do a join on all the
1150 * threads created thru it, so this also protects pending imports in
1151 * the threads created via Threading.
1152 */
Nick Coghland6009512014-11-20 21:39:37 +10001153
Marcel Plch776407f2017-12-20 11:17:58 +01001154 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001155
Victor Stinnerda273412017-12-15 01:46:02 +01001156 /* Copy the core config, PyInterpreterState_Delete() free
1157 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001158#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001159 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001160#endif
1161#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001162 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001163#endif
1164#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001165 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001166#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001167
Nick Coghland6009512014-11-20 21:39:37 +10001168 /* Remaining threads (e.g. daemon threads) will automatically exit
1169 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001170 runtime->finalizing = tstate;
1171 runtime->initialized = 0;
1172 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001173
Victor Stinnere0deff32015-03-24 13:46:18 +01001174 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001175 if (flush_std_files() < 0) {
1176 status = -1;
1177 }
Nick Coghland6009512014-11-20 21:39:37 +10001178
1179 /* Disable signal handling */
1180 PyOS_FiniInterrupts();
1181
1182 /* Collect garbage. This may call finalizers; it's nice to call these
1183 * before all modules are destroyed.
1184 * XXX If a __del__ or weakref callback is triggered here, and tries to
1185 * XXX import a module, bad things can happen, because Python no
1186 * XXX longer believes it's initialized.
1187 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1188 * XXX is easy to provoke that way. I've also seen, e.g.,
1189 * XXX Exception exceptions.ImportError: 'No module named sha'
1190 * XXX in <function callback at 0x008F5718> ignored
1191 * XXX but I'm unclear on exactly how that one happens. In any case,
1192 * XXX I haven't seen a real-life report of either of these.
1193 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001194 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001195#ifdef COUNT_ALLOCS
1196 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1197 each collection might release some types from the type
1198 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001199 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001200 /* nothing */;
1201#endif
Eric Snowdae02762017-09-14 00:35:58 -07001202
Nick Coghland6009512014-11-20 21:39:37 +10001203 /* Destroy all modules */
1204 PyImport_Cleanup();
1205
Victor Stinnere0deff32015-03-24 13:46:18 +01001206 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001207 if (flush_std_files() < 0) {
1208 status = -1;
1209 }
Nick Coghland6009512014-11-20 21:39:37 +10001210
1211 /* Collect final garbage. This disposes of cycles created by
1212 * class definitions, for example.
1213 * XXX This is disabled because it caused too many problems. If
1214 * XXX a __del__ or weakref callback triggers here, Python code has
1215 * XXX a hard time running, because even the sys module has been
1216 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1217 * XXX One symptom is a sequence of information-free messages
1218 * XXX coming from threads (if a __del__ or callback is invoked,
1219 * XXX other threads can execute too, and any exception they encounter
1220 * XXX triggers a comedy of errors as subsystem after subsystem
1221 * XXX fails to find what it *expects* to find in sys to help report
1222 * XXX the exception and consequent unexpected failures). I've also
1223 * XXX seen segfaults then, after adding print statements to the
1224 * XXX Python code getting called.
1225 */
1226#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001227 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001228#endif
1229
1230 /* Disable tracemalloc after all Python objects have been destroyed,
1231 so it is possible to use tracemalloc in objects destructor. */
1232 _PyTraceMalloc_Fini();
1233
1234 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1235 _PyImport_Fini();
1236
1237 /* Cleanup typeobject.c's internal caches. */
1238 _PyType_Fini();
1239
1240 /* unload faulthandler module */
1241 _PyFaulthandler_Fini();
1242
1243 /* Debugging stuff */
1244#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001245 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001246#endif
1247 /* dump hash stats */
1248 _PyHash_Fini();
1249
Eric Snowdae02762017-09-14 00:35:58 -07001250#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001251 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001252 _PyDebug_PrintTotalRefs();
1253 }
Eric Snowdae02762017-09-14 00:35:58 -07001254#endif
Nick Coghland6009512014-11-20 21:39:37 +10001255
1256#ifdef Py_TRACE_REFS
1257 /* Display all objects still alive -- this can invoke arbitrary
1258 * __repr__ overrides, so requires a mostly-intact interpreter.
1259 * Alas, a lot of stuff may still be alive now that will be cleaned
1260 * up later.
1261 */
Victor Stinnerda273412017-12-15 01:46:02 +01001262 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001263 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001264 }
Nick Coghland6009512014-11-20 21:39:37 +10001265#endif /* Py_TRACE_REFS */
1266
1267 /* Clear interpreter state and all thread states. */
1268 PyInterpreterState_Clear(interp);
1269
1270 /* Now we decref the exception classes. After this point nothing
1271 can raise an exception. That's okay, because each Fini() method
1272 below has been checked to make sure no exceptions are ever
1273 raised.
1274 */
1275
1276 _PyExc_Fini();
1277
1278 /* Sundry finalizers */
1279 PyMethod_Fini();
1280 PyFrame_Fini();
1281 PyCFunction_Fini();
1282 PyTuple_Fini();
1283 PyList_Fini();
1284 PySet_Fini();
1285 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001286 PyLong_Fini();
1287 PyFloat_Fini();
1288 PyDict_Fini();
1289 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001290 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001291 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001292 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001293 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001294 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001295 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001296
1297 /* Cleanup Unicode implementation */
1298 _PyUnicode_Fini();
1299
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001300 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001301
1302 /* XXX Still allocated:
1303 - various static ad-hoc pointers to interned strings
1304 - int and float free list blocks
1305 - whatever various modules and libraries allocate
1306 */
1307
1308 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1309
1310 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001311 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001312
1313 /* Delete current thread. After this, many C API calls become crashy. */
1314 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001315
Nick Coghland6009512014-11-20 21:39:37 +10001316 PyInterpreterState_Delete(interp);
1317
1318#ifdef Py_TRACE_REFS
1319 /* Display addresses (& refcnts) of all objects still alive.
1320 * An address can be used to find the repr of the object, printed
1321 * above by _Py_PrintReferences.
1322 */
Victor Stinnerda273412017-12-15 01:46:02 +01001323 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001324 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001325 }
Nick Coghland6009512014-11-20 21:39:37 +10001326#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001327#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001328 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001329 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001330 }
Nick Coghland6009512014-11-20 21:39:37 +10001331#endif
1332
Victor Stinner8e91c242019-04-24 17:24:01 +02001333 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001334
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001335 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001336 return status;
1337}
1338
1339void
1340Py_Finalize(void)
1341{
1342 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001343}
1344
1345/* Create and initialize a new interpreter and thread, and return the
1346 new thread. This requires that Py_Initialize() has been called
1347 first.
1348
1349 Unsuccessful initialization yields a NULL pointer. Note that *no*
1350 exception information is available even in this case -- the
1351 exception information is held in the thread, and there is no
1352 thread.
1353
1354 Locking: as above.
1355
1356*/
1357
Victor Stinnera7368ac2017-11-15 18:11:45 -08001358static _PyInitError
1359new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001360{
Victor Stinner9316ee42017-11-25 03:17:57 +01001361 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001362
Victor Stinner43125222019-04-24 18:23:53 +02001363 err = _PyRuntime_Initialize();
1364 if (_Py_INIT_FAILED(err)) {
1365 return err;
1366 }
1367 _PyRuntimeState *runtime = &_PyRuntime;
1368
1369 if (!runtime->initialized) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001370 return _Py_INIT_ERR("Py_Initialize must be called first");
1371 }
Nick Coghland6009512014-11-20 21:39:37 +10001372
Victor Stinner8a1be612016-03-14 22:07:55 +01001373 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1374 interpreters: disable PyGILState_Check(). */
1375 _PyGILState_check_enabled = 0;
1376
Victor Stinner43125222019-04-24 18:23:53 +02001377 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001378 if (interp == NULL) {
1379 *tstate_p = NULL;
1380 return _Py_INIT_OK();
1381 }
Nick Coghland6009512014-11-20 21:39:37 +10001382
Victor Stinner43125222019-04-24 18:23:53 +02001383 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001384 if (tstate == NULL) {
1385 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001386 *tstate_p = NULL;
1387 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001388 }
1389
Victor Stinner43125222019-04-24 18:23:53 +02001390 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001391
Eric Snow1abcf672017-05-23 21:46:51 -07001392 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001393 _PyCoreConfig *core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001394 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001395 core_config = &save_tstate->interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001396 } else {
1397 /* No current thread state, copy from the main interpreter */
1398 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001399 core_config = &main_interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001400 }
1401
Victor Stinner1a9f0d82019-05-01 15:22:52 +02001402 err = _PyCoreConfig_Copy(&interp->core_config, core_config);
1403 if (_Py_INIT_FAILED(err)) {
1404 return err;
Victor Stinnerda273412017-12-15 01:46:02 +01001405 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001406 core_config = &interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001407
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001408 err = _PyExc_Init();
1409 if (_Py_INIT_FAILED(err)) {
1410 return err;
1411 }
1412
Nick Coghland6009512014-11-20 21:39:37 +10001413 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001414 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001415 if (modules == NULL) {
1416 return _Py_INIT_ERR("can't make modules dictionary");
1417 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001418 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001419
Victor Stinner43125222019-04-24 18:23:53 +02001420 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001421 if (sysmod != NULL) {
1422 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001423 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001424 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001425 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001426 Py_INCREF(interp->sysdict);
1427 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner43125222019-04-24 18:23:53 +02001428 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerab672812019-01-23 15:04:40 +01001429 return _Py_INIT_ERR("can't finish initializing sys");
1430 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001431 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001432 else if (PyErr_Occurred()) {
1433 goto handle_error;
1434 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001435
Victor Stinner43125222019-04-24 18:23:53 +02001436 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001437 if (bimod != NULL) {
1438 interp->builtins = PyModule_GetDict(bimod);
1439 if (interp->builtins == NULL)
1440 goto handle_error;
1441 Py_INCREF(interp->builtins);
1442 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001443 else if (PyErr_Occurred()) {
1444 goto handle_error;
1445 }
Nick Coghland6009512014-11-20 21:39:37 +10001446
Nick Coghland6009512014-11-20 21:39:37 +10001447 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001448 err = _PyBuiltins_AddExceptions(bimod);
1449 if (_Py_INIT_FAILED(err)) {
1450 return err;
1451 }
Nick Coghland6009512014-11-20 21:39:37 +10001452
Victor Stinnerab672812019-01-23 15:04:40 +01001453 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1454 if (_Py_INIT_FAILED(err)) {
1455 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001456 }
Nick Coghland6009512014-11-20 21:39:37 +10001457
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001458 err = _PyImportHooks_Init();
1459 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001460 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001461 }
Nick Coghland6009512014-11-20 21:39:37 +10001462
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001463 err = init_importlib(interp, sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001464 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001465 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001466 }
Nick Coghland6009512014-11-20 21:39:37 +10001467
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001468 err = init_importlib_external(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001469 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001470 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001471 }
Nick Coghland6009512014-11-20 21:39:37 +10001472
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001473 err = _PyUnicode_InitEncodings(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001474 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001475 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001476 }
1477
Victor Stinner91106cd2017-12-13 12:29:09 +01001478 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001479 if (_Py_INIT_FAILED(err)) {
1480 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001481 }
1482
1483 err = add_main_module(interp);
1484 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001485 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001486 }
1487
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001488 if (core_config->site_import) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001489 err = init_import_size();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001490 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001491 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001492 }
1493 }
Nick Coghland6009512014-11-20 21:39:37 +10001494 }
1495
Victor Stinnera7368ac2017-11-15 18:11:45 -08001496 if (PyErr_Occurred()) {
1497 goto handle_error;
1498 }
Nick Coghland6009512014-11-20 21:39:37 +10001499
Victor Stinnera7368ac2017-11-15 18:11:45 -08001500 *tstate_p = tstate;
1501 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001502
Nick Coghland6009512014-11-20 21:39:37 +10001503handle_error:
1504 /* Oops, it didn't work. Undo it all. */
1505
1506 PyErr_PrintEx(0);
1507 PyThreadState_Clear(tstate);
1508 PyThreadState_Swap(save_tstate);
1509 PyThreadState_Delete(tstate);
1510 PyInterpreterState_Delete(interp);
1511
Victor Stinnera7368ac2017-11-15 18:11:45 -08001512 *tstate_p = NULL;
1513 return _Py_INIT_OK();
1514}
1515
1516PyThreadState *
1517Py_NewInterpreter(void)
1518{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001519 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001520 _PyInitError err = new_interpreter(&tstate);
1521 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001522 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001523 }
1524 return tstate;
1525
Nick Coghland6009512014-11-20 21:39:37 +10001526}
1527
1528/* Delete an interpreter and its last thread. This requires that the
1529 given thread state is current, that the thread has no remaining
1530 frames, and that it is its interpreter's only remaining thread.
1531 It is a fatal error to violate these constraints.
1532
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001533 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001534 everything, regardless.)
1535
1536 Locking: as above.
1537
1538*/
1539
1540void
1541Py_EndInterpreter(PyThreadState *tstate)
1542{
1543 PyInterpreterState *interp = tstate->interp;
1544
Victor Stinner50b48572018-11-01 01:51:40 +01001545 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001546 Py_FatalError("Py_EndInterpreter: thread is not current");
1547 if (tstate->frame != NULL)
1548 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001549 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001550
Eric Snow842a2f02019-03-15 15:47:51 -06001551 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001552 wait_for_thread_shutdown();
1553
Marcel Plch776407f2017-12-20 11:17:58 +01001554 call_py_exitfuncs(interp);
1555
Nick Coghland6009512014-11-20 21:39:37 +10001556 if (tstate != interp->tstate_head || tstate->next != NULL)
1557 Py_FatalError("Py_EndInterpreter: not the last thread");
1558
1559 PyImport_Cleanup();
1560 PyInterpreterState_Clear(interp);
1561 PyThreadState_Swap(NULL);
1562 PyInterpreterState_Delete(interp);
1563}
1564
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001565/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001566
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001567static _PyInitError
1568add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001569{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001570 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001571 m = PyImport_AddModule("__main__");
1572 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001573 return _Py_INIT_ERR("can't create __main__ module");
1574
Nick Coghland6009512014-11-20 21:39:37 +10001575 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001576 ann_dict = PyDict_New();
1577 if ((ann_dict == NULL) ||
1578 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001579 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001580 }
1581 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001582
Nick Coghland6009512014-11-20 21:39:37 +10001583 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1584 PyObject *bimod = PyImport_ImportModule("builtins");
1585 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001586 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001587 }
1588 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001589 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001590 }
1591 Py_DECREF(bimod);
1592 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001593
Nick Coghland6009512014-11-20 21:39:37 +10001594 /* Main is a little special - imp.is_builtin("__main__") will return
1595 * False, but BuiltinImporter is still the most appropriate initial
1596 * setting for its __loader__ attribute. A more suitable value will
1597 * be set if __main__ gets further initialized later in the startup
1598 * process.
1599 */
1600 loader = PyDict_GetItemString(d, "__loader__");
1601 if (loader == NULL || loader == Py_None) {
1602 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1603 "BuiltinImporter");
1604 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001605 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001606 }
1607 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001608 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001609 }
1610 Py_DECREF(loader);
1611 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001612 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001613}
1614
Nick Coghland6009512014-11-20 21:39:37 +10001615/* Import the site module (not into __main__ though) */
1616
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001617static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001618init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001619{
1620 PyObject *m;
1621 m = PyImport_ImportModule("site");
1622 if (m == NULL) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001623 return _Py_INIT_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001624 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001625 Py_DECREF(m);
1626 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001627}
1628
Victor Stinner874dbe82015-09-04 17:29:57 +02001629/* Check if a file descriptor is valid or not.
1630 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1631static int
1632is_valid_fd(int fd)
1633{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001634/* dup() is faster than fstat(): fstat() can require input/output operations,
1635 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1636 startup. Problem: dup() doesn't check if the file descriptor is valid on
1637 some platforms.
1638
1639 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1640 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1641 EBADF. FreeBSD has similar issue (bpo-32849).
1642
1643 Only use dup() on platforms where dup() is enough to detect invalid FD in
1644 corner cases: on Linux and Windows (bpo-32849). */
1645#if defined(__linux__) || defined(MS_WINDOWS)
1646 if (fd < 0) {
1647 return 0;
1648 }
1649 int fd2;
1650
1651 _Py_BEGIN_SUPPRESS_IPH
1652 fd2 = dup(fd);
1653 if (fd2 >= 0) {
1654 close(fd2);
1655 }
1656 _Py_END_SUPPRESS_IPH
1657
1658 return (fd2 >= 0);
1659#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001660 struct stat st;
1661 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001662#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001663}
1664
1665/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001666static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001667create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001668 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001669 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001670{
1671 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1672 const char* mode;
1673 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001674 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001675 int buffering, isatty;
1676 _Py_IDENTIFIER(open);
1677 _Py_IDENTIFIER(isatty);
1678 _Py_IDENTIFIER(TextIOWrapper);
1679 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001680 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001681
Victor Stinner874dbe82015-09-04 17:29:57 +02001682 if (!is_valid_fd(fd))
1683 Py_RETURN_NONE;
1684
Nick Coghland6009512014-11-20 21:39:37 +10001685 /* stdin is always opened in buffered mode, first because it shouldn't
1686 make a difference in common use cases, second because TextIOWrapper
1687 depends on the presence of a read1() method which only exists on
1688 buffered streams.
1689 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001690 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001691 buffering = 0;
1692 else
1693 buffering = -1;
1694 if (write_mode)
1695 mode = "wb";
1696 else
1697 mode = "rb";
1698 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1699 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001700 Py_None, Py_None, /* encoding, errors */
1701 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001702 if (buf == NULL)
1703 goto error;
1704
1705 if (buffering) {
1706 _Py_IDENTIFIER(raw);
1707 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1708 if (raw == NULL)
1709 goto error;
1710 }
1711 else {
1712 raw = buf;
1713 Py_INCREF(raw);
1714 }
1715
Steve Dower39294992016-08-30 21:22:36 -07001716#ifdef MS_WINDOWS
1717 /* Windows console IO is always UTF-8 encoded */
1718 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001719 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001720#endif
1721
Nick Coghland6009512014-11-20 21:39:37 +10001722 text = PyUnicode_FromString(name);
1723 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1724 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001725 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001726 if (res == NULL)
1727 goto error;
1728 isatty = PyObject_IsTrue(res);
1729 Py_DECREF(res);
1730 if (isatty == -1)
1731 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001732 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001733 write_through = Py_True;
1734 else
1735 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001736 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001737 line_buffering = Py_True;
1738 else
1739 line_buffering = Py_False;
1740
1741 Py_CLEAR(raw);
1742 Py_CLEAR(text);
1743
1744#ifdef MS_WINDOWS
1745 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1746 newlines to "\n".
1747 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1748 newline = NULL;
1749#else
1750 /* sys.stdin: split lines at "\n".
1751 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1752 newline = "\n";
1753#endif
1754
Victor Stinner709d23d2019-05-02 14:56:30 -04001755 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1756 if (encoding_str == NULL) {
1757 Py_CLEAR(buf);
1758 goto error;
1759 }
1760
1761 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1762 if (errors_str == NULL) {
1763 Py_CLEAR(buf);
1764 Py_CLEAR(encoding_str);
1765 goto error;
1766 }
1767
1768 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1769 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001770 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001771 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001772 Py_CLEAR(encoding_str);
1773 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001774 if (stream == NULL)
1775 goto error;
1776
1777 if (write_mode)
1778 mode = "w";
1779 else
1780 mode = "r";
1781 text = PyUnicode_FromString(mode);
1782 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1783 goto error;
1784 Py_CLEAR(text);
1785 return stream;
1786
1787error:
1788 Py_XDECREF(buf);
1789 Py_XDECREF(stream);
1790 Py_XDECREF(text);
1791 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001792
Victor Stinner874dbe82015-09-04 17:29:57 +02001793 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1794 /* Issue #24891: the file descriptor was closed after the first
1795 is_valid_fd() check was called. Ignore the OSError and set the
1796 stream to None. */
1797 PyErr_Clear();
1798 Py_RETURN_NONE;
1799 }
1800 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001801}
1802
1803/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001804static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001805init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001806{
1807 PyObject *iomod = NULL, *wrapper;
1808 PyObject *bimod = NULL;
1809 PyObject *m;
1810 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001811 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001812 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001813 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001814 _PyCoreConfig *config = &interp->core_config;
1815
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001816 /* Check that stdin is not a directory
1817 Using shell redirection, you can redirect stdin to a directory,
1818 crashing the Python interpreter. Catch this common mistake here
1819 and output a useful error message. Note that under MS Windows,
1820 the shell already prevents that. */
1821#ifndef MS_WINDOWS
1822 struct _Py_stat_struct sb;
1823 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1824 S_ISDIR(sb.st_mode)) {
Victor Stinnerdb719752019-05-01 05:35:33 +02001825 return _Py_INIT_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001826 }
1827#endif
1828
Nick Coghland6009512014-11-20 21:39:37 +10001829 /* Hack to avoid a nasty recursion issue when Python is invoked
1830 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1831 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1832 goto error;
1833 }
1834 Py_DECREF(m);
1835
1836 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1837 goto error;
1838 }
1839 Py_DECREF(m);
1840
1841 if (!(bimod = PyImport_ImportModule("builtins"))) {
1842 goto error;
1843 }
1844
1845 if (!(iomod = PyImport_ImportModule("io"))) {
1846 goto error;
1847 }
1848 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1849 goto error;
1850 }
1851
1852 /* Set builtins.open */
1853 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1854 Py_DECREF(wrapper);
1855 goto error;
1856 }
1857 Py_DECREF(wrapper);
1858
Nick Coghland6009512014-11-20 21:39:37 +10001859 /* Set sys.stdin */
1860 fd = fileno(stdin);
1861 /* Under some conditions stdin, stdout and stderr may not be connected
1862 * and fileno() may point to an invalid file descriptor. For example
1863 * GUI apps don't have valid standard streams by default.
1864 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001865 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001866 config->stdio_encoding,
1867 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001868 if (std == NULL)
1869 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001870 PySys_SetObject("__stdin__", std);
1871 _PySys_SetObjectId(&PyId_stdin, std);
1872 Py_DECREF(std);
1873
1874 /* Set sys.stdout */
1875 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001876 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001877 config->stdio_encoding,
1878 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001879 if (std == NULL)
1880 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001881 PySys_SetObject("__stdout__", std);
1882 _PySys_SetObjectId(&PyId_stdout, std);
1883 Py_DECREF(std);
1884
1885#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1886 /* Set sys.stderr, replaces the preliminary stderr */
1887 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001888 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001889 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001890 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001891 if (std == NULL)
1892 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001893
1894 /* Same as hack above, pre-import stderr's codec to avoid recursion
1895 when import.c tries to write to stderr in verbose mode. */
1896 encoding_attr = PyObject_GetAttrString(std, "encoding");
1897 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001898 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001899 if (std_encoding != NULL) {
1900 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1901 Py_XDECREF(codec_info);
1902 }
1903 Py_DECREF(encoding_attr);
1904 }
1905 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1906
1907 if (PySys_SetObject("__stderr__", std) < 0) {
1908 Py_DECREF(std);
1909 goto error;
1910 }
1911 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1912 Py_DECREF(std);
1913 goto error;
1914 }
1915 Py_DECREF(std);
1916#endif
1917
Victor Stinnera7368ac2017-11-15 18:11:45 -08001918 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001919
Victor Stinnera7368ac2017-11-15 18:11:45 -08001920error:
1921 res = _Py_INIT_ERR("can't initialize sys standard streams");
1922
1923done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001924 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001925
Nick Coghland6009512014-11-20 21:39:37 +10001926 Py_XDECREF(bimod);
1927 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001928 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001929}
1930
1931
Victor Stinner10dc4842015-03-24 12:01:30 +01001932static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001933_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001934{
Victor Stinner10dc4842015-03-24 12:01:30 +01001935 fputc('\n', stderr);
1936 fflush(stderr);
1937
1938 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001939 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001940}
Victor Stinner791da1c2016-03-14 16:53:12 +01001941
1942/* Print the current exception (if an exception is set) with its traceback,
1943 or display the current Python stack.
1944
1945 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1946 called on catastrophic cases.
1947
1948 Return 1 if the traceback was displayed, 0 otherwise. */
1949
1950static int
1951_Py_FatalError_PrintExc(int fd)
1952{
1953 PyObject *ferr, *res;
1954 PyObject *exception, *v, *tb;
1955 int has_tb;
1956
Victor Stinner791da1c2016-03-14 16:53:12 +01001957 PyErr_Fetch(&exception, &v, &tb);
1958 if (exception == NULL) {
1959 /* No current exception */
1960 return 0;
1961 }
1962
1963 ferr = _PySys_GetObjectId(&PyId_stderr);
1964 if (ferr == NULL || ferr == Py_None) {
1965 /* sys.stderr is not set yet or set to None,
1966 no need to try to display the exception */
1967 return 0;
1968 }
1969
1970 PyErr_NormalizeException(&exception, &v, &tb);
1971 if (tb == NULL) {
1972 tb = Py_None;
1973 Py_INCREF(tb);
1974 }
1975 PyException_SetTraceback(v, tb);
1976 if (exception == NULL) {
1977 /* PyErr_NormalizeException() failed */
1978 return 0;
1979 }
1980
1981 has_tb = (tb != Py_None);
1982 PyErr_Display(exception, v, tb);
1983 Py_XDECREF(exception);
1984 Py_XDECREF(v);
1985 Py_XDECREF(tb);
1986
1987 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001988 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001989 if (res == NULL)
1990 PyErr_Clear();
1991 else
1992 Py_DECREF(res);
1993
1994 return has_tb;
1995}
1996
Nick Coghland6009512014-11-20 21:39:37 +10001997/* Print fatal error message and abort */
1998
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001999#ifdef MS_WINDOWS
2000static void
2001fatal_output_debug(const char *msg)
2002{
2003 /* buffer of 256 bytes allocated on the stack */
2004 WCHAR buffer[256 / sizeof(WCHAR)];
2005 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2006 size_t msglen;
2007
2008 OutputDebugStringW(L"Fatal Python error: ");
2009
2010 msglen = strlen(msg);
2011 while (msglen) {
2012 size_t i;
2013
2014 if (buflen > msglen) {
2015 buflen = msglen;
2016 }
2017
2018 /* Convert the message to wchar_t. This uses a simple one-to-one
2019 conversion, assuming that the this error message actually uses
2020 ASCII only. If this ceases to be true, we will have to convert. */
2021 for (i=0; i < buflen; ++i) {
2022 buffer[i] = msg[i];
2023 }
2024 buffer[i] = L'\0';
2025 OutputDebugStringW(buffer);
2026
2027 msg += buflen;
2028 msglen -= buflen;
2029 }
2030 OutputDebugStringW(L"\n");
2031}
2032#endif
2033
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002034static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002035fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002036{
2037 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002038 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002039
2040 if (reentrant) {
2041 /* Py_FatalError() caused a second fatal error.
2042 Example: flush_std_files() raises a recursion error. */
2043 goto exit;
2044 }
2045 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002046
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002047 fprintf(stderr, "Fatal Python error: ");
2048 if (prefix) {
2049 fputs(prefix, stderr);
2050 fputs(": ", stderr);
2051 }
2052 if (msg) {
2053 fputs(msg, stderr);
2054 }
2055 else {
2056 fprintf(stderr, "<message not set>");
2057 }
2058 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002059 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002060
Victor Stinner3a228ab2018-11-01 00:26:41 +01002061 /* Check if the current thread has a Python thread state
2062 and holds the GIL */
2063 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2064 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002065 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002066 if (tss_tstate != tstate) {
2067 /* The Python thread does not hold the GIL */
2068 tss_tstate = NULL;
2069 }
2070 }
2071 else {
2072 /* Py_FatalError() has been called from a C thread
2073 which has no Python thread state. */
2074 }
2075 int has_tstate_and_gil = (tss_tstate != NULL);
2076
2077 if (has_tstate_and_gil) {
2078 /* If an exception is set, print the exception with its traceback */
2079 if (!_Py_FatalError_PrintExc(fd)) {
2080 /* No exception is set, or an exception is set without traceback */
2081 _Py_FatalError_DumpTracebacks(fd);
2082 }
2083 }
2084 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002085 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002086 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002087
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002088 /* The main purpose of faulthandler is to display the traceback.
2089 This function already did its best to display a traceback.
2090 Disable faulthandler to prevent writing a second traceback
2091 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002092 _PyFaulthandler_Fini();
2093
Victor Stinner791da1c2016-03-14 16:53:12 +01002094 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002095 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002096 /* Flush sys.stdout and sys.stderr */
2097 flush_std_files();
2098 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002099
Nick Coghland6009512014-11-20 21:39:37 +10002100#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002101 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002102#endif /* MS_WINDOWS */
2103
2104exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002105 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002106#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002107 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002108#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002109 abort();
2110 }
2111 else {
2112 exit(status);
2113 }
2114}
2115
Victor Stinner19760862017-12-20 01:41:59 +01002116void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002117Py_FatalError(const char *msg)
2118{
2119 fatal_error(NULL, msg, -1);
2120}
2121
Victor Stinner19760862017-12-20 01:41:59 +01002122void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002123_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002124{
Victor Stinnerdb719752019-05-01 05:35:33 +02002125 assert(_Py_INIT_FAILED(err));
2126 if (_Py_INIT_IS_EXIT(err)) {
2127#ifdef MS_WINDOWS
2128 ExitProcess(err.exitcode);
2129#else
Victor Stinnerdfe88472019-03-01 12:14:41 +01002130 exit(err.exitcode);
Victor Stinnerdb719752019-05-01 05:35:33 +02002131#endif
Victor Stinnerdfe88472019-03-01 12:14:41 +01002132 }
2133 else {
Victor Stinnerdb719752019-05-01 05:35:33 +02002134 assert(_Py_INIT_IS_ERROR(err));
2135 fatal_error(err._func, err.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002136 }
Nick Coghland6009512014-11-20 21:39:37 +10002137}
2138
2139/* Clean up and exit */
2140
Victor Stinnerd7292b52016-06-17 12:29:00 +02002141# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002142
Nick Coghland6009512014-11-20 21:39:37 +10002143/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002144void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002145{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002146 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002147
Antoine Pitroufc5db952017-12-13 02:29:07 +01002148 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002149 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2150
2151 is->pyexitfunc = func;
2152 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002153}
2154
2155static void
Marcel Plch776407f2017-12-20 11:17:58 +01002156call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002157{
Marcel Plch776407f2017-12-20 11:17:58 +01002158 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002159 return;
2160
Marcel Plch776407f2017-12-20 11:17:58 +01002161 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002162 PyErr_Clear();
2163}
2164
2165/* Wait until threading._shutdown completes, provided
2166 the threading module was imported in the first place.
2167 The shutdown routine will wait until all non-daemon
2168 "threading" threads have completed. */
2169static void
2170wait_for_thread_shutdown(void)
2171{
Nick Coghland6009512014-11-20 21:39:37 +10002172 _Py_IDENTIFIER(_shutdown);
2173 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002174 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002175 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002176 if (PyErr_Occurred()) {
2177 PyErr_WriteUnraisable(NULL);
2178 }
2179 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002180 return;
2181 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002182 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002183 if (result == NULL) {
2184 PyErr_WriteUnraisable(threading);
2185 }
2186 else {
2187 Py_DECREF(result);
2188 }
2189 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002190}
2191
2192#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002193int Py_AtExit(void (*func)(void))
2194{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002195 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002196 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002197 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002198 return 0;
2199}
2200
2201static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002202call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002203{
Victor Stinner8e91c242019-04-24 17:24:01 +02002204 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002205 /* pop last function from the list */
2206 runtime->nexitfuncs--;
2207 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2208 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2209
2210 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002211 }
Nick Coghland6009512014-11-20 21:39:37 +10002212
2213 fflush(stdout);
2214 fflush(stderr);
2215}
2216
Victor Stinnercfc88312018-08-01 16:41:25 +02002217void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002218Py_Exit(int sts)
2219{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002220 if (Py_FinalizeEx() < 0) {
2221 sts = 120;
2222 }
Nick Coghland6009512014-11-20 21:39:37 +10002223
2224 exit(sts);
2225}
2226
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002227static _PyInitError
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002228init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002229{
2230#ifdef SIGPIPE
2231 PyOS_setsig(SIGPIPE, SIG_IGN);
2232#endif
2233#ifdef SIGXFZ
2234 PyOS_setsig(SIGXFZ, SIG_IGN);
2235#endif
2236#ifdef SIGXFSZ
2237 PyOS_setsig(SIGXFSZ, SIG_IGN);
2238#endif
2239 PyOS_InitInterrupts(); /* May imply initsignal() */
2240 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002241 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002242 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002243 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002244}
2245
2246
2247/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2248 *
2249 * All of the code in this function must only use async-signal-safe functions,
2250 * listed at `man 7 signal` or
2251 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2252 */
2253void
2254_Py_RestoreSignals(void)
2255{
2256#ifdef SIGPIPE
2257 PyOS_setsig(SIGPIPE, SIG_DFL);
2258#endif
2259#ifdef SIGXFZ
2260 PyOS_setsig(SIGXFZ, SIG_DFL);
2261#endif
2262#ifdef SIGXFSZ
2263 PyOS_setsig(SIGXFSZ, SIG_DFL);
2264#endif
2265}
2266
2267
2268/*
2269 * The file descriptor fd is considered ``interactive'' if either
2270 * a) isatty(fd) is TRUE, or
2271 * b) the -i flag was given, and the filename associated with
2272 * the descriptor is NULL or "<stdin>" or "???".
2273 */
2274int
2275Py_FdIsInteractive(FILE *fp, const char *filename)
2276{
2277 if (isatty((int)fileno(fp)))
2278 return 1;
2279 if (!Py_InteractiveFlag)
2280 return 0;
2281 return (filename == NULL) ||
2282 (strcmp(filename, "<stdin>") == 0) ||
2283 (strcmp(filename, "???") == 0);
2284}
2285
2286
Nick Coghland6009512014-11-20 21:39:37 +10002287/* Wrappers around sigaction() or signal(). */
2288
2289PyOS_sighandler_t
2290PyOS_getsig(int sig)
2291{
2292#ifdef HAVE_SIGACTION
2293 struct sigaction context;
2294 if (sigaction(sig, NULL, &context) == -1)
2295 return SIG_ERR;
2296 return context.sa_handler;
2297#else
2298 PyOS_sighandler_t handler;
2299/* Special signal handling for the secure CRT in Visual Studio 2005 */
2300#if defined(_MSC_VER) && _MSC_VER >= 1400
2301 switch (sig) {
2302 /* Only these signals are valid */
2303 case SIGINT:
2304 case SIGILL:
2305 case SIGFPE:
2306 case SIGSEGV:
2307 case SIGTERM:
2308 case SIGBREAK:
2309 case SIGABRT:
2310 break;
2311 /* Don't call signal() with other values or it will assert */
2312 default:
2313 return SIG_ERR;
2314 }
2315#endif /* _MSC_VER && _MSC_VER >= 1400 */
2316 handler = signal(sig, SIG_IGN);
2317 if (handler != SIG_ERR)
2318 signal(sig, handler);
2319 return handler;
2320#endif
2321}
2322
2323/*
2324 * All of the code in this function must only use async-signal-safe functions,
2325 * listed at `man 7 signal` or
2326 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2327 */
2328PyOS_sighandler_t
2329PyOS_setsig(int sig, PyOS_sighandler_t handler)
2330{
2331#ifdef HAVE_SIGACTION
2332 /* Some code in Modules/signalmodule.c depends on sigaction() being
2333 * used here if HAVE_SIGACTION is defined. Fix that if this code
2334 * changes to invalidate that assumption.
2335 */
2336 struct sigaction context, ocontext;
2337 context.sa_handler = handler;
2338 sigemptyset(&context.sa_mask);
2339 context.sa_flags = 0;
2340 if (sigaction(sig, &context, &ocontext) == -1)
2341 return SIG_ERR;
2342 return ocontext.sa_handler;
2343#else
2344 PyOS_sighandler_t oldhandler;
2345 oldhandler = signal(sig, handler);
2346#ifdef HAVE_SIGINTERRUPT
2347 siginterrupt(sig, 1);
2348#endif
2349 return oldhandler;
2350#endif
2351}
2352
2353#ifdef __cplusplus
2354}
2355#endif