blob: 7c6948e6bdb1c3c6f23b89ad2fc31fde2348deef [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);
68static void call_ll_exitfuncs(void);
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 Stinner20004952019-03-26 02:31:11 +0100289_emit_stderr_warning_for_legacy_locale(void)
Nick Coghlaneb817952017-06-18 12:29:42 +1000290{
Victor Stinner20004952019-03-26 02:31:11 +0100291 const _PyPreConfig *preconfig = &_PyRuntime.preconfig;
292 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 Stinner6d43f6f2019-01-22 21:18:05 +0100471_Py_Initialize_ReconfigureCore(PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200472 const _PyCoreConfig *core_config)
473{
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100474 PyThreadState *tstate = _PyThreadState_GET();
475 if (!tstate) {
476 return _Py_INIT_ERR("failed to read thread state");
477 }
478
479 PyInterpreterState *interp = tstate->interp;
480 if (interp == NULL) {
481 return _Py_INIT_ERR("can't make main interpreter");
482 }
483 *interp_p = interp;
484
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100485 _PyCoreConfig_Write(core_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200486
487 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
488 return _Py_INIT_ERR("failed to copy core config");
489 }
490 core_config = &interp->core_config;
491
492 if (core_config->_install_importlib) {
493 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
494 if (_Py_INIT_FAILED(err)) {
495 return err;
496 }
497 }
498 return _Py_INIT_OK();
499}
500
501
Victor Stinner1dc6e392018-07-25 02:49:17 +0200502static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100503pycore_init_runtime(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000504{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200505 if (_PyRuntime.initialized) {
506 return _Py_INIT_ERR("main interpreter already initialized");
507 }
Victor Stinnerda273412017-12-15 01:46:02 +0100508
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100509 _PyCoreConfig_Write(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000510
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100511 _PyInitError err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800512 if (_Py_INIT_FAILED(err)) {
513 return err;
514 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600515
Eric Snow1abcf672017-05-23 21:46:51 -0700516 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
517 * threads behave a little more gracefully at interpreter shutdown.
518 * We clobber it here so the new interpreter can start with a clean
519 * slate.
520 *
521 * However, this may still lead to misbehaviour if there are daemon
522 * threads still hanging around from a previous Py_Initialize/Finalize
523 * pair :(
524 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600525 _PyRuntime.finalizing = NULL;
526
Victor Stinnerda273412017-12-15 01:46:02 +0100527 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800528 if (_Py_INIT_FAILED(err)) {
529 return err;
530 }
531
Victor Stinnera7368ac2017-11-15 18:11:45 -0800532 err = _PyInterpreterState_Enable(&_PyRuntime);
533 if (_Py_INIT_FAILED(err)) {
534 return err;
535 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100536 return _Py_INIT_OK();
537}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800538
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100539
540static _PyInitError
541pycore_create_interpreter(const _PyCoreConfig *core_config,
542 PyInterpreterState **interp_p)
543{
544 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100545 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800546 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100547 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200548 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100549
550 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
551 return _Py_INIT_ERR("failed to copy core config");
552 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200553 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000554
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200555 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000556 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800557 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000558 (void) PyThreadState_Swap(tstate);
559
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000560 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000561 destroying the GIL might fail when it is being referenced from
562 another running thread (see issue #9901).
563 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000564 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000565 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100566
Nick Coghland6009512014-11-20 21:39:37 +1000567 /* Auto-thread-state API */
568 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000569
Victor Stinner2914bb32018-01-29 11:57:45 +0100570 /* Create the GIL */
571 PyEval_InitThreads();
572
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573 return _Py_INIT_OK();
574}
Nick Coghland6009512014-11-20 21:39:37 +1000575
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100576
577static _PyInitError
578pycore_init_types(void)
579{
Victor Stinnerab672812019-01-23 15:04:40 +0100580 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100581 if (_Py_INIT_FAILED(err)) {
582 return err;
583 }
584
585 err = _PyUnicode_Init();
586 if (_Py_INIT_FAILED(err)) {
587 return err;
588 }
589
590 if (_PyStructSequence_Init() < 0) {
591 return _Py_INIT_ERR("can't initialize structseq");
592 }
593
594 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800595 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100596 }
Nick Coghland6009512014-11-20 21:39:37 +1000597
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100598 err = _PyExc_Init();
599 if (_Py_INIT_FAILED(err)) {
600 return err;
601 }
602
603 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800604 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100605 }
Nick Coghland6009512014-11-20 21:39:37 +1000606
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100607 if (!_PyContext_Init()) {
608 return _Py_INIT_ERR("can't init context");
609 }
610 return _Py_INIT_OK();
611}
612
613
614static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100615pycore_init_builtins(PyInterpreterState *interp)
616{
617 PyObject *bimod = _PyBuiltin_Init();
618 if (bimod == NULL) {
619 return _Py_INIT_ERR("can't initialize builtins modules");
620 }
621 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
622
623 interp->builtins = PyModule_GetDict(bimod);
624 if (interp->builtins == NULL) {
625 return _Py_INIT_ERR("can't initialize builtins dict");
626 }
627 Py_INCREF(interp->builtins);
628
629 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
630 if (_Py_INIT_FAILED(err)) {
631 return err;
632 }
633 return _Py_INIT_OK();
634}
635
636
637static _PyInitError
638pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
639{
640 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800641 if (_Py_INIT_FAILED(err)) {
642 return err;
643 }
Nick Coghland6009512014-11-20 21:39:37 +1000644
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800645 err = _PyImportHooks_Init();
646 if (_Py_INIT_FAILED(err)) {
647 return err;
648 }
Nick Coghland6009512014-11-20 21:39:37 +1000649
650 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100651 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100652 return _Py_INIT_ERR("can't initialize warnings");
653 }
Nick Coghland6009512014-11-20 21:39:37 +1000654
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100655 if (interp->core_config._install_importlib) {
656 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200657 if (_Py_INIT_FAILED(err)) {
658 return err;
659 }
660 }
661
Eric Snow1abcf672017-05-23 21:46:51 -0700662 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100663 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800664 err = initimport(interp, sysmod);
665 if (_Py_INIT_FAILED(err)) {
666 return err;
667 }
Eric Snow1abcf672017-05-23 21:46:51 -0700668 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100669 return _Py_INIT_OK();
670}
671
672
673static _PyInitError
674_Py_InitializeCore_impl(PyInterpreterState **interp_p,
675 const _PyCoreConfig *core_config)
676{
677 PyInterpreterState *interp;
678
Victor Stinner20004952019-03-26 02:31:11 +0100679 _PyCoreConfig_Write(core_config);
680
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100681 _PyInitError err = pycore_init_runtime(core_config);
682 if (_Py_INIT_FAILED(err)) {
683 return err;
684 }
685
686 err = pycore_create_interpreter(core_config, &interp);
687 if (_Py_INIT_FAILED(err)) {
688 return err;
689 }
690 core_config = &interp->core_config;
691 *interp_p = interp;
692
693 err = pycore_init_types();
694 if (_Py_INIT_FAILED(err)) {
695 return err;
696 }
697
698 PyObject *sysmod;
Victor Stinnerab672812019-01-23 15:04:40 +0100699 err = _PySys_Create(interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100700 if (_Py_INIT_FAILED(err)) {
701 return err;
702 }
703
704 err = pycore_init_builtins(interp);
705 if (_Py_INIT_FAILED(err)) {
706 return err;
707 }
708
709 err = pycore_init_import_warnings(interp, sysmod);
710 if (_Py_INIT_FAILED(err)) {
711 return err;
712 }
Eric Snow1abcf672017-05-23 21:46:51 -0700713
714 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600715 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800716 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700717}
718
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100719
Victor Stinnerf29084d2019-03-20 02:20:13 +0100720static _PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100721preinit(const _PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100722{
723 _PyInitError err;
724
725 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100726 if (_Py_INIT_FAILED(err)) {
Victor Stinner5ac27a52019-03-27 13:40:14 +0100727 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100728 }
729
Victor Stinnerf72346c2019-03-25 17:54:58 +0100730 if (_PyRuntime.pre_initialized) {
731 /* 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
754 _PyRuntime.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 Stinner5ac27a52019-03-27 13:40:14 +0100788 _PyPreConfig config = _PyPreConfig_INIT;
789 _PyCoreConfig_GetCoreConfig(&config, coreconfig);
790 return _Py_PreInitialize(&config);
791 /* No need to clear config:
792 _PyCoreConfig_GetCoreConfig() doesn't allocate memory */
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100793}
794
795
796static _PyInitError
Victor Stinner5ac27a52019-03-27 13:40:14 +0100797pyinit_coreconfig(_PyCoreConfig *config,
798 const _PyCoreConfig *src_config,
799 const _PyArgv *args,
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100800 PyInterpreterState **interp_p)
801{
Victor Stinnerc656e252019-03-06 01:13:43 +0100802 if (_PyCoreConfig_Copy(config, src_config) < 0) {
803 return _Py_INIT_ERR("failed to copy core config");
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100804 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100805
Victor Stinner5ac27a52019-03-27 13:40:14 +0100806 _PyInitError err = _PyCoreConfig_Read(config, args);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100807 if (_Py_INIT_FAILED(err)) {
808 return err;
809 }
810
811 if (!_PyRuntime.core_initialized) {
812 return _Py_InitializeCore_impl(interp_p, config);
813 }
814 else {
815 return _Py_Initialize_ReconfigureCore(interp_p, config);
816 }
817}
818
819
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100820/* Begin interpreter initialization
821 *
822 * On return, the first thread and interpreter state have been created,
823 * but the compiler, signal handling, multithreading and
824 * multiple interpreter support, and codec infrastructure are not yet
825 * available.
826 *
827 * The import system will support builtin and frozen modules only.
828 * The only supported io is writing to sys.stderr
829 *
830 * If any operation invoked by this function fails, a fatal error is
831 * issued and the function does not return.
832 *
833 * Any code invoked from this function should *not* assume it has access
834 * to the Python C API (unless the API is explicitly listed as being
835 * safe to call without calling Py_Initialize first)
836 */
Victor Stinner484f20d2019-03-27 02:04:16 +0100837static _PyInitError
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100838_Py_InitializeCore(const _PyCoreConfig *src_config,
Victor Stinner5ac27a52019-03-27 13:40:14 +0100839 const _PyArgv *args,
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100840 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200841{
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100842 assert(src_config != NULL);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200843
Victor Stinner5ac27a52019-03-27 13:40:14 +0100844 _PyInitError err = _Py_PreInitializeFromCoreConfig(src_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200845 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100846 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200847 }
848
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100849 _PyCoreConfig local_config = _PyCoreConfig_INIT;
Victor Stinner5ac27a52019-03-27 13:40:14 +0100850 err = pyinit_coreconfig(&local_config, src_config, args, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100851 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200852 return err;
853}
854
Victor Stinner5ac27a52019-03-27 13:40:14 +0100855
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200856/* Py_Initialize() has already been called: update the main interpreter
857 configuration. Example of bpo-34008: Py_Main() called after
858 Py_Initialize(). */
859static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100860_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200861{
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100862 _PyCoreConfig *core_config = &interp->core_config;
863
864 PyObject *argv = _PyWstrList_AsList(&core_config->argv);
865 if (argv == NULL) {
866 return _Py_INIT_NO_MEMORY(); \
867 }
868
869 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
870 Py_DECREF(argv);
871 if (res < 0) {
872 return _Py_INIT_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200873 }
874 return _Py_INIT_OK();
875}
876
Eric Snowc7ec9982017-05-23 23:00:52 -0700877/* Update interpreter state based on supplied configuration settings
878 *
879 * After calling this function, most of the restrictions on the interpreter
880 * are lifted. The only remaining incomplete settings are those related
881 * to the main module (sys.argv[0], __main__ metadata)
882 *
883 * Calling this when the interpreter is not initializing, is already
884 * initialized or without a valid current thread state is a fatal error.
885 * Other errors should be reported as normal Python exceptions with a
886 * non-zero return code.
887 */
Victor Stinner5ac27a52019-03-27 13:40:14 +0100888static _PyInitError
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100889_Py_InitializeMainInterpreter(PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700890{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600891 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800892 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700893 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700894
Victor Stinner1dc6e392018-07-25 02:49:17 +0200895 /* Configure the main interpreter */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200896 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700897
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200898 if (_PyRuntime.initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100899 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200900 }
901
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200902 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700903 /* Special mode for freeze_importlib: run with no import system
904 *
905 * This means anything which needs support from extension modules
906 * or pure Python code in the standard library won't work.
907 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600908 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800909 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700910 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100911
Victor Stinner33c377e2017-12-05 15:12:41 +0100912 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100914 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200915
Victor Stinnerab672812019-01-23 15:04:40 +0100916 if (_PySys_InitMain(interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800917 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100918 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800919
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200920 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800921 if (_Py_INIT_FAILED(err)) {
922 return err;
923 }
Nick Coghland6009512014-11-20 21:39:37 +1000924
925 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200926 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927 if (_Py_INIT_FAILED(err)) {
928 return err;
929 }
Nick Coghland6009512014-11-20 21:39:37 +1000930
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 err = initfsencoding(interp);
932 if (_Py_INIT_FAILED(err)) {
933 return err;
934 }
Nick Coghland6009512014-11-20 21:39:37 +1000935
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100936 if (core_config->install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800937 err = initsigs(); /* Signal handling stuff, including initintr() */
938 if (_Py_INIT_FAILED(err)) {
939 return err;
940 }
941 }
Nick Coghland6009512014-11-20 21:39:37 +1000942
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200943 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800944 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200945 }
Nick Coghland6009512014-11-20 21:39:37 +1000946
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800947 err = add_main_module(interp);
948 if (_Py_INIT_FAILED(err)) {
949 return err;
950 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800951
Victor Stinner91106cd2017-12-13 12:29:09 +0100952 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800953 if (_Py_INIT_FAILED(err)) {
954 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800955 }
Nick Coghland6009512014-11-20 21:39:37 +1000956
957 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100958 PyObject *warnoptions = PySys_GetObject("warnoptions");
959 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100960 {
Nick Coghland6009512014-11-20 21:39:37 +1000961 PyObject *warnings_module = PyImport_ImportModule("warnings");
962 if (warnings_module == NULL) {
963 fprintf(stderr, "'import warnings' failed; traceback:\n");
964 PyErr_Print();
965 }
966 Py_XDECREF(warnings_module);
967 }
968
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600969 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700970
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200971 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800972 err = initsite(); /* Module site */
973 if (_Py_INIT_FAILED(err)) {
974 return err;
975 }
976 }
Victor Stinnercf215042018-08-29 22:56:06 +0200977
978#ifndef MS_WINDOWS
Victor Stinner20004952019-03-26 02:31:11 +0100979 _emit_stderr_warning_for_legacy_locale();
Victor Stinnercf215042018-08-29 22:56:06 +0200980#endif
981
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800982 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000983}
984
Eric Snowc7ec9982017-05-23 23:00:52 -0700985#undef _INIT_DEBUG_PRINT
986
Victor Stinner5ac27a52019-03-27 13:40:14 +0100987static _PyInitError
988init_python(const _PyCoreConfig *config, const _PyArgv *args)
Eric Snow1abcf672017-05-23 21:46:51 -0700989{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700990 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800991 _PyInitError err;
Victor Stinner5ac27a52019-03-27 13:40:14 +0100992 err = _Py_InitializeCore(config, args, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800993 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200994 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800995 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200996 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100997
Victor Stinner484f20d2019-03-27 02:04:16 +0100998 if (config->_init_main) {
999 err = _Py_InitializeMainInterpreter(interp);
1000 if (_Py_INIT_FAILED(err)) {
1001 return err;
1002 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001003 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001004
Victor Stinner1dc6e392018-07-25 02:49:17 +02001005 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001006}
1007
1008
Victor Stinner5ac27a52019-03-27 13:40:14 +01001009_PyInitError
1010_Py_InitializeFromArgs(const _PyCoreConfig *config, int argc, char **argv)
1011{
1012 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1013 return init_python(config, &args);
1014}
1015
1016
1017_PyInitError
1018_Py_InitializeFromWideArgs(const _PyCoreConfig *config, int argc, wchar_t **argv)
1019{
1020 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1021 return init_python(config, &args);
1022}
1023
1024
1025_PyInitError
1026_Py_InitializeFromConfig(const _PyCoreConfig *config)
1027{
1028 return init_python(config, NULL);
1029}
1030
1031
Eric Snow1abcf672017-05-23 21:46:51 -07001032void
Nick Coghland6009512014-11-20 21:39:37 +10001033Py_InitializeEx(int install_sigs)
1034{
Victor Stinner1dc6e392018-07-25 02:49:17 +02001035 if (_PyRuntime.initialized) {
1036 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1037 return;
1038 }
1039
Victor Stinner1dc6e392018-07-25 02:49:17 +02001040 _PyCoreConfig config = _PyCoreConfig_INIT;
1041 config.install_signal_handlers = install_sigs;
1042
Victor Stinner5ac27a52019-03-27 13:40:14 +01001043 _PyInitError err = _Py_InitializeFromConfig(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001044 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001045 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001046 }
Nick Coghland6009512014-11-20 21:39:37 +10001047}
1048
1049void
1050Py_Initialize(void)
1051{
1052 Py_InitializeEx(1);
1053}
1054
1055
1056#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001057extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001058#endif
1059
1060/* Flush stdout and stderr */
1061
1062static int
1063file_is_closed(PyObject *fobj)
1064{
1065 int r;
1066 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1067 if (tmp == NULL) {
1068 PyErr_Clear();
1069 return 0;
1070 }
1071 r = PyObject_IsTrue(tmp);
1072 Py_DECREF(tmp);
1073 if (r < 0)
1074 PyErr_Clear();
1075 return r > 0;
1076}
1077
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001078static int
Nick Coghland6009512014-11-20 21:39:37 +10001079flush_std_files(void)
1080{
1081 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1082 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1083 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001084 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001085
1086 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001087 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001088 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001089 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001090 status = -1;
1091 }
Nick Coghland6009512014-11-20 21:39:37 +10001092 else
1093 Py_DECREF(tmp);
1094 }
1095
1096 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001097 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001098 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001099 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001100 status = -1;
1101 }
Nick Coghland6009512014-11-20 21:39:37 +10001102 else
1103 Py_DECREF(tmp);
1104 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001105
1106 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001107}
1108
1109/* Undo the effect of Py_Initialize().
1110
1111 Beware: if multiple interpreter and/or thread states exist, these
1112 are not wiped out; only the current thread and interpreter state
1113 are deleted. But since everything else is deleted, those other
1114 interpreter and thread states should no longer be used.
1115
1116 (XXX We should do better, e.g. wipe out all interpreters and
1117 threads.)
1118
1119 Locking: as above.
1120
1121*/
1122
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001123int
1124Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001125{
1126 PyInterpreterState *interp;
1127 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001128 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001129
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001130 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001131 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001132
Eric Snow842a2f02019-03-15 15:47:51 -06001133 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001134 wait_for_thread_shutdown();
1135
Marcel Plch776407f2017-12-20 11:17:58 +01001136 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001137 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001138 interp = tstate->interp;
1139
Eric Snow842a2f02019-03-15 15:47:51 -06001140 // Make any remaining pending calls.
1141 _Py_FinishPendingCalls();
1142
Nick Coghland6009512014-11-20 21:39:37 +10001143 /* The interpreter is still entirely intact at this point, and the
1144 * exit funcs may be relying on that. In particular, if some thread
1145 * or exit func is still waiting to do an import, the import machinery
1146 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001147 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001148 * Note that Threading.py uses an exit func to do a join on all the
1149 * threads created thru it, so this also protects pending imports in
1150 * the threads created via Threading.
1151 */
Nick Coghland6009512014-11-20 21:39:37 +10001152
Marcel Plch776407f2017-12-20 11:17:58 +01001153 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001154
Victor Stinnerda273412017-12-15 01:46:02 +01001155 /* Copy the core config, PyInterpreterState_Delete() free
1156 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001157#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001158 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001159#endif
1160#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001161 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001162#endif
1163#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001164 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001165#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001166
Nick Coghland6009512014-11-20 21:39:37 +10001167 /* Remaining threads (e.g. daemon threads) will automatically exit
1168 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001169 _PyRuntime.finalizing = tstate;
1170 _PyRuntime.initialized = 0;
1171 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001172
Victor Stinnere0deff32015-03-24 13:46:18 +01001173 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001174 if (flush_std_files() < 0) {
1175 status = -1;
1176 }
Nick Coghland6009512014-11-20 21:39:37 +10001177
1178 /* Disable signal handling */
1179 PyOS_FiniInterrupts();
1180
1181 /* Collect garbage. This may call finalizers; it's nice to call these
1182 * before all modules are destroyed.
1183 * XXX If a __del__ or weakref callback is triggered here, and tries to
1184 * XXX import a module, bad things can happen, because Python no
1185 * XXX longer believes it's initialized.
1186 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1187 * XXX is easy to provoke that way. I've also seen, e.g.,
1188 * XXX Exception exceptions.ImportError: 'No module named sha'
1189 * XXX in <function callback at 0x008F5718> ignored
1190 * XXX but I'm unclear on exactly how that one happens. In any case,
1191 * XXX I haven't seen a real-life report of either of these.
1192 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001193 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001194#ifdef COUNT_ALLOCS
1195 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1196 each collection might release some types from the type
1197 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001198 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001199 /* nothing */;
1200#endif
Eric Snowdae02762017-09-14 00:35:58 -07001201
Nick Coghland6009512014-11-20 21:39:37 +10001202 /* Destroy all modules */
1203 PyImport_Cleanup();
1204
Victor Stinnere0deff32015-03-24 13:46:18 +01001205 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001206 if (flush_std_files() < 0) {
1207 status = -1;
1208 }
Nick Coghland6009512014-11-20 21:39:37 +10001209
1210 /* Collect final garbage. This disposes of cycles created by
1211 * class definitions, for example.
1212 * XXX This is disabled because it caused too many problems. If
1213 * XXX a __del__ or weakref callback triggers here, Python code has
1214 * XXX a hard time running, because even the sys module has been
1215 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1216 * XXX One symptom is a sequence of information-free messages
1217 * XXX coming from threads (if a __del__ or callback is invoked,
1218 * XXX other threads can execute too, and any exception they encounter
1219 * XXX triggers a comedy of errors as subsystem after subsystem
1220 * XXX fails to find what it *expects* to find in sys to help report
1221 * XXX the exception and consequent unexpected failures). I've also
1222 * XXX seen segfaults then, after adding print statements to the
1223 * XXX Python code getting called.
1224 */
1225#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001226 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001227#endif
1228
1229 /* Disable tracemalloc after all Python objects have been destroyed,
1230 so it is possible to use tracemalloc in objects destructor. */
1231 _PyTraceMalloc_Fini();
1232
1233 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1234 _PyImport_Fini();
1235
1236 /* Cleanup typeobject.c's internal caches. */
1237 _PyType_Fini();
1238
1239 /* unload faulthandler module */
1240 _PyFaulthandler_Fini();
1241
1242 /* Debugging stuff */
1243#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001244 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001245#endif
1246 /* dump hash stats */
1247 _PyHash_Fini();
1248
Eric Snowdae02762017-09-14 00:35:58 -07001249#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001250 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001251 _PyDebug_PrintTotalRefs();
1252 }
Eric Snowdae02762017-09-14 00:35:58 -07001253#endif
Nick Coghland6009512014-11-20 21:39:37 +10001254
1255#ifdef Py_TRACE_REFS
1256 /* Display all objects still alive -- this can invoke arbitrary
1257 * __repr__ overrides, so requires a mostly-intact interpreter.
1258 * Alas, a lot of stuff may still be alive now that will be cleaned
1259 * up later.
1260 */
Victor Stinnerda273412017-12-15 01:46:02 +01001261 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001262 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001263 }
Nick Coghland6009512014-11-20 21:39:37 +10001264#endif /* Py_TRACE_REFS */
1265
1266 /* Clear interpreter state and all thread states. */
1267 PyInterpreterState_Clear(interp);
1268
1269 /* Now we decref the exception classes. After this point nothing
1270 can raise an exception. That's okay, because each Fini() method
1271 below has been checked to make sure no exceptions are ever
1272 raised.
1273 */
1274
1275 _PyExc_Fini();
1276
1277 /* Sundry finalizers */
1278 PyMethod_Fini();
1279 PyFrame_Fini();
1280 PyCFunction_Fini();
1281 PyTuple_Fini();
1282 PyList_Fini();
1283 PySet_Fini();
1284 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001285 PyLong_Fini();
1286 PyFloat_Fini();
1287 PyDict_Fini();
1288 PySlice_Fini();
1289 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001290 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001291 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001292 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001293 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001294
1295 /* Cleanup Unicode implementation */
1296 _PyUnicode_Fini();
1297
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001298 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001299
1300 /* XXX Still allocated:
1301 - various static ad-hoc pointers to interned strings
1302 - int and float free list blocks
1303 - whatever various modules and libraries allocate
1304 */
1305
1306 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1307
1308 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001309 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001310
1311 /* Delete current thread. After this, many C API calls become crashy. */
1312 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001313
Nick Coghland6009512014-11-20 21:39:37 +10001314 PyInterpreterState_Delete(interp);
1315
1316#ifdef Py_TRACE_REFS
1317 /* Display addresses (& refcnts) of all objects still alive.
1318 * An address can be used to find the repr of the object, printed
1319 * above by _Py_PrintReferences.
1320 */
Victor Stinnerda273412017-12-15 01:46:02 +01001321 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001322 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001323 }
Nick Coghland6009512014-11-20 21:39:37 +10001324#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001325#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001326 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001327 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001328 }
Nick Coghland6009512014-11-20 21:39:37 +10001329#endif
1330
1331 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001332
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001333 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001334 return status;
1335}
1336
1337void
1338Py_Finalize(void)
1339{
1340 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001341}
1342
1343/* Create and initialize a new interpreter and thread, and return the
1344 new thread. This requires that Py_Initialize() has been called
1345 first.
1346
1347 Unsuccessful initialization yields a NULL pointer. Note that *no*
1348 exception information is available even in this case -- the
1349 exception information is held in the thread, and there is no
1350 thread.
1351
1352 Locking: as above.
1353
1354*/
1355
Victor Stinnera7368ac2017-11-15 18:11:45 -08001356static _PyInitError
1357new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001358{
1359 PyInterpreterState *interp;
1360 PyThreadState *tstate, *save_tstate;
1361 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001362 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001363
Victor Stinnera7368ac2017-11-15 18:11:45 -08001364 if (!_PyRuntime.initialized) {
1365 return _Py_INIT_ERR("Py_Initialize must be called first");
1366 }
Nick Coghland6009512014-11-20 21:39:37 +10001367
Victor Stinner8a1be612016-03-14 22:07:55 +01001368 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1369 interpreters: disable PyGILState_Check(). */
1370 _PyGILState_check_enabled = 0;
1371
Nick Coghland6009512014-11-20 21:39:37 +10001372 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001373 if (interp == NULL) {
1374 *tstate_p = NULL;
1375 return _Py_INIT_OK();
1376 }
Nick Coghland6009512014-11-20 21:39:37 +10001377
1378 tstate = PyThreadState_New(interp);
1379 if (tstate == NULL) {
1380 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001381 *tstate_p = NULL;
1382 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001383 }
1384
1385 save_tstate = PyThreadState_Swap(tstate);
1386
Eric Snow1abcf672017-05-23 21:46:51 -07001387 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001388 _PyCoreConfig *core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001389 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001390 core_config = &save_tstate->interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001391 } else {
1392 /* No current thread state, copy from the main interpreter */
1393 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001394 core_config = &main_interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001395 }
1396
1397 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1398 return _Py_INIT_ERR("failed to copy core config");
1399 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001400 core_config = &interp->core_config;
Eric Snow1abcf672017-05-23 21:46:51 -07001401
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001402 err = _PyExc_Init();
1403 if (_Py_INIT_FAILED(err)) {
1404 return err;
1405 }
1406
Nick Coghland6009512014-11-20 21:39:37 +10001407 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001408 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001409 if (modules == NULL) {
1410 return _Py_INIT_ERR("can't make modules dictionary");
1411 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001412 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001413
Eric Snowd393c1b2017-09-14 12:18:12 -06001414 sysmod = _PyImport_FindBuiltin("sys", modules);
1415 if (sysmod != NULL) {
1416 interp->sysdict = PyModule_GetDict(sysmod);
1417 if (interp->sysdict == NULL)
1418 goto handle_error;
1419 Py_INCREF(interp->sysdict);
1420 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerab672812019-01-23 15:04:40 +01001421 if (_PySys_InitMain(interp) < 0) {
1422 return _Py_INIT_ERR("can't finish initializing sys");
1423 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001424 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001425 else if (PyErr_Occurred()) {
1426 goto handle_error;
1427 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001428
1429 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001430 if (bimod != NULL) {
1431 interp->builtins = PyModule_GetDict(bimod);
1432 if (interp->builtins == NULL)
1433 goto handle_error;
1434 Py_INCREF(interp->builtins);
1435 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001436 else if (PyErr_Occurred()) {
1437 goto handle_error;
1438 }
Nick Coghland6009512014-11-20 21:39:37 +10001439
Nick Coghland6009512014-11-20 21:39:37 +10001440 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001441 err = _PyBuiltins_AddExceptions(bimod);
1442 if (_Py_INIT_FAILED(err)) {
1443 return err;
1444 }
Nick Coghland6009512014-11-20 21:39:37 +10001445
Victor Stinnerab672812019-01-23 15:04:40 +01001446 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1447 if (_Py_INIT_FAILED(err)) {
1448 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001449 }
Nick Coghland6009512014-11-20 21:39:37 +10001450
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001451 err = _PyImportHooks_Init();
1452 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001453 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001454 }
Nick Coghland6009512014-11-20 21:39:37 +10001455
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001456 err = initimport(interp, sysmod);
1457 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001458 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001459 }
Nick Coghland6009512014-11-20 21:39:37 +10001460
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001461 err = initexternalimport(interp);
1462 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001463 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001464 }
Nick Coghland6009512014-11-20 21:39:37 +10001465
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001466 err = initfsencoding(interp);
1467 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001468 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001469 }
1470
Victor Stinner91106cd2017-12-13 12:29:09 +01001471 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001472 if (_Py_INIT_FAILED(err)) {
1473 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001474 }
1475
1476 err = add_main_module(interp);
1477 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001478 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001479 }
1480
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001481 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001482 err = initsite();
1483 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001484 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001485 }
1486 }
Nick Coghland6009512014-11-20 21:39:37 +10001487 }
1488
Victor Stinnera7368ac2017-11-15 18:11:45 -08001489 if (PyErr_Occurred()) {
1490 goto handle_error;
1491 }
Nick Coghland6009512014-11-20 21:39:37 +10001492
Victor Stinnera7368ac2017-11-15 18:11:45 -08001493 *tstate_p = tstate;
1494 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001495
Nick Coghland6009512014-11-20 21:39:37 +10001496handle_error:
1497 /* Oops, it didn't work. Undo it all. */
1498
1499 PyErr_PrintEx(0);
1500 PyThreadState_Clear(tstate);
1501 PyThreadState_Swap(save_tstate);
1502 PyThreadState_Delete(tstate);
1503 PyInterpreterState_Delete(interp);
1504
Victor Stinnera7368ac2017-11-15 18:11:45 -08001505 *tstate_p = NULL;
1506 return _Py_INIT_OK();
1507}
1508
1509PyThreadState *
1510Py_NewInterpreter(void)
1511{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001512 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001513 _PyInitError err = new_interpreter(&tstate);
1514 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001515 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001516 }
1517 return tstate;
1518
Nick Coghland6009512014-11-20 21:39:37 +10001519}
1520
1521/* Delete an interpreter and its last thread. This requires that the
1522 given thread state is current, that the thread has no remaining
1523 frames, and that it is its interpreter's only remaining thread.
1524 It is a fatal error to violate these constraints.
1525
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001526 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001527 everything, regardless.)
1528
1529 Locking: as above.
1530
1531*/
1532
1533void
1534Py_EndInterpreter(PyThreadState *tstate)
1535{
1536 PyInterpreterState *interp = tstate->interp;
1537
Victor Stinner50b48572018-11-01 01:51:40 +01001538 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001539 Py_FatalError("Py_EndInterpreter: thread is not current");
1540 if (tstate->frame != NULL)
1541 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001542 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001543
Eric Snow842a2f02019-03-15 15:47:51 -06001544 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001545 wait_for_thread_shutdown();
1546
Marcel Plch776407f2017-12-20 11:17:58 +01001547 call_py_exitfuncs(interp);
1548
Nick Coghland6009512014-11-20 21:39:37 +10001549 if (tstate != interp->tstate_head || tstate->next != NULL)
1550 Py_FatalError("Py_EndInterpreter: not the last thread");
1551
1552 PyImport_Cleanup();
1553 PyInterpreterState_Clear(interp);
1554 PyThreadState_Swap(NULL);
1555 PyInterpreterState_Delete(interp);
1556}
1557
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001558/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001559
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001560static _PyInitError
1561add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001562{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001563 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001564 m = PyImport_AddModule("__main__");
1565 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001566 return _Py_INIT_ERR("can't create __main__ module");
1567
Nick Coghland6009512014-11-20 21:39:37 +10001568 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001569 ann_dict = PyDict_New();
1570 if ((ann_dict == NULL) ||
1571 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001572 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001573 }
1574 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001575
Nick Coghland6009512014-11-20 21:39:37 +10001576 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1577 PyObject *bimod = PyImport_ImportModule("builtins");
1578 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001579 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001580 }
1581 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001582 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001583 }
1584 Py_DECREF(bimod);
1585 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001586
Nick Coghland6009512014-11-20 21:39:37 +10001587 /* Main is a little special - imp.is_builtin("__main__") will return
1588 * False, but BuiltinImporter is still the most appropriate initial
1589 * setting for its __loader__ attribute. A more suitable value will
1590 * be set if __main__ gets further initialized later in the startup
1591 * process.
1592 */
1593 loader = PyDict_GetItemString(d, "__loader__");
1594 if (loader == NULL || loader == Py_None) {
1595 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1596 "BuiltinImporter");
1597 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001598 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001599 }
1600 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001601 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001602 }
1603 Py_DECREF(loader);
1604 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001605 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001606}
1607
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001608static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001609initfsencoding(PyInterpreterState *interp)
1610{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001611 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001612
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001613 char *encoding = get_codec_name(config->filesystem_encoding);
1614 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001615 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001616 memory, import a module of the standard library failed, etc. */
1617 return _Py_INIT_ERR("failed to get the Python codec "
1618 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001619 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001620
1621 /* Update the filesystem encoding to the normalized Python codec name.
1622 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1623 (Python codec name). */
1624 PyMem_RawFree(config->filesystem_encoding);
1625 config->filesystem_encoding = encoding;
1626
1627 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1628 global configuration variables. */
1629 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1630 config->filesystem_errors) < 0) {
1631 return _Py_INIT_NO_MEMORY();
1632 }
1633
1634 /* PyUnicode can now use the Python codec rather than C implementation
1635 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001636 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001637 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001638}
1639
1640/* Import the site module (not into __main__ though) */
1641
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001642static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001643initsite(void)
1644{
1645 PyObject *m;
1646 m = PyImport_ImportModule("site");
1647 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001648 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001649 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001650 Py_DECREF(m);
1651 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001652}
1653
Victor Stinner874dbe82015-09-04 17:29:57 +02001654/* Check if a file descriptor is valid or not.
1655 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1656static int
1657is_valid_fd(int fd)
1658{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001659#ifdef __APPLE__
1660 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1661 and the other side of the pipe is closed, dup(1) succeed, whereas
1662 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1663 such error. */
1664 struct stat st;
1665 return (fstat(fd, &st) == 0);
1666#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001667 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001668 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001669 return 0;
1670 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001671 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1672 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1673 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001674 fd2 = dup(fd);
1675 if (fd2 >= 0)
1676 close(fd2);
1677 _Py_END_SUPPRESS_IPH
1678 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001679#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001680}
1681
1682/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001683static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001684create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001685 int fd, int write_mode, const char* name,
1686 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001687{
1688 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1689 const char* mode;
1690 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001691 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001692 int buffering, isatty;
1693 _Py_IDENTIFIER(open);
1694 _Py_IDENTIFIER(isatty);
1695 _Py_IDENTIFIER(TextIOWrapper);
1696 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001697 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001698
Victor Stinner874dbe82015-09-04 17:29:57 +02001699 if (!is_valid_fd(fd))
1700 Py_RETURN_NONE;
1701
Nick Coghland6009512014-11-20 21:39:37 +10001702 /* stdin is always opened in buffered mode, first because it shouldn't
1703 make a difference in common use cases, second because TextIOWrapper
1704 depends on the presence of a read1() method which only exists on
1705 buffered streams.
1706 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001707 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001708 buffering = 0;
1709 else
1710 buffering = -1;
1711 if (write_mode)
1712 mode = "wb";
1713 else
1714 mode = "rb";
1715 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1716 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001717 Py_None, Py_None, /* encoding, errors */
1718 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001719 if (buf == NULL)
1720 goto error;
1721
1722 if (buffering) {
1723 _Py_IDENTIFIER(raw);
1724 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1725 if (raw == NULL)
1726 goto error;
1727 }
1728 else {
1729 raw = buf;
1730 Py_INCREF(raw);
1731 }
1732
Steve Dower39294992016-08-30 21:22:36 -07001733#ifdef MS_WINDOWS
1734 /* Windows console IO is always UTF-8 encoded */
1735 if (PyWindowsConsoleIO_Check(raw))
1736 encoding = "utf-8";
1737#endif
1738
Nick Coghland6009512014-11-20 21:39:37 +10001739 text = PyUnicode_FromString(name);
1740 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1741 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001742 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001743 if (res == NULL)
1744 goto error;
1745 isatty = PyObject_IsTrue(res);
1746 Py_DECREF(res);
1747 if (isatty == -1)
1748 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001749 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001750 write_through = Py_True;
1751 else
1752 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001753 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001754 line_buffering = Py_True;
1755 else
1756 line_buffering = Py_False;
1757
1758 Py_CLEAR(raw);
1759 Py_CLEAR(text);
1760
1761#ifdef MS_WINDOWS
1762 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1763 newlines to "\n".
1764 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1765 newline = NULL;
1766#else
1767 /* sys.stdin: split lines at "\n".
1768 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1769 newline = "\n";
1770#endif
1771
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001772 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001773 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001774 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001775 Py_CLEAR(buf);
1776 if (stream == NULL)
1777 goto error;
1778
1779 if (write_mode)
1780 mode = "w";
1781 else
1782 mode = "r";
1783 text = PyUnicode_FromString(mode);
1784 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1785 goto error;
1786 Py_CLEAR(text);
1787 return stream;
1788
1789error:
1790 Py_XDECREF(buf);
1791 Py_XDECREF(stream);
1792 Py_XDECREF(text);
1793 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001794
Victor Stinner874dbe82015-09-04 17:29:57 +02001795 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1796 /* Issue #24891: the file descriptor was closed after the first
1797 is_valid_fd() check was called. Ignore the OSError and set the
1798 stream to None. */
1799 PyErr_Clear();
1800 Py_RETURN_NONE;
1801 }
1802 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001803}
1804
1805/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001806static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001807init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001808{
1809 PyObject *iomod = NULL, *wrapper;
1810 PyObject *bimod = NULL;
1811 PyObject *m;
1812 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001813 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001814 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001815 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001816 _PyCoreConfig *config = &interp->core_config;
1817
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001818 /* Check that stdin is not a directory
1819 Using shell redirection, you can redirect stdin to a directory,
1820 crashing the Python interpreter. Catch this common mistake here
1821 and output a useful error message. Note that under MS Windows,
1822 the shell already prevents that. */
1823#ifndef MS_WINDOWS
1824 struct _Py_stat_struct sb;
1825 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1826 S_ISDIR(sb.st_mode)) {
1827 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1828 "cannot continue");
1829 }
1830#endif
1831
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001832 char *codec_name = get_codec_name(config->stdio_encoding);
1833 if (codec_name == NULL) {
1834 return _Py_INIT_ERR("failed to get the Python codec name "
1835 "of the stdio encoding");
1836 }
1837 PyMem_RawFree(config->stdio_encoding);
1838 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001839
1840 /* Hack to avoid a nasty recursion issue when Python is invoked
1841 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1842 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1843 goto error;
1844 }
1845 Py_DECREF(m);
1846
1847 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1848 goto error;
1849 }
1850 Py_DECREF(m);
1851
1852 if (!(bimod = PyImport_ImportModule("builtins"))) {
1853 goto error;
1854 }
1855
1856 if (!(iomod = PyImport_ImportModule("io"))) {
1857 goto error;
1858 }
1859 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1860 goto error;
1861 }
1862
1863 /* Set builtins.open */
1864 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1865 Py_DECREF(wrapper);
1866 goto error;
1867 }
1868 Py_DECREF(wrapper);
1869
Nick Coghland6009512014-11-20 21:39:37 +10001870 /* Set sys.stdin */
1871 fd = fileno(stdin);
1872 /* Under some conditions stdin, stdout and stderr may not be connected
1873 * and fileno() may point to an invalid file descriptor. For example
1874 * GUI apps don't have valid standard streams by default.
1875 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001876 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001877 config->stdio_encoding,
1878 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001879 if (std == NULL)
1880 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001881 PySys_SetObject("__stdin__", std);
1882 _PySys_SetObjectId(&PyId_stdin, std);
1883 Py_DECREF(std);
1884
1885 /* Set sys.stdout */
1886 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001887 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001888 config->stdio_encoding,
1889 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001890 if (std == NULL)
1891 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001892 PySys_SetObject("__stdout__", std);
1893 _PySys_SetObjectId(&PyId_stdout, std);
1894 Py_DECREF(std);
1895
1896#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1897 /* Set sys.stderr, replaces the preliminary stderr */
1898 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001899 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001900 config->stdio_encoding,
1901 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001902 if (std == NULL)
1903 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001904
1905 /* Same as hack above, pre-import stderr's codec to avoid recursion
1906 when import.c tries to write to stderr in verbose mode. */
1907 encoding_attr = PyObject_GetAttrString(std, "encoding");
1908 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001909 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001910 if (std_encoding != NULL) {
1911 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1912 Py_XDECREF(codec_info);
1913 }
1914 Py_DECREF(encoding_attr);
1915 }
1916 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1917
1918 if (PySys_SetObject("__stderr__", std) < 0) {
1919 Py_DECREF(std);
1920 goto error;
1921 }
1922 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1923 Py_DECREF(std);
1924 goto error;
1925 }
1926 Py_DECREF(std);
1927#endif
1928
Victor Stinnera7368ac2017-11-15 18:11:45 -08001929 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001930
Victor Stinnera7368ac2017-11-15 18:11:45 -08001931error:
1932 res = _Py_INIT_ERR("can't initialize sys standard streams");
1933
1934done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001935 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001936
Nick Coghland6009512014-11-20 21:39:37 +10001937 Py_XDECREF(bimod);
1938 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001939 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001940}
1941
1942
Victor Stinner10dc4842015-03-24 12:01:30 +01001943static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001944_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001945{
Victor Stinner10dc4842015-03-24 12:01:30 +01001946 fputc('\n', stderr);
1947 fflush(stderr);
1948
1949 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001950 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001951}
Victor Stinner791da1c2016-03-14 16:53:12 +01001952
1953/* Print the current exception (if an exception is set) with its traceback,
1954 or display the current Python stack.
1955
1956 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1957 called on catastrophic cases.
1958
1959 Return 1 if the traceback was displayed, 0 otherwise. */
1960
1961static int
1962_Py_FatalError_PrintExc(int fd)
1963{
1964 PyObject *ferr, *res;
1965 PyObject *exception, *v, *tb;
1966 int has_tb;
1967
Victor Stinner791da1c2016-03-14 16:53:12 +01001968 PyErr_Fetch(&exception, &v, &tb);
1969 if (exception == NULL) {
1970 /* No current exception */
1971 return 0;
1972 }
1973
1974 ferr = _PySys_GetObjectId(&PyId_stderr);
1975 if (ferr == NULL || ferr == Py_None) {
1976 /* sys.stderr is not set yet or set to None,
1977 no need to try to display the exception */
1978 return 0;
1979 }
1980
1981 PyErr_NormalizeException(&exception, &v, &tb);
1982 if (tb == NULL) {
1983 tb = Py_None;
1984 Py_INCREF(tb);
1985 }
1986 PyException_SetTraceback(v, tb);
1987 if (exception == NULL) {
1988 /* PyErr_NormalizeException() failed */
1989 return 0;
1990 }
1991
1992 has_tb = (tb != Py_None);
1993 PyErr_Display(exception, v, tb);
1994 Py_XDECREF(exception);
1995 Py_XDECREF(v);
1996 Py_XDECREF(tb);
1997
1998 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001999 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002000 if (res == NULL)
2001 PyErr_Clear();
2002 else
2003 Py_DECREF(res);
2004
2005 return has_tb;
2006}
2007
Nick Coghland6009512014-11-20 21:39:37 +10002008/* Print fatal error message and abort */
2009
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002010#ifdef MS_WINDOWS
2011static void
2012fatal_output_debug(const char *msg)
2013{
2014 /* buffer of 256 bytes allocated on the stack */
2015 WCHAR buffer[256 / sizeof(WCHAR)];
2016 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2017 size_t msglen;
2018
2019 OutputDebugStringW(L"Fatal Python error: ");
2020
2021 msglen = strlen(msg);
2022 while (msglen) {
2023 size_t i;
2024
2025 if (buflen > msglen) {
2026 buflen = msglen;
2027 }
2028
2029 /* Convert the message to wchar_t. This uses a simple one-to-one
2030 conversion, assuming that the this error message actually uses
2031 ASCII only. If this ceases to be true, we will have to convert. */
2032 for (i=0; i < buflen; ++i) {
2033 buffer[i] = msg[i];
2034 }
2035 buffer[i] = L'\0';
2036 OutputDebugStringW(buffer);
2037
2038 msg += buflen;
2039 msglen -= buflen;
2040 }
2041 OutputDebugStringW(L"\n");
2042}
2043#endif
2044
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002045static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002046fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002047{
2048 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002049 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002050
2051 if (reentrant) {
2052 /* Py_FatalError() caused a second fatal error.
2053 Example: flush_std_files() raises a recursion error. */
2054 goto exit;
2055 }
2056 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002057
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002058 fprintf(stderr, "Fatal Python error: ");
2059 if (prefix) {
2060 fputs(prefix, stderr);
2061 fputs(": ", stderr);
2062 }
2063 if (msg) {
2064 fputs(msg, stderr);
2065 }
2066 else {
2067 fprintf(stderr, "<message not set>");
2068 }
2069 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002070 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002071
Victor Stinner3a228ab2018-11-01 00:26:41 +01002072 /* Check if the current thread has a Python thread state
2073 and holds the GIL */
2074 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2075 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002076 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002077 if (tss_tstate != tstate) {
2078 /* The Python thread does not hold the GIL */
2079 tss_tstate = NULL;
2080 }
2081 }
2082 else {
2083 /* Py_FatalError() has been called from a C thread
2084 which has no Python thread state. */
2085 }
2086 int has_tstate_and_gil = (tss_tstate != NULL);
2087
2088 if (has_tstate_and_gil) {
2089 /* If an exception is set, print the exception with its traceback */
2090 if (!_Py_FatalError_PrintExc(fd)) {
2091 /* No exception is set, or an exception is set without traceback */
2092 _Py_FatalError_DumpTracebacks(fd);
2093 }
2094 }
2095 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002096 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002097 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002098
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002099 /* The main purpose of faulthandler is to display the traceback.
2100 This function already did its best to display a traceback.
2101 Disable faulthandler to prevent writing a second traceback
2102 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002103 _PyFaulthandler_Fini();
2104
Victor Stinner791da1c2016-03-14 16:53:12 +01002105 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002106 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002107 /* Flush sys.stdout and sys.stderr */
2108 flush_std_files();
2109 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002110
Nick Coghland6009512014-11-20 21:39:37 +10002111#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002112 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002113#endif /* MS_WINDOWS */
2114
2115exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002116 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002117#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002118 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002119#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002120 abort();
2121 }
2122 else {
2123 exit(status);
2124 }
2125}
2126
Victor Stinner19760862017-12-20 01:41:59 +01002127void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002128Py_FatalError(const char *msg)
2129{
2130 fatal_error(NULL, msg, -1);
2131}
2132
Victor Stinner19760862017-12-20 01:41:59 +01002133void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002134_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002135{
Victor Stinnerdfe88472019-03-01 12:14:41 +01002136 if (err.exitcode >= 0) {
2137 exit(err.exitcode);
2138 }
2139 else {
2140 /* On "user" error: exit with status 1.
2141 For all other errors, call abort(). */
2142 int status = err.user_err ? 1 : -1;
2143 fatal_error(err.prefix, err.msg, status);
2144 }
Nick Coghland6009512014-11-20 21:39:37 +10002145}
2146
2147/* Clean up and exit */
2148
Victor Stinnerd7292b52016-06-17 12:29:00 +02002149# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002150
Nick Coghland6009512014-11-20 21:39:37 +10002151/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002152void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002153{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002154 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002155
Antoine Pitroufc5db952017-12-13 02:29:07 +01002156 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002157 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2158
2159 is->pyexitfunc = func;
2160 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002161}
2162
2163static void
Marcel Plch776407f2017-12-20 11:17:58 +01002164call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002165{
Marcel Plch776407f2017-12-20 11:17:58 +01002166 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002167 return;
2168
Marcel Plch776407f2017-12-20 11:17:58 +01002169 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002170 PyErr_Clear();
2171}
2172
2173/* Wait until threading._shutdown completes, provided
2174 the threading module was imported in the first place.
2175 The shutdown routine will wait until all non-daemon
2176 "threading" threads have completed. */
2177static void
2178wait_for_thread_shutdown(void)
2179{
Nick Coghland6009512014-11-20 21:39:37 +10002180 _Py_IDENTIFIER(_shutdown);
2181 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002182 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002183 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002184 if (PyErr_Occurred()) {
2185 PyErr_WriteUnraisable(NULL);
2186 }
2187 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002188 return;
2189 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002190 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002191 if (result == NULL) {
2192 PyErr_WriteUnraisable(threading);
2193 }
2194 else {
2195 Py_DECREF(result);
2196 }
2197 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002198}
2199
2200#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002201int Py_AtExit(void (*func)(void))
2202{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002203 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002204 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002205 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002206 return 0;
2207}
2208
2209static void
2210call_ll_exitfuncs(void)
2211{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002212 while (_PyRuntime.nexitfuncs > 0)
2213 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002214
2215 fflush(stdout);
2216 fflush(stderr);
2217}
2218
Victor Stinnercfc88312018-08-01 16:41:25 +02002219void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002220Py_Exit(int sts)
2221{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002222 if (Py_FinalizeEx() < 0) {
2223 sts = 120;
2224 }
Nick Coghland6009512014-11-20 21:39:37 +10002225
2226 exit(sts);
2227}
2228
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002229static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002230initsigs(void)
2231{
2232#ifdef SIGPIPE
2233 PyOS_setsig(SIGPIPE, SIG_IGN);
2234#endif
2235#ifdef SIGXFZ
2236 PyOS_setsig(SIGXFZ, SIG_IGN);
2237#endif
2238#ifdef SIGXFSZ
2239 PyOS_setsig(SIGXFSZ, SIG_IGN);
2240#endif
2241 PyOS_InitInterrupts(); /* May imply initsignal() */
2242 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002243 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002244 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002245 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002246}
2247
2248
2249/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2250 *
2251 * All of the code in this function must only use async-signal-safe functions,
2252 * listed at `man 7 signal` or
2253 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2254 */
2255void
2256_Py_RestoreSignals(void)
2257{
2258#ifdef SIGPIPE
2259 PyOS_setsig(SIGPIPE, SIG_DFL);
2260#endif
2261#ifdef SIGXFZ
2262 PyOS_setsig(SIGXFZ, SIG_DFL);
2263#endif
2264#ifdef SIGXFSZ
2265 PyOS_setsig(SIGXFSZ, SIG_DFL);
2266#endif
2267}
2268
2269
2270/*
2271 * The file descriptor fd is considered ``interactive'' if either
2272 * a) isatty(fd) is TRUE, or
2273 * b) the -i flag was given, and the filename associated with
2274 * the descriptor is NULL or "<stdin>" or "???".
2275 */
2276int
2277Py_FdIsInteractive(FILE *fp, const char *filename)
2278{
2279 if (isatty((int)fileno(fp)))
2280 return 1;
2281 if (!Py_InteractiveFlag)
2282 return 0;
2283 return (filename == NULL) ||
2284 (strcmp(filename, "<stdin>") == 0) ||
2285 (strcmp(filename, "???") == 0);
2286}
2287
2288
Nick Coghland6009512014-11-20 21:39:37 +10002289/* Wrappers around sigaction() or signal(). */
2290
2291PyOS_sighandler_t
2292PyOS_getsig(int sig)
2293{
2294#ifdef HAVE_SIGACTION
2295 struct sigaction context;
2296 if (sigaction(sig, NULL, &context) == -1)
2297 return SIG_ERR;
2298 return context.sa_handler;
2299#else
2300 PyOS_sighandler_t handler;
2301/* Special signal handling for the secure CRT in Visual Studio 2005 */
2302#if defined(_MSC_VER) && _MSC_VER >= 1400
2303 switch (sig) {
2304 /* Only these signals are valid */
2305 case SIGINT:
2306 case SIGILL:
2307 case SIGFPE:
2308 case SIGSEGV:
2309 case SIGTERM:
2310 case SIGBREAK:
2311 case SIGABRT:
2312 break;
2313 /* Don't call signal() with other values or it will assert */
2314 default:
2315 return SIG_ERR;
2316 }
2317#endif /* _MSC_VER && _MSC_VER >= 1400 */
2318 handler = signal(sig, SIG_IGN);
2319 if (handler != SIG_ERR)
2320 signal(sig, handler);
2321 return handler;
2322#endif
2323}
2324
2325/*
2326 * All of the code in this function must only use async-signal-safe functions,
2327 * listed at `man 7 signal` or
2328 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2329 */
2330PyOS_sighandler_t
2331PyOS_setsig(int sig, PyOS_sighandler_t handler)
2332{
2333#ifdef HAVE_SIGACTION
2334 /* Some code in Modules/signalmodule.c depends on sigaction() being
2335 * used here if HAVE_SIGACTION is defined. Fix that if this code
2336 * changes to invalidate that assumption.
2337 */
2338 struct sigaction context, ocontext;
2339 context.sa_handler = handler;
2340 sigemptyset(&context.sa_mask);
2341 context.sa_flags = 0;
2342 if (sigaction(sig, &context, &ocontext) == -1)
2343 return SIG_ERR;
2344 return ocontext.sa_handler;
2345#else
2346 PyOS_sighandler_t oldhandler;
2347 oldhandler = signal(sig, handler);
2348#ifdef HAVE_SIGINTERRUPT
2349 siginterrupt(sig, 1);
2350#endif
2351 return oldhandler;
2352#endif
2353}
2354
2355#ifdef __cplusplus
2356}
2357#endif