blob: ae2d0bf92c6e1f6b4c5956a7fc54bb1b8867154c [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 Stinnerf684d832019-03-01 03:44:13 +01007#include "pycore_coreconfig.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01008#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);
62static _PyInitError initfsencoding(PyInterpreterState *interp);
63static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010064static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080065static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010066static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100067static void wait_for_thread_shutdown(void);
Victor Stinner8e91c242019-04-24 17:24:01 +020068static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100069
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080070int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010072static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075_PyRuntime_Initialize(void)
76{
77 /* XXX We only initialize once in the process, which aligns with
78 the static initialization of the former globals now found in
79 _PyRuntime. However, _PyRuntime *should* be initialized with
80 every Py_Initialize() call, but doing so breaks the runtime.
81 This is because the runtime state is not properly finalized
82 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010083 if (runtime_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084 return _Py_INIT_OK();
85 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010086 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087
88 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
90
91void
92_PyRuntime_Finalize(void)
93{
94 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010095 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
97
98int
99_Py_IsFinalizing(void)
100{
101 return _PyRuntime.finalizing != NULL;
102}
103
Nick Coghland6009512014-11-20 21:39:37 +1000104/* Hack to force loading of object files */
105int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
106 PyOS_mystrnicmp; /* Python/pystrcmp.o */
107
108/* PyModule_GetWarningsModule is no longer necessary as of 2.6
109since _warnings is builtin. This API should not be used. */
110PyObject *
111PyModule_GetWarningsModule(void)
112{
113 return PyImport_ImportModule("warnings");
114}
115
Eric Snowc7ec9982017-05-23 23:00:52 -0700116
Eric Snow1abcf672017-05-23 21:46:51 -0700117/* APIs to access the initialization flags
118 *
119 * Can be called prior to Py_Initialize.
120 */
Nick Coghland6009512014-11-20 21:39:37 +1000121
Eric Snow1abcf672017-05-23 21:46:51 -0700122int
123_Py_IsCoreInitialized(void)
124{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600125 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700126}
Nick Coghland6009512014-11-20 21:39:37 +1000127
128int
129Py_IsInitialized(void)
130{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600131 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000132}
133
Nick Coghlan6ea41862017-06-11 13:16:15 +1000134
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000135/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
136 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000137 initializations fail, a fatal error is issued and the function does
138 not return. On return, the first thread and interpreter state have
139 been created.
140
141 Locking: you must hold the interpreter lock while calling this.
142 (If the lock has not yet been initialized, that's equivalent to
143 having the lock, but you cannot use multiple threads.)
144
145*/
146
Nick Coghland6009512014-11-20 21:39:37 +1000147static char*
148get_codec_name(const char *encoding)
149{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200150 const char *name_utf8;
151 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000152 PyObject *codec, *name = NULL;
153
154 codec = _PyCodec_Lookup(encoding);
155 if (!codec)
156 goto error;
157
158 name = _PyObject_GetAttrId(codec, &PyId_name);
159 Py_CLEAR(codec);
160 if (!name)
161 goto error;
162
Serhiy Storchaka06515832016-11-20 09:13:07 +0200163 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000164 if (name_utf8 == NULL)
165 goto error;
166 name_str = _PyMem_RawStrdup(name_utf8);
167 Py_DECREF(name);
168 if (name_str == NULL) {
169 PyErr_NoMemory();
170 return NULL;
171 }
172 return name_str;
173
174error:
175 Py_XDECREF(codec);
176 Py_XDECREF(name);
177 return NULL;
178}
179
Nick Coghland6009512014-11-20 21:39:37 +1000180
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800181static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700182initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000183{
184 PyObject *importlib;
185 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000186 PyObject *value;
187
188 /* Import _importlib through its frozen version, _frozen_importlib. */
189 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800190 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000191 }
192 else if (Py_VerboseFlag) {
193 PySys_FormatStderr("import _frozen_importlib # frozen\n");
194 }
195 importlib = PyImport_AddModule("_frozen_importlib");
196 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800197 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000198 }
199 interp->importlib = importlib;
200 Py_INCREF(interp->importlib);
201
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300202 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
203 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800204 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300205 Py_INCREF(interp->import_func);
206
Victor Stinnercd6e6942015-09-18 09:11:57 +0200207 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800208 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000209 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800210 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000211 }
212 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200213 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000214 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600215 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800216 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000217 }
218
Victor Stinnercd6e6942015-09-18 09:11:57 +0200219 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000220 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
221 if (value == NULL) {
222 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800223 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000224 }
225 Py_DECREF(value);
226 Py_DECREF(impmod);
227
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800228 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000229}
230
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800231static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700232initexternalimport(PyInterpreterState *interp)
233{
234 PyObject *value;
235 value = PyObject_CallMethod(interp->importlib,
236 "_install_external_importers", "");
237 if (value == NULL) {
238 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800239 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700240 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200241 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300242 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700243}
Nick Coghland6009512014-11-20 21:39:37 +1000244
Nick Coghlan6ea41862017-06-11 13:16:15 +1000245/* Helper functions to better handle the legacy C locale
246 *
247 * The legacy C locale assumes ASCII as the default text encoding, which
248 * causes problems not only for the CPython runtime, but also other
249 * components like GNU readline.
250 *
251 * Accordingly, when the CLI detects it, it attempts to coerce it to a
252 * more capable UTF-8 based alternative as follows:
253 *
254 * if (_Py_LegacyLocaleDetected()) {
255 * _Py_CoerceLegacyLocale();
256 * }
257 *
258 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
259 *
260 * Locale coercion also impacts the default error handler for the standard
261 * streams: while the usual default is "strict", the default for the legacy
262 * C locale and for any of the coercion target locales is "surrogateescape".
263 */
264
265int
266_Py_LegacyLocaleDetected(void)
267{
268#ifndef MS_WINDOWS
269 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000270 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
271 * the POSIX locale as a simple alias for the C locale, so
272 * we may also want to check for that explicitly.
273 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000274 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
275 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
276#else
277 /* Windows uses code pages instead of locales, so no locale is legacy */
278 return 0;
279#endif
280}
281
Nick Coghlaneb817952017-06-18 12:29:42 +1000282static const char *_C_LOCALE_WARNING =
283 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
284 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
285 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
286 "locales is recommended.\n";
287
Nick Coghlaneb817952017-06-18 12:29:42 +1000288static void
Victor Stinner43125222019-04-24 18:23:53 +0200289emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000290{
Victor Stinner43125222019-04-24 18:23:53 +0200291 const _PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner20004952019-03-26 02:31:11 +0100292 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200293 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000294 }
295}
296
Nick Coghlan6ea41862017-06-11 13:16:15 +1000297typedef struct _CandidateLocale {
298 const char *locale_name; /* The locale to try as a coercion target */
299} _LocaleCoercionTarget;
300
301static _LocaleCoercionTarget _TARGET_LOCALES[] = {
302 {"C.UTF-8"},
303 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000304 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305 {NULL}
306};
307
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200308
309int
310_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200312 const _LocaleCoercionTarget *target = NULL;
313 for (target = _TARGET_LOCALES; target->locale_name; target++) {
314 if (strcmp(ctype_loc, target->locale_name) == 0) {
315 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000316 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200317 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200318 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319}
320
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200321
Nick Coghlan6ea41862017-06-11 13:16:15 +1000322#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100323static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000324 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
325 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
326
327static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200328_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000329{
330 const char *newloc = target->locale_name;
331
332 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100333 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000334
335 /* Set the relevant locale environment variable */
336 if (setenv("LC_CTYPE", newloc, 1)) {
337 fprintf(stderr,
338 "Error setting LC_CTYPE, skipping C locale coercion\n");
339 return;
340 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200341 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100342 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000343 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000344
345 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100346 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000347}
348#endif
349
350void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200351_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000352{
353#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200354 char *oldloc = NULL;
355
356 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
357 if (oldloc == NULL) {
358 return;
359 }
360
Victor Stinner94540602017-12-16 04:54:22 +0100361 const char *locale_override = getenv("LC_ALL");
362 if (locale_override == NULL || *locale_override == '\0') {
363 /* LC_ALL is also not set (or is set to an empty string) */
364 const _LocaleCoercionTarget *target = NULL;
365 for (target = _TARGET_LOCALES; target->locale_name; target++) {
366 const char *new_locale = setlocale(LC_CTYPE,
367 target->locale_name);
368 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100369#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100370defined(HAVE_LANGINFO_H) && defined(CODESET)
371 /* Also ensure that nl_langinfo works in this locale */
372 char *codeset = nl_langinfo(CODESET);
373 if (!codeset || *codeset == '\0') {
374 /* CODESET is not set or empty, so skip coercion */
375 new_locale = NULL;
376 _Py_SetLocaleFromEnv(LC_CTYPE);
377 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000378 }
Victor Stinner94540602017-12-16 04:54:22 +0100379#endif
380 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200381 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200382 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000383 }
384 }
385 }
386 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200387
388 setlocale(LC_CTYPE, oldloc);
389
390done:
391 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000392#endif
393}
394
xdegaye1588be62017-11-12 12:45:59 +0100395/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
396 * isolate the idiosyncrasies of different libc implementations. It reads the
397 * appropriate environment variable and uses its value to select the locale for
398 * 'category'. */
399char *
400_Py_SetLocaleFromEnv(int category)
401{
Victor Stinner353933e2018-11-23 13:08:26 +0100402 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100403#ifdef __ANDROID__
404 const char *locale;
405 const char **pvar;
406#ifdef PY_COERCE_C_LOCALE
407 const char *coerce_c_locale;
408#endif
409 const char *utf8_locale = "C.UTF-8";
410 const char *env_var_set[] = {
411 "LC_ALL",
412 "LC_CTYPE",
413 "LANG",
414 NULL,
415 };
416
417 /* Android setlocale(category, "") doesn't check the environment variables
418 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
419 * check the environment variables listed in env_var_set. */
420 for (pvar=env_var_set; *pvar; pvar++) {
421 locale = getenv(*pvar);
422 if (locale != NULL && *locale != '\0') {
423 if (strcmp(locale, utf8_locale) == 0 ||
424 strcmp(locale, "en_US.UTF-8") == 0) {
425 return setlocale(category, utf8_locale);
426 }
427 return setlocale(category, "C");
428 }
429 }
430
431 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
432 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
433 * Quote from POSIX section "8.2 Internationalization Variables":
434 * "4. If the LANG environment variable is not set or is set to the empty
435 * string, the implementation-defined default locale shall be used." */
436
437#ifdef PY_COERCE_C_LOCALE
438 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
439 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
440 /* Some other ported code may check the environment variables (e.g. in
441 * extension modules), so we make sure that they match the locale
442 * configuration */
443 if (setenv("LC_CTYPE", utf8_locale, 1)) {
444 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
445 "environment variable to %s\n", utf8_locale);
446 }
447 }
448#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100449 res = setlocale(category, utf8_locale);
450#else /* !defined(__ANDROID__) */
451 res = setlocale(category, "");
452#endif
453 _Py_ResetForceASCII();
454 return res;
xdegaye1588be62017-11-12 12:45:59 +0100455}
456
Nick Coghlan6ea41862017-06-11 13:16:15 +1000457
Eric Snow1abcf672017-05-23 21:46:51 -0700458/* Global initializations. Can be undone by Py_Finalize(). Don't
459 call this twice without an intervening Py_Finalize() call.
460
Victor Stinner484f20d2019-03-27 02:04:16 +0100461 Every call to _Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700462 must have a corresponding call to Py_Finalize.
463
464 Locking: you must hold the interpreter lock while calling these APIs.
465 (If the lock has not yet been initialized, that's equivalent to
466 having the lock, but you cannot use multiple threads.)
467
468*/
469
Victor Stinner1dc6e392018-07-25 02:49:17 +0200470static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200471_Py_Initialize_ReconfigureCore(_PyRuntimeState *runtime,
472 PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200473 const _PyCoreConfig *core_config)
474{
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100475 PyThreadState *tstate = _PyThreadState_GET();
476 if (!tstate) {
477 return _Py_INIT_ERR("failed to read thread state");
478 }
479
480 PyInterpreterState *interp = tstate->interp;
481 if (interp == NULL) {
482 return _Py_INIT_ERR("can't make main interpreter");
483 }
484 *interp_p = interp;
485
Victor Stinner43125222019-04-24 18:23:53 +0200486 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200487
488 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
Victor Stinnerd929f182019-03-27 18:28:46 +0100489 return _Py_INIT_NO_MEMORY();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200490 }
491 core_config = &interp->core_config;
492
493 if (core_config->_install_importlib) {
494 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
495 if (_Py_INIT_FAILED(err)) {
496 return err;
497 }
498 }
499 return _Py_INIT_OK();
500}
501
502
Victor Stinner1dc6e392018-07-25 02:49:17 +0200503static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200504pycore_init_runtime(_PyRuntimeState *runtime,
505 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000506{
Victor Stinner43125222019-04-24 18:23:53 +0200507 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200508 return _Py_INIT_ERR("main interpreter already initialized");
509 }
Victor Stinnerda273412017-12-15 01:46:02 +0100510
Victor Stinner43125222019-04-24 18:23:53 +0200511 _PyCoreConfig_Write(core_config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600512
Eric Snow1abcf672017-05-23 21:46:51 -0700513 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
514 * threads behave a little more gracefully at interpreter shutdown.
515 * We clobber it here so the new interpreter can start with a clean
516 * slate.
517 *
518 * However, this may still lead to misbehaviour if there are daemon
519 * threads still hanging around from a previous Py_Initialize/Finalize
520 * pair :(
521 */
Victor Stinner43125222019-04-24 18:23:53 +0200522 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600523
Victor Stinner43125222019-04-24 18:23:53 +0200524 _PyInitError err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800525 if (_Py_INIT_FAILED(err)) {
526 return err;
527 }
528
Victor Stinner43125222019-04-24 18:23:53 +0200529 err = _PyInterpreterState_Enable(runtime);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800530 if (_Py_INIT_FAILED(err)) {
531 return err;
532 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100533 return _Py_INIT_OK();
534}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800535
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100536
537static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200538pycore_create_interpreter(_PyRuntimeState *runtime,
539 const _PyCoreConfig *core_config,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100540 PyInterpreterState **interp_p)
541{
542 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100543 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800544 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100545 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200546 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100547
548 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
Victor Stinnerd929f182019-03-27 18:28:46 +0100549 return _Py_INIT_NO_MEMORY();
Victor Stinnerda273412017-12-15 01:46:02 +0100550 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200551 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000552
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200553 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000554 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800555 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000556 (void) PyThreadState_Swap(tstate);
557
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000558 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000559 destroying the GIL might fail when it is being referenced from
560 another running thread (see issue #9901).
561 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000562 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000563 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100564
Nick Coghland6009512014-11-20 21:39:37 +1000565 /* Auto-thread-state API */
Victor Stinner43125222019-04-24 18:23:53 +0200566 _PyGILState_Init(runtime, interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000567
Victor Stinner2914bb32018-01-29 11:57:45 +0100568 /* Create the GIL */
569 PyEval_InitThreads();
570
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100571 return _Py_INIT_OK();
572}
Nick Coghland6009512014-11-20 21:39:37 +1000573
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100574
575static _PyInitError
576pycore_init_types(void)
577{
Victor Stinnerab672812019-01-23 15:04:40 +0100578 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100579 if (_Py_INIT_FAILED(err)) {
580 return err;
581 }
582
583 err = _PyUnicode_Init();
584 if (_Py_INIT_FAILED(err)) {
585 return err;
586 }
587
588 if (_PyStructSequence_Init() < 0) {
589 return _Py_INIT_ERR("can't initialize structseq");
590 }
591
592 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800593 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100594 }
Nick Coghland6009512014-11-20 21:39:37 +1000595
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100596 err = _PyExc_Init();
597 if (_Py_INIT_FAILED(err)) {
598 return err;
599 }
600
601 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800602 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100603 }
Nick Coghland6009512014-11-20 21:39:37 +1000604
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100605 if (!_PyContext_Init()) {
606 return _Py_INIT_ERR("can't init context");
607 }
608 return _Py_INIT_OK();
609}
610
611
612static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100613pycore_init_builtins(PyInterpreterState *interp)
614{
615 PyObject *bimod = _PyBuiltin_Init();
616 if (bimod == NULL) {
617 return _Py_INIT_ERR("can't initialize builtins modules");
618 }
619 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
620
621 interp->builtins = PyModule_GetDict(bimod);
622 if (interp->builtins == NULL) {
623 return _Py_INIT_ERR("can't initialize builtins dict");
624 }
625 Py_INCREF(interp->builtins);
626
627 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
628 if (_Py_INIT_FAILED(err)) {
629 return err;
630 }
631 return _Py_INIT_OK();
632}
633
634
635static _PyInitError
636pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
637{
638 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800639 if (_Py_INIT_FAILED(err)) {
640 return err;
641 }
Nick Coghland6009512014-11-20 21:39:37 +1000642
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800643 err = _PyImportHooks_Init();
644 if (_Py_INIT_FAILED(err)) {
645 return err;
646 }
Nick Coghland6009512014-11-20 21:39:37 +1000647
648 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100649 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100650 return _Py_INIT_ERR("can't initialize warnings");
651 }
Nick Coghland6009512014-11-20 21:39:37 +1000652
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100653 if (interp->core_config._install_importlib) {
654 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200655 if (_Py_INIT_FAILED(err)) {
656 return err;
657 }
658 }
659
Eric Snow1abcf672017-05-23 21:46:51 -0700660 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100661 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800662 err = initimport(interp, sysmod);
663 if (_Py_INIT_FAILED(err)) {
664 return err;
665 }
Eric Snow1abcf672017-05-23 21:46:51 -0700666 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100667 return _Py_INIT_OK();
668}
669
670
671static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200672_Py_InitializeCore_impl(_PyRuntimeState *runtime,
673 PyInterpreterState **interp_p,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100674 const _PyCoreConfig *core_config)
675{
676 PyInterpreterState *interp;
677
Victor Stinner43125222019-04-24 18:23:53 +0200678 _PyCoreConfig_Write(core_config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100679
Victor Stinner43125222019-04-24 18:23:53 +0200680 _PyInitError err = pycore_init_runtime(runtime, core_config);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100681 if (_Py_INIT_FAILED(err)) {
682 return err;
683 }
684
Victor Stinner43125222019-04-24 18:23:53 +0200685 err = pycore_create_interpreter(runtime, core_config, &interp);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100686 if (_Py_INIT_FAILED(err)) {
687 return err;
688 }
689 core_config = &interp->core_config;
690 *interp_p = interp;
691
692 err = pycore_init_types();
693 if (_Py_INIT_FAILED(err)) {
694 return err;
695 }
696
697 PyObject *sysmod;
Victor Stinner43125222019-04-24 18:23:53 +0200698 err = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100699 if (_Py_INIT_FAILED(err)) {
700 return err;
701 }
702
703 err = pycore_init_builtins(interp);
704 if (_Py_INIT_FAILED(err)) {
705 return err;
706 }
707
708 err = pycore_init_import_warnings(interp, sysmod);
709 if (_Py_INIT_FAILED(err)) {
710 return err;
711 }
Eric Snow1abcf672017-05-23 21:46:51 -0700712
713 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200714 runtime->core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800715 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700716}
717
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100718
Victor Stinnerf29084d2019-03-20 02:20:13 +0100719static _PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100720preinit(const _PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100721{
722 _PyInitError err;
723
724 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100725 if (_Py_INIT_FAILED(err)) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100726 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100727 }
Victor Stinner43125222019-04-24 18:23:53 +0200728 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100729
Victor Stinner43125222019-04-24 18:23:53 +0200730 if (runtime->pre_initialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100731 /* If it's already configured: ignored the new configuration */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100732 return _Py_INIT_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100733 }
734
Victor Stinner5ac27a52019-03-27 13:40:14 +0100735 _PyPreConfig config = _PyPreConfig_INIT;
736
Victor Stinnerf72346c2019-03-25 17:54:58 +0100737 if (src_config) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100738 if (_PyPreConfig_Copy(&config, src_config) < 0) {
739 err = _Py_INIT_NO_MEMORY();
Victor Stinner20004952019-03-26 02:31:11 +0100740 goto done;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100741 }
742 }
743
Victor Stinner5ac27a52019-03-27 13:40:14 +0100744 err = _PyPreConfig_Read(&config, args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100745 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100746 goto done;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100747 }
748
Victor Stinner5ac27a52019-03-27 13:40:14 +0100749 err = _PyPreConfig_Write(&config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100750 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100751 goto done;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100752 }
753
Victor Stinner43125222019-04-24 18:23:53 +0200754 runtime->pre_initialized = 1;
Victor Stinner20004952019-03-26 02:31:11 +0100755 err = _Py_INIT_OK();
756
757done:
Victor Stinner5ac27a52019-03-27 13:40:14 +0100758 _PyPreConfig_Clear(&config);
Victor Stinner20004952019-03-26 02:31:11 +0100759 return err;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100760}
761
Victor Stinnerf72346c2019-03-25 17:54:58 +0100762_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100763_Py_PreInitializeFromArgs(const _PyPreConfig *src_config, int argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100764{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100765 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
766 return preinit(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100767}
768
769
770_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100771_Py_PreInitializeFromWideArgs(const _PyPreConfig *src_config, int argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100772{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100773 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
774 return preinit(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100775}
776
777
778_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100779_Py_PreInitialize(const _PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100780{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100781 return preinit(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100782}
783
784
785_PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100786_Py_PreInitializeFromCoreConfig(const _PyCoreConfig *coreconfig)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100787{
Victor Stinnerd929f182019-03-27 18:28:46 +0100788 assert(coreconfig != NULL);
Victor Stinner5ac27a52019-03-27 13:40:14 +0100789 _PyPreConfig config = _PyPreConfig_INIT;
790 _PyCoreConfig_GetCoreConfig(&config, coreconfig);
791 return _Py_PreInitialize(&config);
792 /* No need to clear config:
793 _PyCoreConfig_GetCoreConfig() doesn't allocate memory */
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100794}
795
796
797static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200798pyinit_coreconfig(_PyRuntimeState *runtime,
799 _PyCoreConfig *config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100800 const _PyCoreConfig *src_config,
801 const _PyArgv *args,
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100802 PyInterpreterState **interp_p)
803{
Victor Stinnerd929f182019-03-27 18:28:46 +0100804 if (src_config) {
805 if (_PyCoreConfig_Copy(config, src_config) < 0) {
806 return _Py_INIT_NO_MEMORY();
807 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100808 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100809
Victor Stinner5ac27a52019-03-27 13:40:14 +0100810 _PyInitError err = _PyCoreConfig_Read(config, args);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100811 if (_Py_INIT_FAILED(err)) {
812 return err;
813 }
814
Victor Stinner43125222019-04-24 18:23:53 +0200815 if (!runtime->core_initialized) {
816 return _Py_InitializeCore_impl(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100817 }
818 else {
Victor Stinner43125222019-04-24 18:23:53 +0200819 return _Py_Initialize_ReconfigureCore(runtime, interp_p, config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100820 }
821}
822
823
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100824/* Begin interpreter initialization
825 *
826 * On return, the first thread and interpreter state have been created,
827 * but the compiler, signal handling, multithreading and
828 * multiple interpreter support, and codec infrastructure are not yet
829 * available.
830 *
831 * The import system will support builtin and frozen modules only.
832 * The only supported io is writing to sys.stderr
833 *
834 * If any operation invoked by this function fails, a fatal error is
835 * issued and the function does not return.
836 *
837 * Any code invoked from this function should *not* assume it has access
838 * to the Python C API (unless the API is explicitly listed as being
839 * safe to call without calling Py_Initialize first)
840 */
Victor Stinner484f20d2019-03-27 02:04:16 +0100841static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200842_Py_InitializeCore(_PyRuntimeState *runtime,
843 const _PyCoreConfig *src_config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100844 const _PyArgv *args,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100845 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200846{
Victor Stinnerd929f182019-03-27 18:28:46 +0100847 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200848
Victor Stinnerd929f182019-03-27 18:28:46 +0100849 if (src_config) {
850 err = _Py_PreInitializeFromCoreConfig(src_config);
851 }
852 else {
853 err = _Py_PreInitialize(NULL);
854 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200855 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100856 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200857 }
858
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100859 _PyCoreConfig local_config = _PyCoreConfig_INIT;
Victor Stinner43125222019-04-24 18:23:53 +0200860 err = pyinit_coreconfig(runtime, &local_config, src_config, args, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100861 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200862 return err;
863}
864
Victor Stinner5ac27a52019-03-27 13:40:14 +0100865
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200866/* Py_Initialize() has already been called: update the main interpreter
867 configuration. Example of bpo-34008: Py_Main() called after
868 Py_Initialize(). */
869static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100870_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200871{
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100872 _PyCoreConfig *core_config = &interp->core_config;
873
874 PyObject *argv = _PyWstrList_AsList(&core_config->argv);
875 if (argv == NULL) {
876 return _Py_INIT_NO_MEMORY(); \
877 }
878
879 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
880 Py_DECREF(argv);
881 if (res < 0) {
882 return _Py_INIT_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200883 }
884 return _Py_INIT_OK();
885}
886
Eric Snowc7ec9982017-05-23 23:00:52 -0700887/* Update interpreter state based on supplied configuration settings
888 *
889 * After calling this function, most of the restrictions on the interpreter
890 * are lifted. The only remaining incomplete settings are those related
891 * to the main module (sys.argv[0], __main__ metadata)
892 *
893 * Calling this when the interpreter is not initializing, is already
894 * initialized or without a valid current thread state is a fatal error.
895 * Other errors should be reported as normal Python exceptions with a
896 * non-zero return code.
897 */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100898static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +0200899_Py_InitializeMainInterpreter(_PyRuntimeState *runtime,
900 PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700901{
Victor Stinner43125222019-04-24 18:23:53 +0200902 if (!runtime->core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800903 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700904 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700905
Victor Stinner1dc6e392018-07-25 02:49:17 +0200906 /* Configure the main interpreter */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200907 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700908
Victor Stinner43125222019-04-24 18:23:53 +0200909 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100910 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200911 }
912
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200913 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700914 /* Special mode for freeze_importlib: run with no import system
915 *
916 * This means anything which needs support from extension modules
917 * or pure Python code in the standard library won't work.
918 */
Victor Stinner43125222019-04-24 18:23:53 +0200919 runtime->initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800920 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700921 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100922
Victor Stinner33c377e2017-12-05 15:12:41 +0100923 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800924 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100925 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200926
Victor Stinner43125222019-04-24 18:23:53 +0200927 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800928 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100929 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800930
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200931 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800932 if (_Py_INIT_FAILED(err)) {
933 return err;
934 }
Nick Coghland6009512014-11-20 21:39:37 +1000935
936 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200937 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800938 if (_Py_INIT_FAILED(err)) {
939 return err;
940 }
Nick Coghland6009512014-11-20 21:39:37 +1000941
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800942 err = initfsencoding(interp);
943 if (_Py_INIT_FAILED(err)) {
944 return err;
945 }
Nick Coghland6009512014-11-20 21:39:37 +1000946
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100947 if (core_config->install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800948 err = initsigs(); /* Signal handling stuff, including initintr() */
949 if (_Py_INIT_FAILED(err)) {
950 return err;
951 }
952 }
Nick Coghland6009512014-11-20 21:39:37 +1000953
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200954 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800955 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200956 }
Nick Coghland6009512014-11-20 21:39:37 +1000957
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800958 err = add_main_module(interp);
959 if (_Py_INIT_FAILED(err)) {
960 return err;
961 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800962
Victor Stinner91106cd2017-12-13 12:29:09 +0100963 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800964 if (_Py_INIT_FAILED(err)) {
965 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800966 }
Nick Coghland6009512014-11-20 21:39:37 +1000967
968 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100969 PyObject *warnoptions = PySys_GetObject("warnoptions");
970 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100971 {
Nick Coghland6009512014-11-20 21:39:37 +1000972 PyObject *warnings_module = PyImport_ImportModule("warnings");
973 if (warnings_module == NULL) {
974 fprintf(stderr, "'import warnings' failed; traceback:\n");
975 PyErr_Print();
976 }
977 Py_XDECREF(warnings_module);
978 }
979
Victor Stinner43125222019-04-24 18:23:53 +0200980 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700981
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200982 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800983 err = initsite(); /* Module site */
984 if (_Py_INIT_FAILED(err)) {
985 return err;
986 }
987 }
Victor Stinnercf215042018-08-29 22:56:06 +0200988
989#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200990 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200991#endif
992
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800993 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000994}
995
Eric Snowc7ec9982017-05-23 23:00:52 -0700996#undef _INIT_DEBUG_PRINT
997
Victor Stinner5ac27a52019-03-27 13:40:14 +0100998static _PyInitError
999init_python(const _PyCoreConfig *config, const _PyArgv *args)
Eric Snow1abcf672017-05-23 21:46:51 -07001000{
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001001 _PyInitError err;
Victor Stinner43125222019-04-24 18:23:53 +02001002
1003 err = _PyRuntime_Initialize();
1004 if (_Py_INIT_FAILED(err)) {
1005 return err;
1006 }
1007 _PyRuntimeState *runtime = &_PyRuntime;
1008
1009 PyInterpreterState *interp = NULL;
1010 err = _Py_InitializeCore(runtime, config, args, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001011 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001012 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001013 }
Victor Stinner1dc6e392018-07-25 02:49:17 +02001014 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001015
Victor Stinner484f20d2019-03-27 02:04:16 +01001016 if (config->_init_main) {
Victor Stinner43125222019-04-24 18:23:53 +02001017 err = _Py_InitializeMainInterpreter(runtime, interp);
Victor Stinner484f20d2019-03-27 02:04:16 +01001018 if (_Py_INIT_FAILED(err)) {
1019 return err;
1020 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001021 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001022
Victor Stinner1dc6e392018-07-25 02:49:17 +02001023 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001024}
1025
1026
Victor Stinner5ac27a52019-03-27 13:40:14 +01001027_PyInitError
1028_Py_InitializeFromArgs(const _PyCoreConfig *config, int argc, char **argv)
1029{
1030 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1031 return init_python(config, &args);
1032}
1033
1034
1035_PyInitError
1036_Py_InitializeFromWideArgs(const _PyCoreConfig *config, int argc, wchar_t **argv)
1037{
1038 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1039 return init_python(config, &args);
1040}
1041
1042
1043_PyInitError
1044_Py_InitializeFromConfig(const _PyCoreConfig *config)
1045{
1046 return init_python(config, NULL);
1047}
1048
1049
Eric Snow1abcf672017-05-23 21:46:51 -07001050void
Nick Coghland6009512014-11-20 21:39:37 +10001051Py_InitializeEx(int install_sigs)
1052{
Victor Stinner43125222019-04-24 18:23:53 +02001053 _PyInitError err;
1054
1055 err = _PyRuntime_Initialize();
1056 if (_Py_INIT_FAILED(err)) {
1057 _Py_ExitInitError(err);
1058 }
1059 _PyRuntimeState *runtime = &_PyRuntime;
1060
1061 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001062 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1063 return;
1064 }
1065
Victor Stinner1dc6e392018-07-25 02:49:17 +02001066 _PyCoreConfig config = _PyCoreConfig_INIT;
1067 config.install_signal_handlers = install_sigs;
1068
Victor Stinner43125222019-04-24 18:23:53 +02001069 err = _Py_InitializeFromConfig(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001070 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001071 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001072 }
Nick Coghland6009512014-11-20 21:39:37 +10001073}
1074
1075void
1076Py_Initialize(void)
1077{
1078 Py_InitializeEx(1);
1079}
1080
1081
1082#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001083extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001084#endif
1085
1086/* Flush stdout and stderr */
1087
1088static int
1089file_is_closed(PyObject *fobj)
1090{
1091 int r;
1092 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1093 if (tmp == NULL) {
1094 PyErr_Clear();
1095 return 0;
1096 }
1097 r = PyObject_IsTrue(tmp);
1098 Py_DECREF(tmp);
1099 if (r < 0)
1100 PyErr_Clear();
1101 return r > 0;
1102}
1103
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001104static int
Nick Coghland6009512014-11-20 21:39:37 +10001105flush_std_files(void)
1106{
1107 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1108 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1109 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001110 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001111
1112 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001113 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001114 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001115 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001116 status = -1;
1117 }
Nick Coghland6009512014-11-20 21:39:37 +10001118 else
1119 Py_DECREF(tmp);
1120 }
1121
1122 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001123 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001124 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001125 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001126 status = -1;
1127 }
Nick Coghland6009512014-11-20 21:39:37 +10001128 else
1129 Py_DECREF(tmp);
1130 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001131
1132 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001133}
1134
1135/* Undo the effect of Py_Initialize().
1136
1137 Beware: if multiple interpreter and/or thread states exist, these
1138 are not wiped out; only the current thread and interpreter state
1139 are deleted. But since everything else is deleted, those other
1140 interpreter and thread states should no longer be used.
1141
1142 (XXX We should do better, e.g. wipe out all interpreters and
1143 threads.)
1144
1145 Locking: as above.
1146
1147*/
1148
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001149int
1150Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001151{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001152 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001153
Victor Stinner8e91c242019-04-24 17:24:01 +02001154 _PyRuntimeState *runtime = &_PyRuntime;
1155 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001156 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001157 }
Nick Coghland6009512014-11-20 21:39:37 +10001158
Eric Snow842a2f02019-03-15 15:47:51 -06001159 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001160 wait_for_thread_shutdown();
1161
Eric Snow842a2f02019-03-15 15:47:51 -06001162 // Make any remaining pending calls.
Eric Snowb75b1a352019-04-12 10:20:10 -06001163 _Py_FinishPendingCalls();
Eric Snow842a2f02019-03-15 15:47:51 -06001164
Victor Stinner8e91c242019-04-24 17:24:01 +02001165 /* Get current thread state and interpreter pointer */
1166 PyThreadState *tstate = _PyThreadState_GET();
1167 PyInterpreterState *interp = tstate->interp;
1168
Nick Coghland6009512014-11-20 21:39:37 +10001169 /* The interpreter is still entirely intact at this point, and the
1170 * exit funcs may be relying on that. In particular, if some thread
1171 * or exit func is still waiting to do an import, the import machinery
1172 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001173 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001174 * Note that Threading.py uses an exit func to do a join on all the
1175 * threads created thru it, so this also protects pending imports in
1176 * the threads created via Threading.
1177 */
Nick Coghland6009512014-11-20 21:39:37 +10001178
Marcel Plch776407f2017-12-20 11:17:58 +01001179 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001180
Victor Stinnerda273412017-12-15 01:46:02 +01001181 /* Copy the core config, PyInterpreterState_Delete() free
1182 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001183#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001184 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001185#endif
1186#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001187 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001188#endif
1189#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001190 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001191#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001192
Nick Coghland6009512014-11-20 21:39:37 +10001193 /* Remaining threads (e.g. daemon threads) will automatically exit
1194 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001195 runtime->finalizing = tstate;
1196 runtime->initialized = 0;
1197 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001198
Victor Stinnere0deff32015-03-24 13:46:18 +01001199 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001200 if (flush_std_files() < 0) {
1201 status = -1;
1202 }
Nick Coghland6009512014-11-20 21:39:37 +10001203
1204 /* Disable signal handling */
1205 PyOS_FiniInterrupts();
1206
1207 /* Collect garbage. This may call finalizers; it's nice to call these
1208 * before all modules are destroyed.
1209 * XXX If a __del__ or weakref callback is triggered here, and tries to
1210 * XXX import a module, bad things can happen, because Python no
1211 * XXX longer believes it's initialized.
1212 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1213 * XXX is easy to provoke that way. I've also seen, e.g.,
1214 * XXX Exception exceptions.ImportError: 'No module named sha'
1215 * XXX in <function callback at 0x008F5718> ignored
1216 * XXX but I'm unclear on exactly how that one happens. In any case,
1217 * XXX I haven't seen a real-life report of either of these.
1218 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001219 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001220#ifdef COUNT_ALLOCS
1221 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1222 each collection might release some types from the type
1223 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001224 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001225 /* nothing */;
1226#endif
Eric Snowdae02762017-09-14 00:35:58 -07001227
Nick Coghland6009512014-11-20 21:39:37 +10001228 /* Destroy all modules */
1229 PyImport_Cleanup();
1230
Victor Stinnere0deff32015-03-24 13:46:18 +01001231 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001232 if (flush_std_files() < 0) {
1233 status = -1;
1234 }
Nick Coghland6009512014-11-20 21:39:37 +10001235
1236 /* Collect final garbage. This disposes of cycles created by
1237 * class definitions, for example.
1238 * XXX This is disabled because it caused too many problems. If
1239 * XXX a __del__ or weakref callback triggers here, Python code has
1240 * XXX a hard time running, because even the sys module has been
1241 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1242 * XXX One symptom is a sequence of information-free messages
1243 * XXX coming from threads (if a __del__ or callback is invoked,
1244 * XXX other threads can execute too, and any exception they encounter
1245 * XXX triggers a comedy of errors as subsystem after subsystem
1246 * XXX fails to find what it *expects* to find in sys to help report
1247 * XXX the exception and consequent unexpected failures). I've also
1248 * XXX seen segfaults then, after adding print statements to the
1249 * XXX Python code getting called.
1250 */
1251#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001252 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001253#endif
1254
1255 /* Disable tracemalloc after all Python objects have been destroyed,
1256 so it is possible to use tracemalloc in objects destructor. */
1257 _PyTraceMalloc_Fini();
1258
1259 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1260 _PyImport_Fini();
1261
1262 /* Cleanup typeobject.c's internal caches. */
1263 _PyType_Fini();
1264
1265 /* unload faulthandler module */
1266 _PyFaulthandler_Fini();
1267
1268 /* Debugging stuff */
1269#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001270 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001271#endif
1272 /* dump hash stats */
1273 _PyHash_Fini();
1274
Eric Snowdae02762017-09-14 00:35:58 -07001275#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001276 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001277 _PyDebug_PrintTotalRefs();
1278 }
Eric Snowdae02762017-09-14 00:35:58 -07001279#endif
Nick Coghland6009512014-11-20 21:39:37 +10001280
1281#ifdef Py_TRACE_REFS
1282 /* Display all objects still alive -- this can invoke arbitrary
1283 * __repr__ overrides, so requires a mostly-intact interpreter.
1284 * Alas, a lot of stuff may still be alive now that will be cleaned
1285 * up later.
1286 */
Victor Stinnerda273412017-12-15 01:46:02 +01001287 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001288 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001289 }
Nick Coghland6009512014-11-20 21:39:37 +10001290#endif /* Py_TRACE_REFS */
1291
1292 /* Clear interpreter state and all thread states. */
1293 PyInterpreterState_Clear(interp);
1294
1295 /* Now we decref the exception classes. After this point nothing
1296 can raise an exception. That's okay, because each Fini() method
1297 below has been checked to make sure no exceptions are ever
1298 raised.
1299 */
1300
1301 _PyExc_Fini();
1302
1303 /* Sundry finalizers */
1304 PyMethod_Fini();
1305 PyFrame_Fini();
1306 PyCFunction_Fini();
1307 PyTuple_Fini();
1308 PyList_Fini();
1309 PySet_Fini();
1310 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001311 PyLong_Fini();
1312 PyFloat_Fini();
1313 PyDict_Fini();
1314 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001315 _PyGC_Fini(runtime);
Victor Stinner87d23a02019-04-26 05:49:26 +02001316 _PyWarnings_Fini(runtime);
Eric Snow6b4be192017-05-22 21:36:03 -07001317 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001318 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001319 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001320 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001321
1322 /* Cleanup Unicode implementation */
1323 _PyUnicode_Fini();
1324
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001325 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001326
1327 /* XXX Still allocated:
1328 - various static ad-hoc pointers to interned strings
1329 - int and float free list blocks
1330 - whatever various modules and libraries allocate
1331 */
1332
1333 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1334
1335 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001336 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001337
1338 /* Delete current thread. After this, many C API calls become crashy. */
1339 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001340
Nick Coghland6009512014-11-20 21:39:37 +10001341 PyInterpreterState_Delete(interp);
1342
1343#ifdef Py_TRACE_REFS
1344 /* Display addresses (& refcnts) of all objects still alive.
1345 * An address can be used to find the repr of the object, printed
1346 * above by _Py_PrintReferences.
1347 */
Victor Stinnerda273412017-12-15 01:46:02 +01001348 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001349 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001350 }
Nick Coghland6009512014-11-20 21:39:37 +10001351#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001352#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001353 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001354 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001355 }
Nick Coghland6009512014-11-20 21:39:37 +10001356#endif
1357
Victor Stinner8e91c242019-04-24 17:24:01 +02001358 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001359
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001360 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001361 return status;
1362}
1363
1364void
1365Py_Finalize(void)
1366{
1367 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001368}
1369
1370/* Create and initialize a new interpreter and thread, and return the
1371 new thread. This requires that Py_Initialize() has been called
1372 first.
1373
1374 Unsuccessful initialization yields a NULL pointer. Note that *no*
1375 exception information is available even in this case -- the
1376 exception information is held in the thread, and there is no
1377 thread.
1378
1379 Locking: as above.
1380
1381*/
1382
Victor Stinnera7368ac2017-11-15 18:11:45 -08001383static _PyInitError
1384new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001385{
Victor Stinner9316ee42017-11-25 03:17:57 +01001386 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001387
Victor Stinner43125222019-04-24 18:23:53 +02001388 err = _PyRuntime_Initialize();
1389 if (_Py_INIT_FAILED(err)) {
1390 return err;
1391 }
1392 _PyRuntimeState *runtime = &_PyRuntime;
1393
1394 if (!runtime->initialized) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001395 return _Py_INIT_ERR("Py_Initialize must be called first");
1396 }
Nick Coghland6009512014-11-20 21:39:37 +10001397
Victor Stinner8a1be612016-03-14 22:07:55 +01001398 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1399 interpreters: disable PyGILState_Check(). */
1400 _PyGILState_check_enabled = 0;
1401
Victor Stinner43125222019-04-24 18:23:53 +02001402 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001403 if (interp == NULL) {
1404 *tstate_p = NULL;
1405 return _Py_INIT_OK();
1406 }
Nick Coghland6009512014-11-20 21:39:37 +10001407
Victor Stinner43125222019-04-24 18:23:53 +02001408 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001409 if (tstate == NULL) {
1410 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001411 *tstate_p = NULL;
1412 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001413 }
1414
Victor Stinner43125222019-04-24 18:23:53 +02001415 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001416
Eric Snow1abcf672017-05-23 21:46:51 -07001417 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001418 _PyCoreConfig *core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001419 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001420 core_config = &save_tstate->interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001421 } else {
1422 /* No current thread state, copy from the main interpreter */
1423 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001424 core_config = &main_interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001425 }
1426
1427 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
Victor Stinnerd929f182019-03-27 18:28:46 +01001428 return _Py_INIT_NO_MEMORY();
Victor Stinnerda273412017-12-15 01:46:02 +01001429 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001430 core_config = &interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001431
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001432 err = _PyExc_Init();
1433 if (_Py_INIT_FAILED(err)) {
1434 return err;
1435 }
1436
Nick Coghland6009512014-11-20 21:39:37 +10001437 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001438 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001439 if (modules == NULL) {
1440 return _Py_INIT_ERR("can't make modules dictionary");
1441 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001442 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001443
Victor Stinner43125222019-04-24 18:23:53 +02001444 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
Eric Snowd393c1b2017-09-14 12:18:12 -06001445 if (sysmod != NULL) {
1446 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001447 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001448 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001449 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001450 Py_INCREF(interp->sysdict);
1451 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner43125222019-04-24 18:23:53 +02001452 if (_PySys_InitMain(runtime, interp) < 0) {
Victor Stinnerab672812019-01-23 15:04:40 +01001453 return _Py_INIT_ERR("can't finish initializing sys");
1454 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001455 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001456 else if (PyErr_Occurred()) {
1457 goto handle_error;
1458 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001459
Victor Stinner43125222019-04-24 18:23:53 +02001460 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001461 if (bimod != NULL) {
1462 interp->builtins = PyModule_GetDict(bimod);
1463 if (interp->builtins == NULL)
1464 goto handle_error;
1465 Py_INCREF(interp->builtins);
1466 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001467 else if (PyErr_Occurred()) {
1468 goto handle_error;
1469 }
Nick Coghland6009512014-11-20 21:39:37 +10001470
Nick Coghland6009512014-11-20 21:39:37 +10001471 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001472 err = _PyBuiltins_AddExceptions(bimod);
1473 if (_Py_INIT_FAILED(err)) {
1474 return err;
1475 }
Nick Coghland6009512014-11-20 21:39:37 +10001476
Victor Stinnerab672812019-01-23 15:04:40 +01001477 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1478 if (_Py_INIT_FAILED(err)) {
1479 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001480 }
Nick Coghland6009512014-11-20 21:39:37 +10001481
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001482 err = _PyImportHooks_Init();
1483 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001484 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001485 }
Nick Coghland6009512014-11-20 21:39:37 +10001486
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001487 err = initimport(interp, sysmod);
1488 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001489 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001490 }
Nick Coghland6009512014-11-20 21:39:37 +10001491
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001492 err = initexternalimport(interp);
1493 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001494 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001495 }
Nick Coghland6009512014-11-20 21:39:37 +10001496
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001497 err = initfsencoding(interp);
1498 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001499 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001500 }
1501
Victor Stinner91106cd2017-12-13 12:29:09 +01001502 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001503 if (_Py_INIT_FAILED(err)) {
1504 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001505 }
1506
1507 err = add_main_module(interp);
1508 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001509 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001510 }
1511
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001512 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001513 err = initsite();
1514 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001515 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001516 }
1517 }
Nick Coghland6009512014-11-20 21:39:37 +10001518 }
1519
Victor Stinnera7368ac2017-11-15 18:11:45 -08001520 if (PyErr_Occurred()) {
1521 goto handle_error;
1522 }
Nick Coghland6009512014-11-20 21:39:37 +10001523
Victor Stinnera7368ac2017-11-15 18:11:45 -08001524 *tstate_p = tstate;
1525 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001526
Nick Coghland6009512014-11-20 21:39:37 +10001527handle_error:
1528 /* Oops, it didn't work. Undo it all. */
1529
1530 PyErr_PrintEx(0);
1531 PyThreadState_Clear(tstate);
1532 PyThreadState_Swap(save_tstate);
1533 PyThreadState_Delete(tstate);
1534 PyInterpreterState_Delete(interp);
1535
Victor Stinnera7368ac2017-11-15 18:11:45 -08001536 *tstate_p = NULL;
1537 return _Py_INIT_OK();
1538}
1539
1540PyThreadState *
1541Py_NewInterpreter(void)
1542{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001543 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001544 _PyInitError err = new_interpreter(&tstate);
1545 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001546 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001547 }
1548 return tstate;
1549
Nick Coghland6009512014-11-20 21:39:37 +10001550}
1551
1552/* Delete an interpreter and its last thread. This requires that the
1553 given thread state is current, that the thread has no remaining
1554 frames, and that it is its interpreter's only remaining thread.
1555 It is a fatal error to violate these constraints.
1556
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001557 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001558 everything, regardless.)
1559
1560 Locking: as above.
1561
1562*/
1563
1564void
1565Py_EndInterpreter(PyThreadState *tstate)
1566{
1567 PyInterpreterState *interp = tstate->interp;
1568
Victor Stinner50b48572018-11-01 01:51:40 +01001569 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001570 Py_FatalError("Py_EndInterpreter: thread is not current");
1571 if (tstate->frame != NULL)
1572 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001573 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001574
Eric Snow842a2f02019-03-15 15:47:51 -06001575 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001576 wait_for_thread_shutdown();
1577
Marcel Plch776407f2017-12-20 11:17:58 +01001578 call_py_exitfuncs(interp);
1579
Nick Coghland6009512014-11-20 21:39:37 +10001580 if (tstate != interp->tstate_head || tstate->next != NULL)
1581 Py_FatalError("Py_EndInterpreter: not the last thread");
1582
1583 PyImport_Cleanup();
1584 PyInterpreterState_Clear(interp);
1585 PyThreadState_Swap(NULL);
1586 PyInterpreterState_Delete(interp);
1587}
1588
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001589/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001590
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001591static _PyInitError
1592add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001593{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001594 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001595 m = PyImport_AddModule("__main__");
1596 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001597 return _Py_INIT_ERR("can't create __main__ module");
1598
Nick Coghland6009512014-11-20 21:39:37 +10001599 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001600 ann_dict = PyDict_New();
1601 if ((ann_dict == NULL) ||
1602 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001603 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001604 }
1605 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001606
Nick Coghland6009512014-11-20 21:39:37 +10001607 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1608 PyObject *bimod = PyImport_ImportModule("builtins");
1609 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001610 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001611 }
1612 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001613 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001614 }
1615 Py_DECREF(bimod);
1616 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001617
Nick Coghland6009512014-11-20 21:39:37 +10001618 /* Main is a little special - imp.is_builtin("__main__") will return
1619 * False, but BuiltinImporter is still the most appropriate initial
1620 * setting for its __loader__ attribute. A more suitable value will
1621 * be set if __main__ gets further initialized later in the startup
1622 * process.
1623 */
1624 loader = PyDict_GetItemString(d, "__loader__");
1625 if (loader == NULL || loader == Py_None) {
1626 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1627 "BuiltinImporter");
1628 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001629 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001630 }
1631 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001632 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001633 }
1634 Py_DECREF(loader);
1635 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001636 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001637}
1638
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001639static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001640initfsencoding(PyInterpreterState *interp)
1641{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001642 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001643
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001644 char *encoding = get_codec_name(config->filesystem_encoding);
1645 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001646 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001647 memory, import a module of the standard library failed, etc. */
1648 return _Py_INIT_ERR("failed to get the Python codec "
1649 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001650 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001651
1652 /* Update the filesystem encoding to the normalized Python codec name.
1653 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1654 (Python codec name). */
1655 PyMem_RawFree(config->filesystem_encoding);
1656 config->filesystem_encoding = encoding;
1657
1658 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1659 global configuration variables. */
1660 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1661 config->filesystem_errors) < 0) {
1662 return _Py_INIT_NO_MEMORY();
1663 }
1664
1665 /* PyUnicode can now use the Python codec rather than C implementation
1666 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001667 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001668 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001669}
1670
1671/* Import the site module (not into __main__ though) */
1672
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001673static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001674initsite(void)
1675{
1676 PyObject *m;
1677 m = PyImport_ImportModule("site");
1678 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001679 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001680 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001681 Py_DECREF(m);
1682 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001683}
1684
Victor Stinner874dbe82015-09-04 17:29:57 +02001685/* Check if a file descriptor is valid or not.
1686 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1687static int
1688is_valid_fd(int fd)
1689{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001690/* dup() is faster than fstat(): fstat() can require input/output operations,
1691 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1692 startup. Problem: dup() doesn't check if the file descriptor is valid on
1693 some platforms.
1694
1695 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1696 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1697 EBADF. FreeBSD has similar issue (bpo-32849).
1698
1699 Only use dup() on platforms where dup() is enough to detect invalid FD in
1700 corner cases: on Linux and Windows (bpo-32849). */
1701#if defined(__linux__) || defined(MS_WINDOWS)
1702 if (fd < 0) {
1703 return 0;
1704 }
1705 int fd2;
1706
1707 _Py_BEGIN_SUPPRESS_IPH
1708 fd2 = dup(fd);
1709 if (fd2 >= 0) {
1710 close(fd2);
1711 }
1712 _Py_END_SUPPRESS_IPH
1713
1714 return (fd2 >= 0);
1715#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001716 struct stat st;
1717 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001718#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001719}
1720
1721/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001722static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001723create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001724 int fd, int write_mode, const char* name,
1725 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001726{
1727 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1728 const char* mode;
1729 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001730 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001731 int buffering, isatty;
1732 _Py_IDENTIFIER(open);
1733 _Py_IDENTIFIER(isatty);
1734 _Py_IDENTIFIER(TextIOWrapper);
1735 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001736 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001737
Victor Stinner874dbe82015-09-04 17:29:57 +02001738 if (!is_valid_fd(fd))
1739 Py_RETURN_NONE;
1740
Nick Coghland6009512014-11-20 21:39:37 +10001741 /* stdin is always opened in buffered mode, first because it shouldn't
1742 make a difference in common use cases, second because TextIOWrapper
1743 depends on the presence of a read1() method which only exists on
1744 buffered streams.
1745 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001746 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001747 buffering = 0;
1748 else
1749 buffering = -1;
1750 if (write_mode)
1751 mode = "wb";
1752 else
1753 mode = "rb";
1754 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1755 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001756 Py_None, Py_None, /* encoding, errors */
1757 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001758 if (buf == NULL)
1759 goto error;
1760
1761 if (buffering) {
1762 _Py_IDENTIFIER(raw);
1763 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1764 if (raw == NULL)
1765 goto error;
1766 }
1767 else {
1768 raw = buf;
1769 Py_INCREF(raw);
1770 }
1771
Steve Dower39294992016-08-30 21:22:36 -07001772#ifdef MS_WINDOWS
1773 /* Windows console IO is always UTF-8 encoded */
1774 if (PyWindowsConsoleIO_Check(raw))
1775 encoding = "utf-8";
1776#endif
1777
Nick Coghland6009512014-11-20 21:39:37 +10001778 text = PyUnicode_FromString(name);
1779 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1780 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001781 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001782 if (res == NULL)
1783 goto error;
1784 isatty = PyObject_IsTrue(res);
1785 Py_DECREF(res);
1786 if (isatty == -1)
1787 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001788 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001789 write_through = Py_True;
1790 else
1791 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001792 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001793 line_buffering = Py_True;
1794 else
1795 line_buffering = Py_False;
1796
1797 Py_CLEAR(raw);
1798 Py_CLEAR(text);
1799
1800#ifdef MS_WINDOWS
1801 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1802 newlines to "\n".
1803 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1804 newline = NULL;
1805#else
1806 /* sys.stdin: split lines at "\n".
1807 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1808 newline = "\n";
1809#endif
1810
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001811 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001812 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001813 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001814 Py_CLEAR(buf);
1815 if (stream == NULL)
1816 goto error;
1817
1818 if (write_mode)
1819 mode = "w";
1820 else
1821 mode = "r";
1822 text = PyUnicode_FromString(mode);
1823 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1824 goto error;
1825 Py_CLEAR(text);
1826 return stream;
1827
1828error:
1829 Py_XDECREF(buf);
1830 Py_XDECREF(stream);
1831 Py_XDECREF(text);
1832 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001833
Victor Stinner874dbe82015-09-04 17:29:57 +02001834 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1835 /* Issue #24891: the file descriptor was closed after the first
1836 is_valid_fd() check was called. Ignore the OSError and set the
1837 stream to None. */
1838 PyErr_Clear();
1839 Py_RETURN_NONE;
1840 }
1841 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001842}
1843
1844/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001845static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001846init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001847{
1848 PyObject *iomod = NULL, *wrapper;
1849 PyObject *bimod = NULL;
1850 PyObject *m;
1851 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001852 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001853 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001854 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001855 _PyCoreConfig *config = &interp->core_config;
1856
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001857 /* Check that stdin is not a directory
1858 Using shell redirection, you can redirect stdin to a directory,
1859 crashing the Python interpreter. Catch this common mistake here
1860 and output a useful error message. Note that under MS Windows,
1861 the shell already prevents that. */
1862#ifndef MS_WINDOWS
1863 struct _Py_stat_struct sb;
1864 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1865 S_ISDIR(sb.st_mode)) {
1866 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1867 "cannot continue");
1868 }
1869#endif
1870
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001871 char *codec_name = get_codec_name(config->stdio_encoding);
1872 if (codec_name == NULL) {
1873 return _Py_INIT_ERR("failed to get the Python codec name "
1874 "of the stdio encoding");
1875 }
1876 PyMem_RawFree(config->stdio_encoding);
1877 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001878
1879 /* Hack to avoid a nasty recursion issue when Python is invoked
1880 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1881 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1882 goto error;
1883 }
1884 Py_DECREF(m);
1885
1886 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1887 goto error;
1888 }
1889 Py_DECREF(m);
1890
1891 if (!(bimod = PyImport_ImportModule("builtins"))) {
1892 goto error;
1893 }
1894
1895 if (!(iomod = PyImport_ImportModule("io"))) {
1896 goto error;
1897 }
1898 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1899 goto error;
1900 }
1901
1902 /* Set builtins.open */
1903 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1904 Py_DECREF(wrapper);
1905 goto error;
1906 }
1907 Py_DECREF(wrapper);
1908
Nick Coghland6009512014-11-20 21:39:37 +10001909 /* Set sys.stdin */
1910 fd = fileno(stdin);
1911 /* Under some conditions stdin, stdout and stderr may not be connected
1912 * and fileno() may point to an invalid file descriptor. For example
1913 * GUI apps don't have valid standard streams by default.
1914 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001915 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001916 config->stdio_encoding,
1917 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001918 if (std == NULL)
1919 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001920 PySys_SetObject("__stdin__", std);
1921 _PySys_SetObjectId(&PyId_stdin, std);
1922 Py_DECREF(std);
1923
1924 /* Set sys.stdout */
1925 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001926 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001927 config->stdio_encoding,
1928 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001929 if (std == NULL)
1930 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001931 PySys_SetObject("__stdout__", std);
1932 _PySys_SetObjectId(&PyId_stdout, std);
1933 Py_DECREF(std);
1934
1935#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1936 /* Set sys.stderr, replaces the preliminary stderr */
1937 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001938 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001939 config->stdio_encoding,
1940 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001941 if (std == NULL)
1942 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001943
1944 /* Same as hack above, pre-import stderr's codec to avoid recursion
1945 when import.c tries to write to stderr in verbose mode. */
1946 encoding_attr = PyObject_GetAttrString(std, "encoding");
1947 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001948 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001949 if (std_encoding != NULL) {
1950 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1951 Py_XDECREF(codec_info);
1952 }
1953 Py_DECREF(encoding_attr);
1954 }
1955 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1956
1957 if (PySys_SetObject("__stderr__", std) < 0) {
1958 Py_DECREF(std);
1959 goto error;
1960 }
1961 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1962 Py_DECREF(std);
1963 goto error;
1964 }
1965 Py_DECREF(std);
1966#endif
1967
Victor Stinnera7368ac2017-11-15 18:11:45 -08001968 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001969
Victor Stinnera7368ac2017-11-15 18:11:45 -08001970error:
1971 res = _Py_INIT_ERR("can't initialize sys standard streams");
1972
1973done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001974 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001975
Nick Coghland6009512014-11-20 21:39:37 +10001976 Py_XDECREF(bimod);
1977 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001978 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001979}
1980
1981
Victor Stinner10dc4842015-03-24 12:01:30 +01001982static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001983_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001984{
Victor Stinner10dc4842015-03-24 12:01:30 +01001985 fputc('\n', stderr);
1986 fflush(stderr);
1987
1988 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001989 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001990}
Victor Stinner791da1c2016-03-14 16:53:12 +01001991
1992/* Print the current exception (if an exception is set) with its traceback,
1993 or display the current Python stack.
1994
1995 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1996 called on catastrophic cases.
1997
1998 Return 1 if the traceback was displayed, 0 otherwise. */
1999
2000static int
2001_Py_FatalError_PrintExc(int fd)
2002{
2003 PyObject *ferr, *res;
2004 PyObject *exception, *v, *tb;
2005 int has_tb;
2006
Victor Stinner791da1c2016-03-14 16:53:12 +01002007 PyErr_Fetch(&exception, &v, &tb);
2008 if (exception == NULL) {
2009 /* No current exception */
2010 return 0;
2011 }
2012
2013 ferr = _PySys_GetObjectId(&PyId_stderr);
2014 if (ferr == NULL || ferr == Py_None) {
2015 /* sys.stderr is not set yet or set to None,
2016 no need to try to display the exception */
2017 return 0;
2018 }
2019
2020 PyErr_NormalizeException(&exception, &v, &tb);
2021 if (tb == NULL) {
2022 tb = Py_None;
2023 Py_INCREF(tb);
2024 }
2025 PyException_SetTraceback(v, tb);
2026 if (exception == NULL) {
2027 /* PyErr_NormalizeException() failed */
2028 return 0;
2029 }
2030
2031 has_tb = (tb != Py_None);
2032 PyErr_Display(exception, v, tb);
2033 Py_XDECREF(exception);
2034 Py_XDECREF(v);
2035 Py_XDECREF(tb);
2036
2037 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002038 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002039 if (res == NULL)
2040 PyErr_Clear();
2041 else
2042 Py_DECREF(res);
2043
2044 return has_tb;
2045}
2046
Nick Coghland6009512014-11-20 21:39:37 +10002047/* Print fatal error message and abort */
2048
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002049#ifdef MS_WINDOWS
2050static void
2051fatal_output_debug(const char *msg)
2052{
2053 /* buffer of 256 bytes allocated on the stack */
2054 WCHAR buffer[256 / sizeof(WCHAR)];
2055 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2056 size_t msglen;
2057
2058 OutputDebugStringW(L"Fatal Python error: ");
2059
2060 msglen = strlen(msg);
2061 while (msglen) {
2062 size_t i;
2063
2064 if (buflen > msglen) {
2065 buflen = msglen;
2066 }
2067
2068 /* Convert the message to wchar_t. This uses a simple one-to-one
2069 conversion, assuming that the this error message actually uses
2070 ASCII only. If this ceases to be true, we will have to convert. */
2071 for (i=0; i < buflen; ++i) {
2072 buffer[i] = msg[i];
2073 }
2074 buffer[i] = L'\0';
2075 OutputDebugStringW(buffer);
2076
2077 msg += buflen;
2078 msglen -= buflen;
2079 }
2080 OutputDebugStringW(L"\n");
2081}
2082#endif
2083
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002084static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002085fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002086{
2087 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002088 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002089
2090 if (reentrant) {
2091 /* Py_FatalError() caused a second fatal error.
2092 Example: flush_std_files() raises a recursion error. */
2093 goto exit;
2094 }
2095 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002096
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002097 fprintf(stderr, "Fatal Python error: ");
2098 if (prefix) {
2099 fputs(prefix, stderr);
2100 fputs(": ", stderr);
2101 }
2102 if (msg) {
2103 fputs(msg, stderr);
2104 }
2105 else {
2106 fprintf(stderr, "<message not set>");
2107 }
2108 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002109 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002110
Victor Stinner3a228ab2018-11-01 00:26:41 +01002111 /* Check if the current thread has a Python thread state
2112 and holds the GIL */
2113 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2114 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002115 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002116 if (tss_tstate != tstate) {
2117 /* The Python thread does not hold the GIL */
2118 tss_tstate = NULL;
2119 }
2120 }
2121 else {
2122 /* Py_FatalError() has been called from a C thread
2123 which has no Python thread state. */
2124 }
2125 int has_tstate_and_gil = (tss_tstate != NULL);
2126
2127 if (has_tstate_and_gil) {
2128 /* If an exception is set, print the exception with its traceback */
2129 if (!_Py_FatalError_PrintExc(fd)) {
2130 /* No exception is set, or an exception is set without traceback */
2131 _Py_FatalError_DumpTracebacks(fd);
2132 }
2133 }
2134 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002135 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002136 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002137
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002138 /* The main purpose of faulthandler is to display the traceback.
2139 This function already did its best to display a traceback.
2140 Disable faulthandler to prevent writing a second traceback
2141 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002142 _PyFaulthandler_Fini();
2143
Victor Stinner791da1c2016-03-14 16:53:12 +01002144 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002145 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002146 /* Flush sys.stdout and sys.stderr */
2147 flush_std_files();
2148 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002149
Nick Coghland6009512014-11-20 21:39:37 +10002150#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002151 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002152#endif /* MS_WINDOWS */
2153
2154exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002155 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002156#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002157 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002158#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002159 abort();
2160 }
2161 else {
2162 exit(status);
2163 }
2164}
2165
Victor Stinner19760862017-12-20 01:41:59 +01002166void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002167Py_FatalError(const char *msg)
2168{
2169 fatal_error(NULL, msg, -1);
2170}
2171
Victor Stinner19760862017-12-20 01:41:59 +01002172void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002173_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002174{
Victor Stinnerdfe88472019-03-01 12:14:41 +01002175 if (err.exitcode >= 0) {
2176 exit(err.exitcode);
2177 }
2178 else {
2179 /* On "user" error: exit with status 1.
2180 For all other errors, call abort(). */
2181 int status = err.user_err ? 1 : -1;
2182 fatal_error(err.prefix, err.msg, status);
2183 }
Nick Coghland6009512014-11-20 21:39:37 +10002184}
2185
2186/* Clean up and exit */
2187
Victor Stinnerd7292b52016-06-17 12:29:00 +02002188# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002189
Nick Coghland6009512014-11-20 21:39:37 +10002190/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002191void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002192{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002193 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002194
Antoine Pitroufc5db952017-12-13 02:29:07 +01002195 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002196 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2197
2198 is->pyexitfunc = func;
2199 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002200}
2201
2202static void
Marcel Plch776407f2017-12-20 11:17:58 +01002203call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002204{
Marcel Plch776407f2017-12-20 11:17:58 +01002205 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002206 return;
2207
Marcel Plch776407f2017-12-20 11:17:58 +01002208 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002209 PyErr_Clear();
2210}
2211
2212/* Wait until threading._shutdown completes, provided
2213 the threading module was imported in the first place.
2214 The shutdown routine will wait until all non-daemon
2215 "threading" threads have completed. */
2216static void
2217wait_for_thread_shutdown(void)
2218{
Nick Coghland6009512014-11-20 21:39:37 +10002219 _Py_IDENTIFIER(_shutdown);
2220 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002221 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002222 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002223 if (PyErr_Occurred()) {
2224 PyErr_WriteUnraisable(NULL);
2225 }
2226 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002227 return;
2228 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002229 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002230 if (result == NULL) {
2231 PyErr_WriteUnraisable(threading);
2232 }
2233 else {
2234 Py_DECREF(result);
2235 }
2236 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002237}
2238
2239#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002240int Py_AtExit(void (*func)(void))
2241{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002242 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002243 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002244 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002245 return 0;
2246}
2247
2248static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002249call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002250{
Victor Stinner8e91c242019-04-24 17:24:01 +02002251 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002252 /* pop last function from the list */
2253 runtime->nexitfuncs--;
2254 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2255 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2256
2257 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002258 }
Nick Coghland6009512014-11-20 21:39:37 +10002259
2260 fflush(stdout);
2261 fflush(stderr);
2262}
2263
Victor Stinnercfc88312018-08-01 16:41:25 +02002264void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002265Py_Exit(int sts)
2266{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002267 if (Py_FinalizeEx() < 0) {
2268 sts = 120;
2269 }
Nick Coghland6009512014-11-20 21:39:37 +10002270
2271 exit(sts);
2272}
2273
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002274static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002275initsigs(void)
2276{
2277#ifdef SIGPIPE
2278 PyOS_setsig(SIGPIPE, SIG_IGN);
2279#endif
2280#ifdef SIGXFZ
2281 PyOS_setsig(SIGXFZ, SIG_IGN);
2282#endif
2283#ifdef SIGXFSZ
2284 PyOS_setsig(SIGXFSZ, SIG_IGN);
2285#endif
2286 PyOS_InitInterrupts(); /* May imply initsignal() */
2287 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002288 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002289 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002290 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002291}
2292
2293
2294/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2295 *
2296 * All of the code in this function must only use async-signal-safe functions,
2297 * listed at `man 7 signal` or
2298 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2299 */
2300void
2301_Py_RestoreSignals(void)
2302{
2303#ifdef SIGPIPE
2304 PyOS_setsig(SIGPIPE, SIG_DFL);
2305#endif
2306#ifdef SIGXFZ
2307 PyOS_setsig(SIGXFZ, SIG_DFL);
2308#endif
2309#ifdef SIGXFSZ
2310 PyOS_setsig(SIGXFSZ, SIG_DFL);
2311#endif
2312}
2313
2314
2315/*
2316 * The file descriptor fd is considered ``interactive'' if either
2317 * a) isatty(fd) is TRUE, or
2318 * b) the -i flag was given, and the filename associated with
2319 * the descriptor is NULL or "<stdin>" or "???".
2320 */
2321int
2322Py_FdIsInteractive(FILE *fp, const char *filename)
2323{
2324 if (isatty((int)fileno(fp)))
2325 return 1;
2326 if (!Py_InteractiveFlag)
2327 return 0;
2328 return (filename == NULL) ||
2329 (strcmp(filename, "<stdin>") == 0) ||
2330 (strcmp(filename, "???") == 0);
2331}
2332
2333
Nick Coghland6009512014-11-20 21:39:37 +10002334/* Wrappers around sigaction() or signal(). */
2335
2336PyOS_sighandler_t
2337PyOS_getsig(int sig)
2338{
2339#ifdef HAVE_SIGACTION
2340 struct sigaction context;
2341 if (sigaction(sig, NULL, &context) == -1)
2342 return SIG_ERR;
2343 return context.sa_handler;
2344#else
2345 PyOS_sighandler_t handler;
2346/* Special signal handling for the secure CRT in Visual Studio 2005 */
2347#if defined(_MSC_VER) && _MSC_VER >= 1400
2348 switch (sig) {
2349 /* Only these signals are valid */
2350 case SIGINT:
2351 case SIGILL:
2352 case SIGFPE:
2353 case SIGSEGV:
2354 case SIGTERM:
2355 case SIGBREAK:
2356 case SIGABRT:
2357 break;
2358 /* Don't call signal() with other values or it will assert */
2359 default:
2360 return SIG_ERR;
2361 }
2362#endif /* _MSC_VER && _MSC_VER >= 1400 */
2363 handler = signal(sig, SIG_IGN);
2364 if (handler != SIG_ERR)
2365 signal(sig, handler);
2366 return handler;
2367#endif
2368}
2369
2370/*
2371 * All of the code in this function must only use async-signal-safe functions,
2372 * listed at `man 7 signal` or
2373 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2374 */
2375PyOS_sighandler_t
2376PyOS_setsig(int sig, PyOS_sighandler_t handler)
2377{
2378#ifdef HAVE_SIGACTION
2379 /* Some code in Modules/signalmodule.c depends on sigaction() being
2380 * used here if HAVE_SIGACTION is defined. Fix that if this code
2381 * changes to invalidate that assumption.
2382 */
2383 struct sigaction context, ocontext;
2384 context.sa_handler = handler;
2385 sigemptyset(&context.sa_mask);
2386 context.sa_flags = 0;
2387 if (sigaction(sig, &context, &ocontext) == -1)
2388 return SIG_ERR;
2389 return ocontext.sa_handler;
2390#else
2391 PyOS_sighandler_t oldhandler;
2392 oldhandler = signal(sig, handler);
2393#ifdef HAVE_SIGINTERRUPT
2394 siginterrupt(sig, 1);
2395#endif
2396 return oldhandler;
2397#endif
2398}
2399
2400#ifdef __cplusplus
2401}
2402#endif