blob: 57b0c3215b7da46dd6bd202d5fe9374f9c2b6240 [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 Stinner1dc6e392018-07-25 02:49:17 +0200461 Every call to _Py_InitializeCore, 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 Stinnera6fbc4e2019-03-25 18:37:10 +0100721pyinit_preinit(_PyPreConfig *config,
722 const _PyPreConfig *src_config,
723 const _PyCoreConfig *coreconfig)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100724{
725 _PyInitError err;
Victor Stinner20004952019-03-26 02:31:11 +0100726 _PyPreConfig local_config = _PyPreConfig_INIT;
727 if (!config) {
728 config = &local_config;
729 }
Victor Stinnerf29084d2019-03-20 02:20:13 +0100730
731 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100732 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100733 goto done;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100734 }
735
Victor Stinnerf72346c2019-03-25 17:54:58 +0100736 if (_PyRuntime.pre_initialized) {
737 /* If it's already configured: ignored the new configuration */
Victor Stinner20004952019-03-26 02:31:11 +0100738 err = _Py_INIT_OK();
739 goto done;
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100740 }
741
Victor Stinnerf72346c2019-03-25 17:54:58 +0100742 if (src_config) {
743 if (_PyPreConfig_Copy(config, src_config) < 0) {
Victor Stinner20004952019-03-26 02:31:11 +0100744 err = _Py_INIT_ERR("failed to copy pre config");
745 goto done;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100746 }
747 }
748
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100749 err = _PyPreConfig_Read(config, NULL, coreconfig);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100750 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100751 goto done;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100752 }
753
Victor Stinnerf72346c2019-03-25 17:54:58 +0100754 err = _PyPreConfig_Write(config);
755 if (_Py_INIT_FAILED(err)) {
Victor Stinner20004952019-03-26 02:31:11 +0100756 goto done;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100757 }
758
759 _PyRuntime.pre_initialized = 1;
Victor Stinner20004952019-03-26 02:31:11 +0100760 err = _Py_INIT_OK();
761
762done:
763 _PyPreConfig_Clear(&local_config);
764 return err;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100765}
766
767
768_PyInitError
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100769_Py_PreInitialize(void)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100770{
Victor Stinner20004952019-03-26 02:31:11 +0100771 return pyinit_preinit(NULL, NULL, NULL);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100772}
773
774
775_PyInitError
Victor Stinner20004952019-03-26 02:31:11 +0100776_Py_PreInitializeFromPreConfig(const _PyPreConfig *src_config)
777{
778 return pyinit_preinit(NULL, src_config, NULL);
779}
780
781
782_PyInitError
783_Py_PreInitializeInPlace(_PyPreConfig *config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100784{
785 return pyinit_preinit(config, NULL, NULL);
786}
787
788
789_PyInitError
790_Py_PreInitializeFromConfig(const _PyCoreConfig *coreconfig)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100791{
Victor Stinner20004952019-03-26 02:31:11 +0100792 return pyinit_preinit(NULL, NULL, coreconfig);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100793}
794
795
796static _PyInitError
797pyinit_coreconfig(_PyCoreConfig *config, const _PyCoreConfig *src_config,
798 PyInterpreterState **interp_p)
799{
Victor Stinnerc656e252019-03-06 01:13:43 +0100800 if (_PyCoreConfig_Copy(config, src_config) < 0) {
801 return _Py_INIT_ERR("failed to copy core config");
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100802 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100803
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100804 _PyInitError err = _PyCoreConfig_Read(config, NULL);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100805 if (_Py_INIT_FAILED(err)) {
806 return err;
807 }
808
809 if (!_PyRuntime.core_initialized) {
810 return _Py_InitializeCore_impl(interp_p, config);
811 }
812 else {
813 return _Py_Initialize_ReconfigureCore(interp_p, config);
814 }
815}
816
817
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100818/* Begin interpreter initialization
819 *
820 * On return, the first thread and interpreter state have been created,
821 * but the compiler, signal handling, multithreading and
822 * multiple interpreter support, and codec infrastructure are not yet
823 * available.
824 *
825 * The import system will support builtin and frozen modules only.
826 * The only supported io is writing to sys.stderr
827 *
828 * If any operation invoked by this function fails, a fatal error is
829 * issued and the function does not return.
830 *
831 * Any code invoked from this function should *not* assume it has access
832 * to the Python C API (unless the API is explicitly listed as being
833 * safe to call without calling Py_Initialize first)
834 */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200835_PyInitError
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100836_Py_InitializeCore(const _PyCoreConfig *src_config,
837 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200838{
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100839 assert(src_config != NULL);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200840
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100841 _PyInitError err = _Py_PreInitializeFromConfig(src_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200842 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100843 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200844 }
845
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100846 _PyCoreConfig local_config = _PyCoreConfig_INIT;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100847 err = pyinit_coreconfig(&local_config, src_config, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100848 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200849 return err;
850}
851
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200852/* Py_Initialize() has already been called: update the main interpreter
853 configuration. Example of bpo-34008: Py_Main() called after
854 Py_Initialize(). */
855static _PyInitError
856_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
857 const _PyMainInterpreterConfig *config)
858{
859 if (config->argv != NULL) {
860 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
861 if (res < 0) {
862 return _Py_INIT_ERR("fail to set sys.argv");
863 }
864 }
865 return _Py_INIT_OK();
866}
867
Eric Snowc7ec9982017-05-23 23:00:52 -0700868/* Update interpreter state based on supplied configuration settings
869 *
870 * After calling this function, most of the restrictions on the interpreter
871 * are lifted. The only remaining incomplete settings are those related
872 * to the main module (sys.argv[0], __main__ metadata)
873 *
874 * Calling this when the interpreter is not initializing, is already
875 * initialized or without a valid current thread state is a fatal error.
876 * Other errors should be reported as normal Python exceptions with a
877 * non-zero return code.
878 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800879_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200880_Py_InitializeMainInterpreter(PyInterpreterState *interp,
881 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700882{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600883 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800884 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700885 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700886
Victor Stinner1dc6e392018-07-25 02:49:17 +0200887 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100888 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
889 return _Py_INIT_ERR("failed to copy main interpreter config");
890 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200891 config = &interp->config;
892 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700893
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200894 if (_PyRuntime.initialized) {
895 return _Py_ReconfigureMainInterpreter(interp, config);
896 }
897
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200898 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700899 /* Special mode for freeze_importlib: run with no import system
900 *
901 * This means anything which needs support from extension modules
902 * or pure Python code in the standard library won't work.
903 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600904 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800905 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700906 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100907
Victor Stinner33c377e2017-12-05 15:12:41 +0100908 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800909 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100910 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200911
Victor Stinnerab672812019-01-23 15:04:40 +0100912 if (_PySys_InitMain(interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100914 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800915
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200916 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800917 if (_Py_INIT_FAILED(err)) {
918 return err;
919 }
Nick Coghland6009512014-11-20 21:39:37 +1000920
921 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200922 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800923 if (_Py_INIT_FAILED(err)) {
924 return err;
925 }
Nick Coghland6009512014-11-20 21:39:37 +1000926
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927 err = initfsencoding(interp);
928 if (_Py_INIT_FAILED(err)) {
929 return err;
930 }
Nick Coghland6009512014-11-20 21:39:37 +1000931
Victor Stinner1f151112017-11-23 10:43:14 +0100932 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800933 err = initsigs(); /* Signal handling stuff, including initintr() */
934 if (_Py_INIT_FAILED(err)) {
935 return err;
936 }
937 }
Nick Coghland6009512014-11-20 21:39:37 +1000938
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200939 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800940 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200941 }
Nick Coghland6009512014-11-20 21:39:37 +1000942
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800943 err = add_main_module(interp);
944 if (_Py_INIT_FAILED(err)) {
945 return err;
946 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800947
Victor Stinner91106cd2017-12-13 12:29:09 +0100948 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800949 if (_Py_INIT_FAILED(err)) {
950 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800951 }
Nick Coghland6009512014-11-20 21:39:37 +1000952
953 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100954 PyObject *warnoptions = PySys_GetObject("warnoptions");
955 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100956 {
Nick Coghland6009512014-11-20 21:39:37 +1000957 PyObject *warnings_module = PyImport_ImportModule("warnings");
958 if (warnings_module == NULL) {
959 fprintf(stderr, "'import warnings' failed; traceback:\n");
960 PyErr_Print();
961 }
962 Py_XDECREF(warnings_module);
963 }
964
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600965 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700966
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200967 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800968 err = initsite(); /* Module site */
969 if (_Py_INIT_FAILED(err)) {
970 return err;
971 }
972 }
Victor Stinnercf215042018-08-29 22:56:06 +0200973
974#ifndef MS_WINDOWS
Victor Stinner20004952019-03-26 02:31:11 +0100975 _emit_stderr_warning_for_legacy_locale();
Victor Stinnercf215042018-08-29 22:56:06 +0200976#endif
977
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800978 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000979}
980
Eric Snowc7ec9982017-05-23 23:00:52 -0700981#undef _INIT_DEBUG_PRINT
982
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800983_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200984_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700985{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700986 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800987 _PyInitError err;
Victor Stinnerf8ba6f52019-03-26 16:58:50 +0100988 err = _Py_InitializeCore(config, &interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800989 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200990 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800991 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200992 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100993
Victor Stinner9cfc0022017-12-20 19:36:46 +0100994 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200995 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100996 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200997 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800998 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100999 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001000 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001001 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001002 }
Victor Stinner1dc6e392018-07-25 02:49:17 +02001003 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001004}
1005
1006
1007void
Nick Coghland6009512014-11-20 21:39:37 +10001008Py_InitializeEx(int install_sigs)
1009{
Victor Stinner1dc6e392018-07-25 02:49:17 +02001010 if (_PyRuntime.initialized) {
1011 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1012 return;
1013 }
1014
1015 _PyInitError err;
1016 _PyCoreConfig config = _PyCoreConfig_INIT;
1017 config.install_signal_handlers = install_sigs;
1018
1019 err = _Py_InitializeFromConfig(&config);
1020 _PyCoreConfig_Clear(&config);
1021
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001022 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001023 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001024 }
Nick Coghland6009512014-11-20 21:39:37 +10001025}
1026
1027void
1028Py_Initialize(void)
1029{
1030 Py_InitializeEx(1);
1031}
1032
1033
1034#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001035extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001036#endif
1037
1038/* Flush stdout and stderr */
1039
1040static int
1041file_is_closed(PyObject *fobj)
1042{
1043 int r;
1044 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1045 if (tmp == NULL) {
1046 PyErr_Clear();
1047 return 0;
1048 }
1049 r = PyObject_IsTrue(tmp);
1050 Py_DECREF(tmp);
1051 if (r < 0)
1052 PyErr_Clear();
1053 return r > 0;
1054}
1055
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001056static int
Nick Coghland6009512014-11-20 21:39:37 +10001057flush_std_files(void)
1058{
1059 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1060 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1061 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001062 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001063
1064 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001065 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001066 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001067 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001068 status = -1;
1069 }
Nick Coghland6009512014-11-20 21:39:37 +10001070 else
1071 Py_DECREF(tmp);
1072 }
1073
1074 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001075 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001076 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001077 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001078 status = -1;
1079 }
Nick Coghland6009512014-11-20 21:39:37 +10001080 else
1081 Py_DECREF(tmp);
1082 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001083
1084 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001085}
1086
1087/* Undo the effect of Py_Initialize().
1088
1089 Beware: if multiple interpreter and/or thread states exist, these
1090 are not wiped out; only the current thread and interpreter state
1091 are deleted. But since everything else is deleted, those other
1092 interpreter and thread states should no longer be used.
1093
1094 (XXX We should do better, e.g. wipe out all interpreters and
1095 threads.)
1096
1097 Locking: as above.
1098
1099*/
1100
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001101int
1102Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001103{
1104 PyInterpreterState *interp;
1105 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001106 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001107
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001108 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001109 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001110
Eric Snow842a2f02019-03-15 15:47:51 -06001111 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001112 wait_for_thread_shutdown();
1113
Marcel Plch776407f2017-12-20 11:17:58 +01001114 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001115 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001116 interp = tstate->interp;
1117
Eric Snow842a2f02019-03-15 15:47:51 -06001118 // Make any remaining pending calls.
1119 _Py_FinishPendingCalls();
1120
Nick Coghland6009512014-11-20 21:39:37 +10001121 /* The interpreter is still entirely intact at this point, and the
1122 * exit funcs may be relying on that. In particular, if some thread
1123 * or exit func is still waiting to do an import, the import machinery
1124 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001125 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001126 * Note that Threading.py uses an exit func to do a join on all the
1127 * threads created thru it, so this also protects pending imports in
1128 * the threads created via Threading.
1129 */
Nick Coghland6009512014-11-20 21:39:37 +10001130
Marcel Plch776407f2017-12-20 11:17:58 +01001131 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001132
Victor Stinnerda273412017-12-15 01:46:02 +01001133 /* Copy the core config, PyInterpreterState_Delete() free
1134 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001135#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001136 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001137#endif
1138#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001139 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001140#endif
1141#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001142 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001143#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001144
Nick Coghland6009512014-11-20 21:39:37 +10001145 /* Remaining threads (e.g. daemon threads) will automatically exit
1146 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001147 _PyRuntime.finalizing = tstate;
1148 _PyRuntime.initialized = 0;
1149 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001150
Victor Stinnere0deff32015-03-24 13:46:18 +01001151 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001152 if (flush_std_files() < 0) {
1153 status = -1;
1154 }
Nick Coghland6009512014-11-20 21:39:37 +10001155
1156 /* Disable signal handling */
1157 PyOS_FiniInterrupts();
1158
1159 /* Collect garbage. This may call finalizers; it's nice to call these
1160 * before all modules are destroyed.
1161 * XXX If a __del__ or weakref callback is triggered here, and tries to
1162 * XXX import a module, bad things can happen, because Python no
1163 * XXX longer believes it's initialized.
1164 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1165 * XXX is easy to provoke that way. I've also seen, e.g.,
1166 * XXX Exception exceptions.ImportError: 'No module named sha'
1167 * XXX in <function callback at 0x008F5718> ignored
1168 * XXX but I'm unclear on exactly how that one happens. In any case,
1169 * XXX I haven't seen a real-life report of either of these.
1170 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001171 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001172#ifdef COUNT_ALLOCS
1173 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1174 each collection might release some types from the type
1175 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001176 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001177 /* nothing */;
1178#endif
Eric Snowdae02762017-09-14 00:35:58 -07001179
Nick Coghland6009512014-11-20 21:39:37 +10001180 /* Destroy all modules */
1181 PyImport_Cleanup();
1182
Victor Stinnere0deff32015-03-24 13:46:18 +01001183 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001184 if (flush_std_files() < 0) {
1185 status = -1;
1186 }
Nick Coghland6009512014-11-20 21:39:37 +10001187
1188 /* Collect final garbage. This disposes of cycles created by
1189 * class definitions, for example.
1190 * XXX This is disabled because it caused too many problems. If
1191 * XXX a __del__ or weakref callback triggers here, Python code has
1192 * XXX a hard time running, because even the sys module has been
1193 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1194 * XXX One symptom is a sequence of information-free messages
1195 * XXX coming from threads (if a __del__ or callback is invoked,
1196 * XXX other threads can execute too, and any exception they encounter
1197 * XXX triggers a comedy of errors as subsystem after subsystem
1198 * XXX fails to find what it *expects* to find in sys to help report
1199 * XXX the exception and consequent unexpected failures). I've also
1200 * XXX seen segfaults then, after adding print statements to the
1201 * XXX Python code getting called.
1202 */
1203#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001204 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001205#endif
1206
1207 /* Disable tracemalloc after all Python objects have been destroyed,
1208 so it is possible to use tracemalloc in objects destructor. */
1209 _PyTraceMalloc_Fini();
1210
1211 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1212 _PyImport_Fini();
1213
1214 /* Cleanup typeobject.c's internal caches. */
1215 _PyType_Fini();
1216
1217 /* unload faulthandler module */
1218 _PyFaulthandler_Fini();
1219
1220 /* Debugging stuff */
1221#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001222 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001223#endif
1224 /* dump hash stats */
1225 _PyHash_Fini();
1226
Eric Snowdae02762017-09-14 00:35:58 -07001227#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001228 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001229 _PyDebug_PrintTotalRefs();
1230 }
Eric Snowdae02762017-09-14 00:35:58 -07001231#endif
Nick Coghland6009512014-11-20 21:39:37 +10001232
1233#ifdef Py_TRACE_REFS
1234 /* Display all objects still alive -- this can invoke arbitrary
1235 * __repr__ overrides, so requires a mostly-intact interpreter.
1236 * Alas, a lot of stuff may still be alive now that will be cleaned
1237 * up later.
1238 */
Victor Stinnerda273412017-12-15 01:46:02 +01001239 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001240 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001241 }
Nick Coghland6009512014-11-20 21:39:37 +10001242#endif /* Py_TRACE_REFS */
1243
1244 /* Clear interpreter state and all thread states. */
1245 PyInterpreterState_Clear(interp);
1246
1247 /* Now we decref the exception classes. After this point nothing
1248 can raise an exception. That's okay, because each Fini() method
1249 below has been checked to make sure no exceptions are ever
1250 raised.
1251 */
1252
1253 _PyExc_Fini();
1254
1255 /* Sundry finalizers */
1256 PyMethod_Fini();
1257 PyFrame_Fini();
1258 PyCFunction_Fini();
1259 PyTuple_Fini();
1260 PyList_Fini();
1261 PySet_Fini();
1262 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001263 PyLong_Fini();
1264 PyFloat_Fini();
1265 PyDict_Fini();
1266 PySlice_Fini();
1267 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001268 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001269 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001270 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001271 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001272
1273 /* Cleanup Unicode implementation */
1274 _PyUnicode_Fini();
1275
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001276 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001277
1278 /* XXX Still allocated:
1279 - various static ad-hoc pointers to interned strings
1280 - int and float free list blocks
1281 - whatever various modules and libraries allocate
1282 */
1283
1284 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1285
1286 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001287 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001288
1289 /* Delete current thread. After this, many C API calls become crashy. */
1290 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001291
Nick Coghland6009512014-11-20 21:39:37 +10001292 PyInterpreterState_Delete(interp);
1293
1294#ifdef Py_TRACE_REFS
1295 /* Display addresses (& refcnts) of all objects still alive.
1296 * An address can be used to find the repr of the object, printed
1297 * above by _Py_PrintReferences.
1298 */
Victor Stinnerda273412017-12-15 01:46:02 +01001299 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001300 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001301 }
Nick Coghland6009512014-11-20 21:39:37 +10001302#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001303#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001304 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001305 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001306 }
Nick Coghland6009512014-11-20 21:39:37 +10001307#endif
1308
1309 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001310
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001311 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001312 return status;
1313}
1314
1315void
1316Py_Finalize(void)
1317{
1318 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001319}
1320
1321/* Create and initialize a new interpreter and thread, and return the
1322 new thread. This requires that Py_Initialize() has been called
1323 first.
1324
1325 Unsuccessful initialization yields a NULL pointer. Note that *no*
1326 exception information is available even in this case -- the
1327 exception information is held in the thread, and there is no
1328 thread.
1329
1330 Locking: as above.
1331
1332*/
1333
Victor Stinnera7368ac2017-11-15 18:11:45 -08001334static _PyInitError
1335new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001336{
1337 PyInterpreterState *interp;
1338 PyThreadState *tstate, *save_tstate;
1339 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001340 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001341
Victor Stinnera7368ac2017-11-15 18:11:45 -08001342 if (!_PyRuntime.initialized) {
1343 return _Py_INIT_ERR("Py_Initialize must be called first");
1344 }
Nick Coghland6009512014-11-20 21:39:37 +10001345
Victor Stinner8a1be612016-03-14 22:07:55 +01001346 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1347 interpreters: disable PyGILState_Check(). */
1348 _PyGILState_check_enabled = 0;
1349
Nick Coghland6009512014-11-20 21:39:37 +10001350 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001351 if (interp == NULL) {
1352 *tstate_p = NULL;
1353 return _Py_INIT_OK();
1354 }
Nick Coghland6009512014-11-20 21:39:37 +10001355
1356 tstate = PyThreadState_New(interp);
1357 if (tstate == NULL) {
1358 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001359 *tstate_p = NULL;
1360 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001361 }
1362
1363 save_tstate = PyThreadState_Swap(tstate);
1364
Eric Snow1abcf672017-05-23 21:46:51 -07001365 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001366 _PyCoreConfig *core_config;
1367 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001368 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001369 core_config = &save_tstate->interp->core_config;
1370 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001371 } else {
1372 /* No current thread state, copy from the main interpreter */
1373 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001374 core_config = &main_interp->core_config;
1375 config = &main_interp->config;
1376 }
1377
1378 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1379 return _Py_INIT_ERR("failed to copy core config");
1380 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001381 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001382 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1383 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001384 }
1385
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001386 err = _PyExc_Init();
1387 if (_Py_INIT_FAILED(err)) {
1388 return err;
1389 }
1390
Nick Coghland6009512014-11-20 21:39:37 +10001391 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001392 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001393 if (modules == NULL) {
1394 return _Py_INIT_ERR("can't make modules dictionary");
1395 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001396 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001397
Eric Snowd393c1b2017-09-14 12:18:12 -06001398 sysmod = _PyImport_FindBuiltin("sys", modules);
1399 if (sysmod != NULL) {
1400 interp->sysdict = PyModule_GetDict(sysmod);
1401 if (interp->sysdict == NULL)
1402 goto handle_error;
1403 Py_INCREF(interp->sysdict);
1404 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerab672812019-01-23 15:04:40 +01001405 if (_PySys_InitMain(interp) < 0) {
1406 return _Py_INIT_ERR("can't finish initializing sys");
1407 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001408 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001409 else if (PyErr_Occurred()) {
1410 goto handle_error;
1411 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001412
1413 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001414 if (bimod != NULL) {
1415 interp->builtins = PyModule_GetDict(bimod);
1416 if (interp->builtins == NULL)
1417 goto handle_error;
1418 Py_INCREF(interp->builtins);
1419 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001420 else if (PyErr_Occurred()) {
1421 goto handle_error;
1422 }
Nick Coghland6009512014-11-20 21:39:37 +10001423
Nick Coghland6009512014-11-20 21:39:37 +10001424 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001425 err = _PyBuiltins_AddExceptions(bimod);
1426 if (_Py_INIT_FAILED(err)) {
1427 return err;
1428 }
Nick Coghland6009512014-11-20 21:39:37 +10001429
Victor Stinnerab672812019-01-23 15:04:40 +01001430 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1431 if (_Py_INIT_FAILED(err)) {
1432 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001433 }
Nick Coghland6009512014-11-20 21:39:37 +10001434
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001435 err = _PyImportHooks_Init();
1436 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001437 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001438 }
Nick Coghland6009512014-11-20 21:39:37 +10001439
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001440 err = initimport(interp, sysmod);
1441 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001442 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001443 }
Nick Coghland6009512014-11-20 21:39:37 +10001444
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001445 err = initexternalimport(interp);
1446 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001447 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001448 }
Nick Coghland6009512014-11-20 21:39:37 +10001449
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001450 err = initfsencoding(interp);
1451 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001452 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001453 }
1454
Victor Stinner91106cd2017-12-13 12:29:09 +01001455 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001456 if (_Py_INIT_FAILED(err)) {
1457 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001458 }
1459
1460 err = add_main_module(interp);
1461 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001462 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001463 }
1464
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001465 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001466 err = initsite();
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 }
Nick Coghland6009512014-11-20 21:39:37 +10001471 }
1472
Victor Stinnera7368ac2017-11-15 18:11:45 -08001473 if (PyErr_Occurred()) {
1474 goto handle_error;
1475 }
Nick Coghland6009512014-11-20 21:39:37 +10001476
Victor Stinnera7368ac2017-11-15 18:11:45 -08001477 *tstate_p = tstate;
1478 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001479
Nick Coghland6009512014-11-20 21:39:37 +10001480handle_error:
1481 /* Oops, it didn't work. Undo it all. */
1482
1483 PyErr_PrintEx(0);
1484 PyThreadState_Clear(tstate);
1485 PyThreadState_Swap(save_tstate);
1486 PyThreadState_Delete(tstate);
1487 PyInterpreterState_Delete(interp);
1488
Victor Stinnera7368ac2017-11-15 18:11:45 -08001489 *tstate_p = NULL;
1490 return _Py_INIT_OK();
1491}
1492
1493PyThreadState *
1494Py_NewInterpreter(void)
1495{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001496 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001497 _PyInitError err = new_interpreter(&tstate);
1498 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001499 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001500 }
1501 return tstate;
1502
Nick Coghland6009512014-11-20 21:39:37 +10001503}
1504
1505/* Delete an interpreter and its last thread. This requires that the
1506 given thread state is current, that the thread has no remaining
1507 frames, and that it is its interpreter's only remaining thread.
1508 It is a fatal error to violate these constraints.
1509
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001510 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001511 everything, regardless.)
1512
1513 Locking: as above.
1514
1515*/
1516
1517void
1518Py_EndInterpreter(PyThreadState *tstate)
1519{
1520 PyInterpreterState *interp = tstate->interp;
1521
Victor Stinner50b48572018-11-01 01:51:40 +01001522 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001523 Py_FatalError("Py_EndInterpreter: thread is not current");
1524 if (tstate->frame != NULL)
1525 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001526 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001527
Eric Snow842a2f02019-03-15 15:47:51 -06001528 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001529 wait_for_thread_shutdown();
1530
Marcel Plch776407f2017-12-20 11:17:58 +01001531 call_py_exitfuncs(interp);
1532
Nick Coghland6009512014-11-20 21:39:37 +10001533 if (tstate != interp->tstate_head || tstate->next != NULL)
1534 Py_FatalError("Py_EndInterpreter: not the last thread");
1535
1536 PyImport_Cleanup();
1537 PyInterpreterState_Clear(interp);
1538 PyThreadState_Swap(NULL);
1539 PyInterpreterState_Delete(interp);
1540}
1541
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001542/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001543
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001544static _PyInitError
1545add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001546{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001547 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001548 m = PyImport_AddModule("__main__");
1549 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001550 return _Py_INIT_ERR("can't create __main__ module");
1551
Nick Coghland6009512014-11-20 21:39:37 +10001552 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001553 ann_dict = PyDict_New();
1554 if ((ann_dict == NULL) ||
1555 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001556 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001557 }
1558 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001559
Nick Coghland6009512014-11-20 21:39:37 +10001560 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1561 PyObject *bimod = PyImport_ImportModule("builtins");
1562 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001563 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001564 }
1565 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001566 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001567 }
1568 Py_DECREF(bimod);
1569 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001570
Nick Coghland6009512014-11-20 21:39:37 +10001571 /* Main is a little special - imp.is_builtin("__main__") will return
1572 * False, but BuiltinImporter is still the most appropriate initial
1573 * setting for its __loader__ attribute. A more suitable value will
1574 * be set if __main__ gets further initialized later in the startup
1575 * process.
1576 */
1577 loader = PyDict_GetItemString(d, "__loader__");
1578 if (loader == NULL || loader == Py_None) {
1579 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1580 "BuiltinImporter");
1581 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001582 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001583 }
1584 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001585 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001586 }
1587 Py_DECREF(loader);
1588 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001589 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001590}
1591
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001592static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001593initfsencoding(PyInterpreterState *interp)
1594{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001595 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001596
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001597 char *encoding = get_codec_name(config->filesystem_encoding);
1598 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001599 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001600 memory, import a module of the standard library failed, etc. */
1601 return _Py_INIT_ERR("failed to get the Python codec "
1602 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001603 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001604
1605 /* Update the filesystem encoding to the normalized Python codec name.
1606 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1607 (Python codec name). */
1608 PyMem_RawFree(config->filesystem_encoding);
1609 config->filesystem_encoding = encoding;
1610
1611 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1612 global configuration variables. */
1613 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1614 config->filesystem_errors) < 0) {
1615 return _Py_INIT_NO_MEMORY();
1616 }
1617
1618 /* PyUnicode can now use the Python codec rather than C implementation
1619 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001620 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001621 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001622}
1623
1624/* Import the site module (not into __main__ though) */
1625
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001626static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001627initsite(void)
1628{
1629 PyObject *m;
1630 m = PyImport_ImportModule("site");
1631 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001632 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001633 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001634 Py_DECREF(m);
1635 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001636}
1637
Victor Stinner874dbe82015-09-04 17:29:57 +02001638/* Check if a file descriptor is valid or not.
1639 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1640static int
1641is_valid_fd(int fd)
1642{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001643#ifdef __APPLE__
1644 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1645 and the other side of the pipe is closed, dup(1) succeed, whereas
1646 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1647 such error. */
1648 struct stat st;
1649 return (fstat(fd, &st) == 0);
1650#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001651 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001652 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001653 return 0;
1654 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001655 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1656 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1657 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001658 fd2 = dup(fd);
1659 if (fd2 >= 0)
1660 close(fd2);
1661 _Py_END_SUPPRESS_IPH
1662 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001663#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001664}
1665
1666/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001667static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001668create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001669 int fd, int write_mode, const char* name,
1670 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001671{
1672 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1673 const char* mode;
1674 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001675 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001676 int buffering, isatty;
1677 _Py_IDENTIFIER(open);
1678 _Py_IDENTIFIER(isatty);
1679 _Py_IDENTIFIER(TextIOWrapper);
1680 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001681 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001682
Victor Stinner874dbe82015-09-04 17:29:57 +02001683 if (!is_valid_fd(fd))
1684 Py_RETURN_NONE;
1685
Nick Coghland6009512014-11-20 21:39:37 +10001686 /* stdin is always opened in buffered mode, first because it shouldn't
1687 make a difference in common use cases, second because TextIOWrapper
1688 depends on the presence of a read1() method which only exists on
1689 buffered streams.
1690 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001691 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001692 buffering = 0;
1693 else
1694 buffering = -1;
1695 if (write_mode)
1696 mode = "wb";
1697 else
1698 mode = "rb";
1699 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1700 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001701 Py_None, Py_None, /* encoding, errors */
1702 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001703 if (buf == NULL)
1704 goto error;
1705
1706 if (buffering) {
1707 _Py_IDENTIFIER(raw);
1708 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1709 if (raw == NULL)
1710 goto error;
1711 }
1712 else {
1713 raw = buf;
1714 Py_INCREF(raw);
1715 }
1716
Steve Dower39294992016-08-30 21:22:36 -07001717#ifdef MS_WINDOWS
1718 /* Windows console IO is always UTF-8 encoded */
1719 if (PyWindowsConsoleIO_Check(raw))
1720 encoding = "utf-8";
1721#endif
1722
Nick Coghland6009512014-11-20 21:39:37 +10001723 text = PyUnicode_FromString(name);
1724 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1725 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001726 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001727 if (res == NULL)
1728 goto error;
1729 isatty = PyObject_IsTrue(res);
1730 Py_DECREF(res);
1731 if (isatty == -1)
1732 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001733 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001734 write_through = Py_True;
1735 else
1736 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001737 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001738 line_buffering = Py_True;
1739 else
1740 line_buffering = Py_False;
1741
1742 Py_CLEAR(raw);
1743 Py_CLEAR(text);
1744
1745#ifdef MS_WINDOWS
1746 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1747 newlines to "\n".
1748 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1749 newline = NULL;
1750#else
1751 /* sys.stdin: split lines at "\n".
1752 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1753 newline = "\n";
1754#endif
1755
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001756 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001757 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001758 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001759 Py_CLEAR(buf);
1760 if (stream == NULL)
1761 goto error;
1762
1763 if (write_mode)
1764 mode = "w";
1765 else
1766 mode = "r";
1767 text = PyUnicode_FromString(mode);
1768 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1769 goto error;
1770 Py_CLEAR(text);
1771 return stream;
1772
1773error:
1774 Py_XDECREF(buf);
1775 Py_XDECREF(stream);
1776 Py_XDECREF(text);
1777 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001778
Victor Stinner874dbe82015-09-04 17:29:57 +02001779 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1780 /* Issue #24891: the file descriptor was closed after the first
1781 is_valid_fd() check was called. Ignore the OSError and set the
1782 stream to None. */
1783 PyErr_Clear();
1784 Py_RETURN_NONE;
1785 }
1786 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001787}
1788
1789/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001790static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001791init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001792{
1793 PyObject *iomod = NULL, *wrapper;
1794 PyObject *bimod = NULL;
1795 PyObject *m;
1796 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001797 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001798 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001799 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001800 _PyCoreConfig *config = &interp->core_config;
1801
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001802 /* Check that stdin is not a directory
1803 Using shell redirection, you can redirect stdin to a directory,
1804 crashing the Python interpreter. Catch this common mistake here
1805 and output a useful error message. Note that under MS Windows,
1806 the shell already prevents that. */
1807#ifndef MS_WINDOWS
1808 struct _Py_stat_struct sb;
1809 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1810 S_ISDIR(sb.st_mode)) {
1811 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1812 "cannot continue");
1813 }
1814#endif
1815
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001816 char *codec_name = get_codec_name(config->stdio_encoding);
1817 if (codec_name == NULL) {
1818 return _Py_INIT_ERR("failed to get the Python codec name "
1819 "of the stdio encoding");
1820 }
1821 PyMem_RawFree(config->stdio_encoding);
1822 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001823
1824 /* Hack to avoid a nasty recursion issue when Python is invoked
1825 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1826 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1827 goto error;
1828 }
1829 Py_DECREF(m);
1830
1831 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1832 goto error;
1833 }
1834 Py_DECREF(m);
1835
1836 if (!(bimod = PyImport_ImportModule("builtins"))) {
1837 goto error;
1838 }
1839
1840 if (!(iomod = PyImport_ImportModule("io"))) {
1841 goto error;
1842 }
1843 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1844 goto error;
1845 }
1846
1847 /* Set builtins.open */
1848 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1849 Py_DECREF(wrapper);
1850 goto error;
1851 }
1852 Py_DECREF(wrapper);
1853
Nick Coghland6009512014-11-20 21:39:37 +10001854 /* Set sys.stdin */
1855 fd = fileno(stdin);
1856 /* Under some conditions stdin, stdout and stderr may not be connected
1857 * and fileno() may point to an invalid file descriptor. For example
1858 * GUI apps don't have valid standard streams by default.
1859 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001860 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001861 config->stdio_encoding,
1862 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001863 if (std == NULL)
1864 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001865 PySys_SetObject("__stdin__", std);
1866 _PySys_SetObjectId(&PyId_stdin, std);
1867 Py_DECREF(std);
1868
1869 /* Set sys.stdout */
1870 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001871 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001872 config->stdio_encoding,
1873 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001874 if (std == NULL)
1875 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001876 PySys_SetObject("__stdout__", std);
1877 _PySys_SetObjectId(&PyId_stdout, std);
1878 Py_DECREF(std);
1879
1880#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1881 /* Set sys.stderr, replaces the preliminary stderr */
1882 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001883 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001884 config->stdio_encoding,
1885 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001886 if (std == NULL)
1887 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001888
1889 /* Same as hack above, pre-import stderr's codec to avoid recursion
1890 when import.c tries to write to stderr in verbose mode. */
1891 encoding_attr = PyObject_GetAttrString(std, "encoding");
1892 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001893 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001894 if (std_encoding != NULL) {
1895 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1896 Py_XDECREF(codec_info);
1897 }
1898 Py_DECREF(encoding_attr);
1899 }
1900 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1901
1902 if (PySys_SetObject("__stderr__", std) < 0) {
1903 Py_DECREF(std);
1904 goto error;
1905 }
1906 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1907 Py_DECREF(std);
1908 goto error;
1909 }
1910 Py_DECREF(std);
1911#endif
1912
Victor Stinnera7368ac2017-11-15 18:11:45 -08001913 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001914
Victor Stinnera7368ac2017-11-15 18:11:45 -08001915error:
1916 res = _Py_INIT_ERR("can't initialize sys standard streams");
1917
1918done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001919 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001920
Nick Coghland6009512014-11-20 21:39:37 +10001921 Py_XDECREF(bimod);
1922 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001923 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001924}
1925
1926
Victor Stinner10dc4842015-03-24 12:01:30 +01001927static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001928_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001929{
Victor Stinner10dc4842015-03-24 12:01:30 +01001930 fputc('\n', stderr);
1931 fflush(stderr);
1932
1933 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001934 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001935}
Victor Stinner791da1c2016-03-14 16:53:12 +01001936
1937/* Print the current exception (if an exception is set) with its traceback,
1938 or display the current Python stack.
1939
1940 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1941 called on catastrophic cases.
1942
1943 Return 1 if the traceback was displayed, 0 otherwise. */
1944
1945static int
1946_Py_FatalError_PrintExc(int fd)
1947{
1948 PyObject *ferr, *res;
1949 PyObject *exception, *v, *tb;
1950 int has_tb;
1951
Victor Stinner791da1c2016-03-14 16:53:12 +01001952 PyErr_Fetch(&exception, &v, &tb);
1953 if (exception == NULL) {
1954 /* No current exception */
1955 return 0;
1956 }
1957
1958 ferr = _PySys_GetObjectId(&PyId_stderr);
1959 if (ferr == NULL || ferr == Py_None) {
1960 /* sys.stderr is not set yet or set to None,
1961 no need to try to display the exception */
1962 return 0;
1963 }
1964
1965 PyErr_NormalizeException(&exception, &v, &tb);
1966 if (tb == NULL) {
1967 tb = Py_None;
1968 Py_INCREF(tb);
1969 }
1970 PyException_SetTraceback(v, tb);
1971 if (exception == NULL) {
1972 /* PyErr_NormalizeException() failed */
1973 return 0;
1974 }
1975
1976 has_tb = (tb != Py_None);
1977 PyErr_Display(exception, v, tb);
1978 Py_XDECREF(exception);
1979 Py_XDECREF(v);
1980 Py_XDECREF(tb);
1981
1982 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001983 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001984 if (res == NULL)
1985 PyErr_Clear();
1986 else
1987 Py_DECREF(res);
1988
1989 return has_tb;
1990}
1991
Nick Coghland6009512014-11-20 21:39:37 +10001992/* Print fatal error message and abort */
1993
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001994#ifdef MS_WINDOWS
1995static void
1996fatal_output_debug(const char *msg)
1997{
1998 /* buffer of 256 bytes allocated on the stack */
1999 WCHAR buffer[256 / sizeof(WCHAR)];
2000 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2001 size_t msglen;
2002
2003 OutputDebugStringW(L"Fatal Python error: ");
2004
2005 msglen = strlen(msg);
2006 while (msglen) {
2007 size_t i;
2008
2009 if (buflen > msglen) {
2010 buflen = msglen;
2011 }
2012
2013 /* Convert the message to wchar_t. This uses a simple one-to-one
2014 conversion, assuming that the this error message actually uses
2015 ASCII only. If this ceases to be true, we will have to convert. */
2016 for (i=0; i < buflen; ++i) {
2017 buffer[i] = msg[i];
2018 }
2019 buffer[i] = L'\0';
2020 OutputDebugStringW(buffer);
2021
2022 msg += buflen;
2023 msglen -= buflen;
2024 }
2025 OutputDebugStringW(L"\n");
2026}
2027#endif
2028
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002029static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002030fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002031{
2032 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002033 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002034
2035 if (reentrant) {
2036 /* Py_FatalError() caused a second fatal error.
2037 Example: flush_std_files() raises a recursion error. */
2038 goto exit;
2039 }
2040 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002041
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002042 fprintf(stderr, "Fatal Python error: ");
2043 if (prefix) {
2044 fputs(prefix, stderr);
2045 fputs(": ", stderr);
2046 }
2047 if (msg) {
2048 fputs(msg, stderr);
2049 }
2050 else {
2051 fprintf(stderr, "<message not set>");
2052 }
2053 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002054 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002055
Victor Stinner3a228ab2018-11-01 00:26:41 +01002056 /* Check if the current thread has a Python thread state
2057 and holds the GIL */
2058 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2059 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002060 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002061 if (tss_tstate != tstate) {
2062 /* The Python thread does not hold the GIL */
2063 tss_tstate = NULL;
2064 }
2065 }
2066 else {
2067 /* Py_FatalError() has been called from a C thread
2068 which has no Python thread state. */
2069 }
2070 int has_tstate_and_gil = (tss_tstate != NULL);
2071
2072 if (has_tstate_and_gil) {
2073 /* If an exception is set, print the exception with its traceback */
2074 if (!_Py_FatalError_PrintExc(fd)) {
2075 /* No exception is set, or an exception is set without traceback */
2076 _Py_FatalError_DumpTracebacks(fd);
2077 }
2078 }
2079 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002080 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002081 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002082
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002083 /* The main purpose of faulthandler is to display the traceback.
2084 This function already did its best to display a traceback.
2085 Disable faulthandler to prevent writing a second traceback
2086 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002087 _PyFaulthandler_Fini();
2088
Victor Stinner791da1c2016-03-14 16:53:12 +01002089 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002090 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002091 /* Flush sys.stdout and sys.stderr */
2092 flush_std_files();
2093 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002094
Nick Coghland6009512014-11-20 21:39:37 +10002095#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002096 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002097#endif /* MS_WINDOWS */
2098
2099exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002100 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002101#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002102 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002103#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002104 abort();
2105 }
2106 else {
2107 exit(status);
2108 }
2109}
2110
Victor Stinner19760862017-12-20 01:41:59 +01002111void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002112Py_FatalError(const char *msg)
2113{
2114 fatal_error(NULL, msg, -1);
2115}
2116
Victor Stinner19760862017-12-20 01:41:59 +01002117void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002118_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002119{
Victor Stinnerdfe88472019-03-01 12:14:41 +01002120 if (err.exitcode >= 0) {
2121 exit(err.exitcode);
2122 }
2123 else {
2124 /* On "user" error: exit with status 1.
2125 For all other errors, call abort(). */
2126 int status = err.user_err ? 1 : -1;
2127 fatal_error(err.prefix, err.msg, status);
2128 }
Nick Coghland6009512014-11-20 21:39:37 +10002129}
2130
2131/* Clean up and exit */
2132
Victor Stinnerd7292b52016-06-17 12:29:00 +02002133# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002134
Nick Coghland6009512014-11-20 21:39:37 +10002135/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002136void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002137{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002138 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002139
Antoine Pitroufc5db952017-12-13 02:29:07 +01002140 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002141 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2142
2143 is->pyexitfunc = func;
2144 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002145}
2146
2147static void
Marcel Plch776407f2017-12-20 11:17:58 +01002148call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002149{
Marcel Plch776407f2017-12-20 11:17:58 +01002150 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002151 return;
2152
Marcel Plch776407f2017-12-20 11:17:58 +01002153 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002154 PyErr_Clear();
2155}
2156
2157/* Wait until threading._shutdown completes, provided
2158 the threading module was imported in the first place.
2159 The shutdown routine will wait until all non-daemon
2160 "threading" threads have completed. */
2161static void
2162wait_for_thread_shutdown(void)
2163{
Nick Coghland6009512014-11-20 21:39:37 +10002164 _Py_IDENTIFIER(_shutdown);
2165 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002166 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002167 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002168 if (PyErr_Occurred()) {
2169 PyErr_WriteUnraisable(NULL);
2170 }
2171 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002172 return;
2173 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002174 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002175 if (result == NULL) {
2176 PyErr_WriteUnraisable(threading);
2177 }
2178 else {
2179 Py_DECREF(result);
2180 }
2181 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002182}
2183
2184#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002185int Py_AtExit(void (*func)(void))
2186{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002187 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002188 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002189 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002190 return 0;
2191}
2192
2193static void
2194call_ll_exitfuncs(void)
2195{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002196 while (_PyRuntime.nexitfuncs > 0)
2197 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002198
2199 fflush(stdout);
2200 fflush(stderr);
2201}
2202
Victor Stinnercfc88312018-08-01 16:41:25 +02002203void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002204Py_Exit(int sts)
2205{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002206 if (Py_FinalizeEx() < 0) {
2207 sts = 120;
2208 }
Nick Coghland6009512014-11-20 21:39:37 +10002209
2210 exit(sts);
2211}
2212
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002213static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002214initsigs(void)
2215{
2216#ifdef SIGPIPE
2217 PyOS_setsig(SIGPIPE, SIG_IGN);
2218#endif
2219#ifdef SIGXFZ
2220 PyOS_setsig(SIGXFZ, SIG_IGN);
2221#endif
2222#ifdef SIGXFSZ
2223 PyOS_setsig(SIGXFSZ, SIG_IGN);
2224#endif
2225 PyOS_InitInterrupts(); /* May imply initsignal() */
2226 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002227 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002228 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002229 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002230}
2231
2232
2233/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2234 *
2235 * All of the code in this function must only use async-signal-safe functions,
2236 * listed at `man 7 signal` or
2237 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2238 */
2239void
2240_Py_RestoreSignals(void)
2241{
2242#ifdef SIGPIPE
2243 PyOS_setsig(SIGPIPE, SIG_DFL);
2244#endif
2245#ifdef SIGXFZ
2246 PyOS_setsig(SIGXFZ, SIG_DFL);
2247#endif
2248#ifdef SIGXFSZ
2249 PyOS_setsig(SIGXFSZ, SIG_DFL);
2250#endif
2251}
2252
2253
2254/*
2255 * The file descriptor fd is considered ``interactive'' if either
2256 * a) isatty(fd) is TRUE, or
2257 * b) the -i flag was given, and the filename associated with
2258 * the descriptor is NULL or "<stdin>" or "???".
2259 */
2260int
2261Py_FdIsInteractive(FILE *fp, const char *filename)
2262{
2263 if (isatty((int)fileno(fp)))
2264 return 1;
2265 if (!Py_InteractiveFlag)
2266 return 0;
2267 return (filename == NULL) ||
2268 (strcmp(filename, "<stdin>") == 0) ||
2269 (strcmp(filename, "???") == 0);
2270}
2271
2272
Nick Coghland6009512014-11-20 21:39:37 +10002273/* Wrappers around sigaction() or signal(). */
2274
2275PyOS_sighandler_t
2276PyOS_getsig(int sig)
2277{
2278#ifdef HAVE_SIGACTION
2279 struct sigaction context;
2280 if (sigaction(sig, NULL, &context) == -1)
2281 return SIG_ERR;
2282 return context.sa_handler;
2283#else
2284 PyOS_sighandler_t handler;
2285/* Special signal handling for the secure CRT in Visual Studio 2005 */
2286#if defined(_MSC_VER) && _MSC_VER >= 1400
2287 switch (sig) {
2288 /* Only these signals are valid */
2289 case SIGINT:
2290 case SIGILL:
2291 case SIGFPE:
2292 case SIGSEGV:
2293 case SIGTERM:
2294 case SIGBREAK:
2295 case SIGABRT:
2296 break;
2297 /* Don't call signal() with other values or it will assert */
2298 default:
2299 return SIG_ERR;
2300 }
2301#endif /* _MSC_VER && _MSC_VER >= 1400 */
2302 handler = signal(sig, SIG_IGN);
2303 if (handler != SIG_ERR)
2304 signal(sig, handler);
2305 return handler;
2306#endif
2307}
2308
2309/*
2310 * All of the code in this function must only use async-signal-safe functions,
2311 * listed at `man 7 signal` or
2312 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2313 */
2314PyOS_sighandler_t
2315PyOS_setsig(int sig, PyOS_sighandler_t handler)
2316{
2317#ifdef HAVE_SIGACTION
2318 /* Some code in Modules/signalmodule.c depends on sigaction() being
2319 * used here if HAVE_SIGACTION is defined. Fix that if this code
2320 * changes to invalidate that assumption.
2321 */
2322 struct sigaction context, ocontext;
2323 context.sa_handler = handler;
2324 sigemptyset(&context.sa_mask);
2325 context.sa_flags = 0;
2326 if (sigaction(sig, &context, &ocontext) == -1)
2327 return SIG_ERR;
2328 return ocontext.sa_handler;
2329#else
2330 PyOS_sighandler_t oldhandler;
2331 oldhandler = signal(sig, handler);
2332#ifdef HAVE_SIGINTERRUPT
2333 siginterrupt(sig, 1);
2334#endif
2335 return oldhandler;
2336#endif
2337}
2338
2339#ifdef __cplusplus
2340}
2341#endif