blob: ec39500d4cd363bdfe17d0b8ef923b6b74b68af4 [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"
6#undef Yield /* undefine macro conflicting with winbase.h */
Yury Selivanovf23746a2018-01-22 19:11:18 -05007#include "internal/context.h"
8#include "internal/hamt.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06009#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100010#include "grammar.h"
11#include "node.h"
12#include "token.h"
13#include "parsetok.h"
14#include "errcode.h"
15#include "code.h"
16#include "symtable.h"
17#include "ast.h"
18#include "marshal.h"
19#include "osdefs.h"
20#include <locale.h>
21
22#ifdef HAVE_SIGNAL_H
23#include <signal.h>
24#endif
25
26#ifdef MS_WINDOWS
27#include "malloc.h" /* for alloca */
28#endif
29
30#ifdef HAVE_LANGINFO_H
31#include <langinfo.h>
32#endif
33
34#ifdef MS_WINDOWS
35#undef BYTE
36#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070037
38extern PyTypeObject PyWindowsConsoleIO_Type;
39#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100040#endif
41
42_Py_IDENTIFIER(flush);
43_Py_IDENTIFIER(name);
44_Py_IDENTIFIER(stdin);
45_Py_IDENTIFIER(stdout);
46_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060047_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100048
49#ifdef __cplusplus
50extern "C" {
51#endif
52
Nick Coghland6009512014-11-20 21:39:37 +100053extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056static _PyInitError add_main_module(PyInterpreterState *interp);
57static _PyInitError initfsencoding(PyInterpreterState *interp);
58static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010059static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010061static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100062static void wait_for_thread_shutdown(void);
63static void call_ll_exitfuncs(void);
64extern int _PyUnicode_Init(void);
65extern int _PyStructSequence_Init(void);
66extern void _PyUnicode_Fini(void);
67extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080069extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100070extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080072extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100073extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070074extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100075
Nick Coghland6009512014-11-20 21:39:37 +100076extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082_PyRuntime_Initialize(void)
83{
84 /* XXX We only initialize once in the process, which aligns with
85 the static initialization of the former globals now found in
86 _PyRuntime. However, _PyRuntime *should* be initialized with
87 every Py_Initialize() call, but doing so breaks the runtime.
88 This is because the runtime state is not properly finalized
89 currently. */
90 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091 if (initialized) {
92 return _Py_INIT_OK();
93 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095
96 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99void
100_PyRuntime_Finalize(void)
101{
102 _PyRuntimeState_Fini(&_PyRuntime);
103}
104
105int
106_Py_IsFinalizing(void)
107{
108 return _PyRuntime.finalizing != NULL;
109}
110
Nick Coghland6009512014-11-20 21:39:37 +1000111/* Hack to force loading of object files */
112int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
113 PyOS_mystrnicmp; /* Python/pystrcmp.o */
114
115/* PyModule_GetWarningsModule is no longer necessary as of 2.6
116since _warnings is builtin. This API should not be used. */
117PyObject *
118PyModule_GetWarningsModule(void)
119{
120 return PyImport_ImportModule("warnings");
121}
122
Eric Snowc7ec9982017-05-23 23:00:52 -0700123
Eric Snow1abcf672017-05-23 21:46:51 -0700124/* APIs to access the initialization flags
125 *
126 * Can be called prior to Py_Initialize.
127 */
Nick Coghland6009512014-11-20 21:39:37 +1000128
Eric Snow1abcf672017-05-23 21:46:51 -0700129int
130_Py_IsCoreInitialized(void)
131{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600132 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700133}
Nick Coghland6009512014-11-20 21:39:37 +1000134
135int
136Py_IsInitialized(void)
137{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600138 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000139}
140
Nick Coghlan6ea41862017-06-11 13:16:15 +1000141
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000142/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
143 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000144 initializations fail, a fatal error is issued and the function does
145 not return. On return, the first thread and interpreter state have
146 been created.
147
148 Locking: you must hold the interpreter lock while calling this.
149 (If the lock has not yet been initialized, that's equivalent to
150 having the lock, but you cannot use multiple threads.)
151
152*/
153
Nick Coghland6009512014-11-20 21:39:37 +1000154static char*
155get_codec_name(const char *encoding)
156{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200157 const char *name_utf8;
158 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000159 PyObject *codec, *name = NULL;
160
161 codec = _PyCodec_Lookup(encoding);
162 if (!codec)
163 goto error;
164
165 name = _PyObject_GetAttrId(codec, &PyId_name);
166 Py_CLEAR(codec);
167 if (!name)
168 goto error;
169
Serhiy Storchaka06515832016-11-20 09:13:07 +0200170 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000171 if (name_utf8 == NULL)
172 goto error;
173 name_str = _PyMem_RawStrdup(name_utf8);
174 Py_DECREF(name);
175 if (name_str == NULL) {
176 PyErr_NoMemory();
177 return NULL;
178 }
179 return name_str;
180
181error:
182 Py_XDECREF(codec);
183 Py_XDECREF(name);
184 return NULL;
185}
186
Nick Coghland6009512014-11-20 21:39:37 +1000187
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800188static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700189initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000190{
191 PyObject *importlib;
192 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000193 PyObject *value;
194
195 /* Import _importlib through its frozen version, _frozen_importlib. */
196 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800197 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000198 }
199 else if (Py_VerboseFlag) {
200 PySys_FormatStderr("import _frozen_importlib # frozen\n");
201 }
202 importlib = PyImport_AddModule("_frozen_importlib");
203 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800204 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000205 }
206 interp->importlib = importlib;
207 Py_INCREF(interp->importlib);
208
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300209 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
210 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800211 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300212 Py_INCREF(interp->import_func);
213
Victor Stinnercd6e6942015-09-18 09:11:57 +0200214 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800215 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000216 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800217 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000218 }
219 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200220 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000221 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600222 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800223 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000224 }
225
Victor Stinnercd6e6942015-09-18 09:11:57 +0200226 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000227 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
228 if (value == NULL) {
229 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800230 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000231 }
232 Py_DECREF(value);
233 Py_DECREF(impmod);
234
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800235 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000236}
237
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800238static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700239initexternalimport(PyInterpreterState *interp)
240{
241 PyObject *value;
242 value = PyObject_CallMethod(interp->importlib,
243 "_install_external_importers", "");
244 if (value == NULL) {
245 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800246 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700247 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200248 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300249 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700250}
Nick Coghland6009512014-11-20 21:39:37 +1000251
Nick Coghlan6ea41862017-06-11 13:16:15 +1000252/* Helper functions to better handle the legacy C locale
253 *
254 * The legacy C locale assumes ASCII as the default text encoding, which
255 * causes problems not only for the CPython runtime, but also other
256 * components like GNU readline.
257 *
258 * Accordingly, when the CLI detects it, it attempts to coerce it to a
259 * more capable UTF-8 based alternative as follows:
260 *
261 * if (_Py_LegacyLocaleDetected()) {
262 * _Py_CoerceLegacyLocale();
263 * }
264 *
265 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
266 *
267 * Locale coercion also impacts the default error handler for the standard
268 * streams: while the usual default is "strict", the default for the legacy
269 * C locale and for any of the coercion target locales is "surrogateescape".
270 */
271
272int
273_Py_LegacyLocaleDetected(void)
274{
275#ifndef MS_WINDOWS
276 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000277 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
278 * the POSIX locale as a simple alias for the C locale, so
279 * we may also want to check for that explicitly.
280 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000281 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
282 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
283#else
284 /* Windows uses code pages instead of locales, so no locale is legacy */
285 return 0;
286#endif
287}
288
Nick Coghlaneb817952017-06-18 12:29:42 +1000289static const char *_C_LOCALE_WARNING =
290 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
291 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
292 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
293 "locales is recommended.\n";
294
Nick Coghlaneb817952017-06-18 12:29:42 +1000295static void
Victor Stinner94540602017-12-16 04:54:22 +0100296_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000297{
Victor Stinner06e76082018-09-19 14:56:36 -0700298 if (core_config->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200299 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000300 }
301}
302
Nick Coghlan6ea41862017-06-11 13:16:15 +1000303typedef struct _CandidateLocale {
304 const char *locale_name; /* The locale to try as a coercion target */
305} _LocaleCoercionTarget;
306
307static _LocaleCoercionTarget _TARGET_LOCALES[] = {
308 {"C.UTF-8"},
309 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000310 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311 {NULL}
312};
313
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200314
315int
316_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200318 const _LocaleCoercionTarget *target = NULL;
319 for (target = _TARGET_LOCALES; target->locale_name; target++) {
320 if (strcmp(ctype_loc, target->locale_name) == 0) {
321 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000322 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200323 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200324 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000325}
326
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200327
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100329static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000330 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
331 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
332
333static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200334_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000335{
336 const char *newloc = target->locale_name;
337
338 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100339 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000340
341 /* Set the relevant locale environment variable */
342 if (setenv("LC_CTYPE", newloc, 1)) {
343 fprintf(stderr,
344 "Error setting LC_CTYPE, skipping C locale coercion\n");
345 return;
346 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200347 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100348 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000349 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350
351 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100352 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000353}
354#endif
355
356void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200357_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000358{
359#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200360 char *oldloc = NULL;
361
362 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
363 if (oldloc == NULL) {
364 return;
365 }
366
Victor Stinner94540602017-12-16 04:54:22 +0100367 const char *locale_override = getenv("LC_ALL");
368 if (locale_override == NULL || *locale_override == '\0') {
369 /* LC_ALL is also not set (or is set to an empty string) */
370 const _LocaleCoercionTarget *target = NULL;
371 for (target = _TARGET_LOCALES; target->locale_name; target++) {
372 const char *new_locale = setlocale(LC_CTYPE,
373 target->locale_name);
374 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100375#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100376defined(HAVE_LANGINFO_H) && defined(CODESET)
377 /* Also ensure that nl_langinfo works in this locale */
378 char *codeset = nl_langinfo(CODESET);
379 if (!codeset || *codeset == '\0') {
380 /* CODESET is not set or empty, so skip coercion */
381 new_locale = NULL;
382 _Py_SetLocaleFromEnv(LC_CTYPE);
383 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000384 }
Victor Stinner94540602017-12-16 04:54:22 +0100385#endif
386 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200387 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200388 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000389 }
390 }
391 }
392 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200393
394 setlocale(LC_CTYPE, oldloc);
395
396done:
397 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000398#endif
399}
400
xdegaye1588be62017-11-12 12:45:59 +0100401/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
402 * isolate the idiosyncrasies of different libc implementations. It reads the
403 * appropriate environment variable and uses its value to select the locale for
404 * 'category'. */
405char *
406_Py_SetLocaleFromEnv(int category)
407{
408#ifdef __ANDROID__
409 const char *locale;
410 const char **pvar;
411#ifdef PY_COERCE_C_LOCALE
412 const char *coerce_c_locale;
413#endif
414 const char *utf8_locale = "C.UTF-8";
415 const char *env_var_set[] = {
416 "LC_ALL",
417 "LC_CTYPE",
418 "LANG",
419 NULL,
420 };
421
422 /* Android setlocale(category, "") doesn't check the environment variables
423 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
424 * check the environment variables listed in env_var_set. */
425 for (pvar=env_var_set; *pvar; pvar++) {
426 locale = getenv(*pvar);
427 if (locale != NULL && *locale != '\0') {
428 if (strcmp(locale, utf8_locale) == 0 ||
429 strcmp(locale, "en_US.UTF-8") == 0) {
430 return setlocale(category, utf8_locale);
431 }
432 return setlocale(category, "C");
433 }
434 }
435
436 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
437 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
438 * Quote from POSIX section "8.2 Internationalization Variables":
439 * "4. If the LANG environment variable is not set or is set to the empty
440 * string, the implementation-defined default locale shall be used." */
441
442#ifdef PY_COERCE_C_LOCALE
443 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
444 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
445 /* Some other ported code may check the environment variables (e.g. in
446 * extension modules), so we make sure that they match the locale
447 * configuration */
448 if (setenv("LC_CTYPE", utf8_locale, 1)) {
449 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
450 "environment variable to %s\n", utf8_locale);
451 }
452 }
453#endif
454 return setlocale(category, utf8_locale);
455#else /* __ANDROID__ */
456 return setlocale(category, "");
457#endif /* __ANDROID__ */
458}
459
Nick Coghlan6ea41862017-06-11 13:16:15 +1000460
Eric Snow1abcf672017-05-23 21:46:51 -0700461/* Global initializations. Can be undone by Py_Finalize(). Don't
462 call this twice without an intervening Py_Finalize() call.
463
Victor Stinner1dc6e392018-07-25 02:49:17 +0200464 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700465 must have a corresponding call to Py_Finalize.
466
467 Locking: you must hold the interpreter lock while calling these APIs.
468 (If the lock has not yet been initialized, that's equivalent to
469 having the lock, but you cannot use multiple threads.)
470
471*/
472
Victor Stinner1dc6e392018-07-25 02:49:17 +0200473static _PyInitError
474_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
475 const _PyCoreConfig *core_config)
476{
477 if (core_config->allocator != NULL) {
478 const char *allocator = _PyMem_GetAllocatorsName();
479 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
480 return _Py_INIT_USER_ERR("cannot modify memory allocator "
481 "after first Py_Initialize()");
482 }
483 }
484
485 _PyCoreConfig_SetGlobalConfig(core_config);
486
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
Eric Snow1abcf672017-05-23 21:46:51 -0700502/* Begin interpreter initialization
503 *
504 * On return, the first thread and interpreter state have been created,
505 * but the compiler, signal handling, multithreading and
506 * multiple interpreter support, and codec infrastructure are not yet
507 * available.
508 *
509 * The import system will support builtin and frozen modules only.
510 * The only supported io is writing to sys.stderr
511 *
512 * If any operation invoked by this function fails, a fatal error is
513 * issued and the function does not return.
514 *
515 * Any code invoked from this function should *not* assume it has access
516 * to the Python C API (unless the API is explicitly listed as being
517 * safe to call without calling Py_Initialize first)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200518 *
519 * The caller is responsible to call _PyCoreConfig_Read().
Eric Snow1abcf672017-05-23 21:46:51 -0700520 */
521
Victor Stinner1dc6e392018-07-25 02:49:17 +0200522static _PyInitError
523_Py_InitializeCore_impl(PyInterpreterState **interp_p,
524 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000525{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200526 PyInterpreterState *interp;
527 _PyInitError err;
528
529 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
530 Py_Initialize() ignores the new configuration. */
531 if (_PyRuntime.core_initialized) {
532 PyThreadState *tstate = PyThreadState_GET();
533 if (!tstate) {
534 return _Py_INIT_ERR("failed to read thread state");
535 }
536
537 interp = tstate->interp;
538 if (interp == NULL) {
539 return _Py_INIT_ERR("can't make main interpreter");
540 }
541 *interp_p = interp;
542
543 return _Py_Initialize_ReconfigureCore(interp, core_config);
544 }
545
546 if (_PyRuntime.initialized) {
547 return _Py_INIT_ERR("main interpreter already initialized");
548 }
Victor Stinnerda273412017-12-15 01:46:02 +0100549
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200550 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000551
Victor Stinner1dc6e392018-07-25 02:49:17 +0200552 err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800553 if (_Py_INIT_FAILED(err)) {
554 return err;
555 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600556
Victor Stinner31e99082017-12-20 23:41:38 +0100557 if (core_config->allocator != NULL) {
558 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
559 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
560 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800561 }
562
Eric Snow1abcf672017-05-23 21:46:51 -0700563 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
564 * threads behave a little more gracefully at interpreter shutdown.
565 * We clobber it here so the new interpreter can start with a clean
566 * slate.
567 *
568 * However, this may still lead to misbehaviour if there are daemon
569 * threads still hanging around from a previous Py_Initialize/Finalize
570 * pair :(
571 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600572 _PyRuntime.finalizing = NULL;
573
Victor Stinnerda273412017-12-15 01:46:02 +0100574 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800575 if (_Py_INIT_FAILED(err)) {
576 return err;
577 }
578
Victor Stinnera7368ac2017-11-15 18:11:45 -0800579 err = _PyInterpreterState_Enable(&_PyRuntime);
580 if (_Py_INIT_FAILED(err)) {
581 return err;
582 }
583
Victor Stinner1dc6e392018-07-25 02:49:17 +0200584 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100585 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800586 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100587 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200588 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100589
590 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
591 return _Py_INIT_ERR("failed to copy core config");
592 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200593 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000594
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200595 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000596 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800597 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000598 (void) PyThreadState_Swap(tstate);
599
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000600 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000601 destroying the GIL might fail when it is being referenced from
602 another running thread (see issue #9901).
603 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000604 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000605 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100606
Nick Coghland6009512014-11-20 21:39:37 +1000607 /* Auto-thread-state API */
608 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000609
Victor Stinner2914bb32018-01-29 11:57:45 +0100610 /* Create the GIL */
611 PyEval_InitThreads();
612
Nick Coghland6009512014-11-20 21:39:37 +1000613 _Py_ReadyTypes();
614
Nick Coghland6009512014-11-20 21:39:37 +1000615 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800616 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000617
618 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800619 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000620
621 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800622 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000623
Eric Snowd393c1b2017-09-14 12:18:12 -0600624 PyObject *modules = PyDict_New();
625 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800626 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600627 interp->modules = modules;
628
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200629 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800630 err = _PySys_BeginInit(&sysmod);
631 if (_Py_INIT_FAILED(err)) {
632 return err;
633 }
634
Eric Snowd393c1b2017-09-14 12:18:12 -0600635 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800636 if (interp->sysdict == NULL) {
637 return _Py_INIT_ERR("can't initialize sys dict");
638 }
639
Eric Snowd393c1b2017-09-14 12:18:12 -0600640 Py_INCREF(interp->sysdict);
641 PyDict_SetItemString(interp->sysdict, "modules", modules);
642 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000643
644 /* Init Unicode implementation; relies on the codec registry */
645 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800646 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700647
Nick Coghland6009512014-11-20 21:39:37 +1000648 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800649 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000650
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200651 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000652 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800653 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600654 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000655 interp->builtins = PyModule_GetDict(bimod);
656 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800657 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000658 Py_INCREF(interp->builtins);
659
660 /* initialize builtin exceptions */
661 _PyExc_Init(bimod);
662
Nick Coghland6009512014-11-20 21:39:37 +1000663 /* Set up a preliminary stderr printer until we have enough
664 infrastructure for the io module in place. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200665 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000666 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800667 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000668 _PySys_SetObjectId(&PyId_stderr, pstderr);
669 PySys_SetObject("__stderr__", pstderr);
670 Py_DECREF(pstderr);
671
Victor Stinner672b6ba2017-12-06 17:25:50 +0100672 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800673 if (_Py_INIT_FAILED(err)) {
674 return err;
675 }
Nick Coghland6009512014-11-20 21:39:37 +1000676
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800677 err = _PyImportHooks_Init();
678 if (_Py_INIT_FAILED(err)) {
679 return err;
680 }
Nick Coghland6009512014-11-20 21:39:37 +1000681
682 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100683 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100684 return _Py_INIT_ERR("can't initialize warnings");
685 }
Nick Coghland6009512014-11-20 21:39:37 +1000686
Yury Selivanovf23746a2018-01-22 19:11:18 -0500687 if (!_PyContext_Init())
688 return _Py_INIT_ERR("can't init context");
689
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200690 if (core_config->_install_importlib) {
Victor Stinnerb1147e42018-07-21 02:06:16 +0200691 err = _PyCoreConfig_SetPathConfig(core_config);
692 if (_Py_INIT_FAILED(err)) {
693 return err;
694 }
695 }
696
Eric Snow1abcf672017-05-23 21:46:51 -0700697 /* This call sets up builtin and frozen import support */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200698 if (core_config->_install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800699 err = initimport(interp, sysmod);
700 if (_Py_INIT_FAILED(err)) {
701 return err;
702 }
Eric Snow1abcf672017-05-23 21:46:51 -0700703 }
704
705 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600706 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800707 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700708}
709
Victor Stinner1dc6e392018-07-25 02:49:17 +0200710_PyInitError
711_Py_InitializeCore(PyInterpreterState **interp_p,
712 const _PyCoreConfig *src_config)
713{
714 assert(src_config != NULL);
715
Victor Stinner1dc6e392018-07-25 02:49:17 +0200716 PyMemAllocatorEx old_alloc;
717 _PyInitError err;
718
719 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
720 (and the input configuration is read only). */
721 _PyCoreConfig config = _PyCoreConfig_INIT;
722
Victor Stinner177d9212018-08-29 11:25:15 +0200723 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200724 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200725
Victor Stinner1dc6e392018-07-25 02:49:17 +0200726 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
727 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
728 err = _PyCoreConfig_Read(&config);
729 }
730 else {
731 err = _Py_INIT_ERR("failed to copy core config");
732 }
733 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
734
735 if (_Py_INIT_FAILED(err)) {
736 goto done;
737 }
738
739 err = _Py_InitializeCore_impl(interp_p, &config);
740
741done:
742 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
743 _PyCoreConfig_Clear(&config);
744 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
745
746 return err;
747}
748
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200749/* Py_Initialize() has already been called: update the main interpreter
750 configuration. Example of bpo-34008: Py_Main() called after
751 Py_Initialize(). */
752static _PyInitError
753_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
754 const _PyMainInterpreterConfig *config)
755{
756 if (config->argv != NULL) {
757 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
758 if (res < 0) {
759 return _Py_INIT_ERR("fail to set sys.argv");
760 }
761 }
762 return _Py_INIT_OK();
763}
764
Eric Snowc7ec9982017-05-23 23:00:52 -0700765/* Update interpreter state based on supplied configuration settings
766 *
767 * After calling this function, most of the restrictions on the interpreter
768 * are lifted. The only remaining incomplete settings are those related
769 * to the main module (sys.argv[0], __main__ metadata)
770 *
771 * Calling this when the interpreter is not initializing, is already
772 * initialized or without a valid current thread state is a fatal error.
773 * Other errors should be reported as normal Python exceptions with a
774 * non-zero return code.
775 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800776_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200777_Py_InitializeMainInterpreter(PyInterpreterState *interp,
778 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700779{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600780 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800781 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700782 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700783
Victor Stinner1dc6e392018-07-25 02:49:17 +0200784 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100785 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
786 return _Py_INIT_ERR("failed to copy main interpreter config");
787 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200788 config = &interp->config;
789 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700790
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200791 if (_PyRuntime.initialized) {
792 return _Py_ReconfigureMainInterpreter(interp, config);
793 }
794
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200795 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700796 /* Special mode for freeze_importlib: run with no import system
797 *
798 * This means anything which needs support from extension modules
799 * or pure Python code in the standard library won't work.
800 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600801 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800802 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700803 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100804
Victor Stinner33c377e2017-12-05 15:12:41 +0100805 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800806 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100807 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200808
Victor Stinnerfbca9082018-08-30 00:50:45 +0200809 if (_PySys_EndInit(interp->sysdict, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800810 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100811 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800812
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200813 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800814 if (_Py_INIT_FAILED(err)) {
815 return err;
816 }
Nick Coghland6009512014-11-20 21:39:37 +1000817
818 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200819 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800820 if (_Py_INIT_FAILED(err)) {
821 return err;
822 }
Nick Coghland6009512014-11-20 21:39:37 +1000823
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800824 err = initfsencoding(interp);
825 if (_Py_INIT_FAILED(err)) {
826 return err;
827 }
Nick Coghland6009512014-11-20 21:39:37 +1000828
Victor Stinner1f151112017-11-23 10:43:14 +0100829 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800830 err = initsigs(); /* Signal handling stuff, including initintr() */
831 if (_Py_INIT_FAILED(err)) {
832 return err;
833 }
834 }
Nick Coghland6009512014-11-20 21:39:37 +1000835
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200836 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800837 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200838 }
Nick Coghland6009512014-11-20 21:39:37 +1000839
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800840 err = add_main_module(interp);
841 if (_Py_INIT_FAILED(err)) {
842 return err;
843 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800844
Victor Stinner91106cd2017-12-13 12:29:09 +0100845 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800846 if (_Py_INIT_FAILED(err)) {
847 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800848 }
Nick Coghland6009512014-11-20 21:39:37 +1000849
850 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100851 if (interp->config.warnoptions != NULL &&
852 PyList_Size(interp->config.warnoptions) > 0)
853 {
Nick Coghland6009512014-11-20 21:39:37 +1000854 PyObject *warnings_module = PyImport_ImportModule("warnings");
855 if (warnings_module == NULL) {
856 fprintf(stderr, "'import warnings' failed; traceback:\n");
857 PyErr_Print();
858 }
859 Py_XDECREF(warnings_module);
860 }
861
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600862 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700863
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200864 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800865 err = initsite(); /* Module site */
866 if (_Py_INIT_FAILED(err)) {
867 return err;
868 }
869 }
Victor Stinnercf215042018-08-29 22:56:06 +0200870
871#ifndef MS_WINDOWS
872 _emit_stderr_warning_for_legacy_locale(core_config);
873#endif
874
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800875 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000876}
877
Eric Snowc7ec9982017-05-23 23:00:52 -0700878#undef _INIT_DEBUG_PRINT
879
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800880_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200881_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700882{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700883 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800884 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200885 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800886 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200887 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800888 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200889 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100890
Victor Stinner9cfc0022017-12-20 19:36:46 +0100891 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200892 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100893 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200894 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800895 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100896 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800897 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200898 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800899 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200900 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700901}
902
903
904void
Nick Coghland6009512014-11-20 21:39:37 +1000905Py_InitializeEx(int install_sigs)
906{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200907 if (_PyRuntime.initialized) {
908 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
909 return;
910 }
911
912 _PyInitError err;
913 _PyCoreConfig config = _PyCoreConfig_INIT;
914 config.install_signal_handlers = install_sigs;
915
916 err = _Py_InitializeFromConfig(&config);
917 _PyCoreConfig_Clear(&config);
918
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800919 if (_Py_INIT_FAILED(err)) {
920 _Py_FatalInitError(err);
921 }
Nick Coghland6009512014-11-20 21:39:37 +1000922}
923
924void
925Py_Initialize(void)
926{
927 Py_InitializeEx(1);
928}
929
930
931#ifdef COUNT_ALLOCS
932extern void dump_counts(FILE*);
933#endif
934
935/* Flush stdout and stderr */
936
937static int
938file_is_closed(PyObject *fobj)
939{
940 int r;
941 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
942 if (tmp == NULL) {
943 PyErr_Clear();
944 return 0;
945 }
946 r = PyObject_IsTrue(tmp);
947 Py_DECREF(tmp);
948 if (r < 0)
949 PyErr_Clear();
950 return r > 0;
951}
952
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000953static int
Nick Coghland6009512014-11-20 21:39:37 +1000954flush_std_files(void)
955{
956 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
957 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
958 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000959 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000960
961 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700962 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000963 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000964 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000965 status = -1;
966 }
Nick Coghland6009512014-11-20 21:39:37 +1000967 else
968 Py_DECREF(tmp);
969 }
970
971 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700972 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000973 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000974 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000975 status = -1;
976 }
Nick Coghland6009512014-11-20 21:39:37 +1000977 else
978 Py_DECREF(tmp);
979 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000980
981 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000982}
983
984/* Undo the effect of Py_Initialize().
985
986 Beware: if multiple interpreter and/or thread states exist, these
987 are not wiped out; only the current thread and interpreter state
988 are deleted. But since everything else is deleted, those other
989 interpreter and thread states should no longer be used.
990
991 (XXX We should do better, e.g. wipe out all interpreters and
992 threads.)
993
994 Locking: as above.
995
996*/
997
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000998int
999Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001000{
1001 PyInterpreterState *interp;
1002 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001003 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001004
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001005 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001006 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001007
1008 wait_for_thread_shutdown();
1009
Marcel Plch776407f2017-12-20 11:17:58 +01001010 /* Get current thread state and interpreter pointer */
1011 tstate = PyThreadState_GET();
1012 interp = tstate->interp;
1013
Nick Coghland6009512014-11-20 21:39:37 +10001014 /* The interpreter is still entirely intact at this point, and the
1015 * exit funcs may be relying on that. In particular, if some thread
1016 * or exit func is still waiting to do an import, the import machinery
1017 * expects Py_IsInitialized() to return true. So don't say the
1018 * interpreter is uninitialized until after the exit funcs have run.
1019 * Note that Threading.py uses an exit func to do a join on all the
1020 * threads created thru it, so this also protects pending imports in
1021 * the threads created via Threading.
1022 */
Nick Coghland6009512014-11-20 21:39:37 +10001023
Marcel Plch776407f2017-12-20 11:17:58 +01001024 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001025
Victor Stinnerda273412017-12-15 01:46:02 +01001026 /* Copy the core config, PyInterpreterState_Delete() free
1027 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001028#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001029 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001030#endif
1031#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001032 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001033#endif
1034#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001035 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001036#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001037
Nick Coghland6009512014-11-20 21:39:37 +10001038 /* Remaining threads (e.g. daemon threads) will automatically exit
1039 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001040 _PyRuntime.finalizing = tstate;
1041 _PyRuntime.initialized = 0;
1042 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001043
Victor Stinnere0deff32015-03-24 13:46:18 +01001044 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001045 if (flush_std_files() < 0) {
1046 status = -1;
1047 }
Nick Coghland6009512014-11-20 21:39:37 +10001048
1049 /* Disable signal handling */
1050 PyOS_FiniInterrupts();
1051
1052 /* Collect garbage. This may call finalizers; it's nice to call these
1053 * before all modules are destroyed.
1054 * XXX If a __del__ or weakref callback is triggered here, and tries to
1055 * XXX import a module, bad things can happen, because Python no
1056 * XXX longer believes it's initialized.
1057 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1058 * XXX is easy to provoke that way. I've also seen, e.g.,
1059 * XXX Exception exceptions.ImportError: 'No module named sha'
1060 * XXX in <function callback at 0x008F5718> ignored
1061 * XXX but I'm unclear on exactly how that one happens. In any case,
1062 * XXX I haven't seen a real-life report of either of these.
1063 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001064 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001065#ifdef COUNT_ALLOCS
1066 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1067 each collection might release some types from the type
1068 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001069 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001070 /* nothing */;
1071#endif
Eric Snowdae02762017-09-14 00:35:58 -07001072
Nick Coghland6009512014-11-20 21:39:37 +10001073 /* Destroy all modules */
1074 PyImport_Cleanup();
1075
Victor Stinnere0deff32015-03-24 13:46:18 +01001076 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001077 if (flush_std_files() < 0) {
1078 status = -1;
1079 }
Nick Coghland6009512014-11-20 21:39:37 +10001080
1081 /* Collect final garbage. This disposes of cycles created by
1082 * class definitions, for example.
1083 * XXX This is disabled because it caused too many problems. If
1084 * XXX a __del__ or weakref callback triggers here, Python code has
1085 * XXX a hard time running, because even the sys module has been
1086 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1087 * XXX One symptom is a sequence of information-free messages
1088 * XXX coming from threads (if a __del__ or callback is invoked,
1089 * XXX other threads can execute too, and any exception they encounter
1090 * XXX triggers a comedy of errors as subsystem after subsystem
1091 * XXX fails to find what it *expects* to find in sys to help report
1092 * XXX the exception and consequent unexpected failures). I've also
1093 * XXX seen segfaults then, after adding print statements to the
1094 * XXX Python code getting called.
1095 */
1096#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001097 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001098#endif
1099
1100 /* Disable tracemalloc after all Python objects have been destroyed,
1101 so it is possible to use tracemalloc in objects destructor. */
1102 _PyTraceMalloc_Fini();
1103
1104 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1105 _PyImport_Fini();
1106
1107 /* Cleanup typeobject.c's internal caches. */
1108 _PyType_Fini();
1109
1110 /* unload faulthandler module */
1111 _PyFaulthandler_Fini();
1112
1113 /* Debugging stuff */
1114#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001115 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001116#endif
1117 /* dump hash stats */
1118 _PyHash_Fini();
1119
Eric Snowdae02762017-09-14 00:35:58 -07001120#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001121 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001122 _PyDebug_PrintTotalRefs();
1123 }
Eric Snowdae02762017-09-14 00:35:58 -07001124#endif
Nick Coghland6009512014-11-20 21:39:37 +10001125
1126#ifdef Py_TRACE_REFS
1127 /* Display all objects still alive -- this can invoke arbitrary
1128 * __repr__ overrides, so requires a mostly-intact interpreter.
1129 * Alas, a lot of stuff may still be alive now that will be cleaned
1130 * up later.
1131 */
Victor Stinnerda273412017-12-15 01:46:02 +01001132 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001133 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001134 }
Nick Coghland6009512014-11-20 21:39:37 +10001135#endif /* Py_TRACE_REFS */
1136
1137 /* Clear interpreter state and all thread states. */
1138 PyInterpreterState_Clear(interp);
1139
1140 /* Now we decref the exception classes. After this point nothing
1141 can raise an exception. That's okay, because each Fini() method
1142 below has been checked to make sure no exceptions are ever
1143 raised.
1144 */
1145
1146 _PyExc_Fini();
1147
1148 /* Sundry finalizers */
1149 PyMethod_Fini();
1150 PyFrame_Fini();
1151 PyCFunction_Fini();
1152 PyTuple_Fini();
1153 PyList_Fini();
1154 PySet_Fini();
1155 PyBytes_Fini();
1156 PyByteArray_Fini();
1157 PyLong_Fini();
1158 PyFloat_Fini();
1159 PyDict_Fini();
1160 PySlice_Fini();
1161 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001162 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001163 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001164 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001165 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001166
1167 /* Cleanup Unicode implementation */
1168 _PyUnicode_Fini();
1169
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001170 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001171
1172 /* XXX Still allocated:
1173 - various static ad-hoc pointers to interned strings
1174 - int and float free list blocks
1175 - whatever various modules and libraries allocate
1176 */
1177
1178 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1179
1180 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001181 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001182
1183 /* Delete current thread. After this, many C API calls become crashy. */
1184 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001185
Nick Coghland6009512014-11-20 21:39:37 +10001186 PyInterpreterState_Delete(interp);
1187
1188#ifdef Py_TRACE_REFS
1189 /* Display addresses (& refcnts) of all objects still alive.
1190 * An address can be used to find the repr of the object, printed
1191 * above by _Py_PrintReferences.
1192 */
Victor Stinnerda273412017-12-15 01:46:02 +01001193 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001194 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001195 }
Nick Coghland6009512014-11-20 21:39:37 +10001196#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001197#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001198 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001199 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001200 }
Nick Coghland6009512014-11-20 21:39:37 +10001201#endif
1202
1203 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001204
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001205 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001206 return status;
1207}
1208
1209void
1210Py_Finalize(void)
1211{
1212 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001213}
1214
1215/* Create and initialize a new interpreter and thread, and return the
1216 new thread. This requires that Py_Initialize() has been called
1217 first.
1218
1219 Unsuccessful initialization yields a NULL pointer. Note that *no*
1220 exception information is available even in this case -- the
1221 exception information is held in the thread, and there is no
1222 thread.
1223
1224 Locking: as above.
1225
1226*/
1227
Victor Stinnera7368ac2017-11-15 18:11:45 -08001228static _PyInitError
1229new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001230{
1231 PyInterpreterState *interp;
1232 PyThreadState *tstate, *save_tstate;
1233 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001234 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001235
Victor Stinnera7368ac2017-11-15 18:11:45 -08001236 if (!_PyRuntime.initialized) {
1237 return _Py_INIT_ERR("Py_Initialize must be called first");
1238 }
Nick Coghland6009512014-11-20 21:39:37 +10001239
Victor Stinner8a1be612016-03-14 22:07:55 +01001240 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1241 interpreters: disable PyGILState_Check(). */
1242 _PyGILState_check_enabled = 0;
1243
Nick Coghland6009512014-11-20 21:39:37 +10001244 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001245 if (interp == NULL) {
1246 *tstate_p = NULL;
1247 return _Py_INIT_OK();
1248 }
Nick Coghland6009512014-11-20 21:39:37 +10001249
1250 tstate = PyThreadState_New(interp);
1251 if (tstate == NULL) {
1252 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001253 *tstate_p = NULL;
1254 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001255 }
1256
1257 save_tstate = PyThreadState_Swap(tstate);
1258
Eric Snow1abcf672017-05-23 21:46:51 -07001259 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001260 _PyCoreConfig *core_config;
1261 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001262 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001263 core_config = &save_tstate->interp->core_config;
1264 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001265 } else {
1266 /* No current thread state, copy from the main interpreter */
1267 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001268 core_config = &main_interp->core_config;
1269 config = &main_interp->config;
1270 }
1271
1272 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1273 return _Py_INIT_ERR("failed to copy core config");
1274 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001275 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001276 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1277 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001278 }
1279
Nick Coghland6009512014-11-20 21:39:37 +10001280 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001281 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001282 if (modules == NULL) {
1283 return _Py_INIT_ERR("can't make modules dictionary");
1284 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001285 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001286
Eric Snowd393c1b2017-09-14 12:18:12 -06001287 sysmod = _PyImport_FindBuiltin("sys", modules);
1288 if (sysmod != NULL) {
1289 interp->sysdict = PyModule_GetDict(sysmod);
1290 if (interp->sysdict == NULL)
1291 goto handle_error;
1292 Py_INCREF(interp->sysdict);
1293 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001294 _PySys_EndInit(interp->sysdict, interp);
Eric Snowd393c1b2017-09-14 12:18:12 -06001295 }
1296
1297 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001298 if (bimod != NULL) {
1299 interp->builtins = PyModule_GetDict(bimod);
1300 if (interp->builtins == NULL)
1301 goto handle_error;
1302 Py_INCREF(interp->builtins);
1303 }
1304
1305 /* initialize builtin exceptions */
1306 _PyExc_Init(bimod);
1307
Nick Coghland6009512014-11-20 21:39:37 +10001308 if (bimod != NULL && sysmod != NULL) {
1309 PyObject *pstderr;
1310
Nick Coghland6009512014-11-20 21:39:37 +10001311 /* Set up a preliminary stderr printer until we have enough
1312 infrastructure for the io module in place. */
1313 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001314 if (pstderr == NULL) {
1315 return _Py_INIT_ERR("can't set preliminary stderr");
1316 }
Nick Coghland6009512014-11-20 21:39:37 +10001317 _PySys_SetObjectId(&PyId_stderr, pstderr);
1318 PySys_SetObject("__stderr__", pstderr);
1319 Py_DECREF(pstderr);
1320
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001321 err = _PyImportHooks_Init();
1322 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001323 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001324 }
Nick Coghland6009512014-11-20 21:39:37 +10001325
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001326 err = initimport(interp, sysmod);
1327 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001328 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001329 }
Nick Coghland6009512014-11-20 21:39:37 +10001330
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001331 err = initexternalimport(interp);
1332 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001333 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001334 }
Nick Coghland6009512014-11-20 21:39:37 +10001335
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001336 err = initfsencoding(interp);
1337 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001338 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001339 }
1340
Victor Stinner91106cd2017-12-13 12:29:09 +01001341 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001342 if (_Py_INIT_FAILED(err)) {
1343 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001344 }
1345
1346 err = add_main_module(interp);
1347 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001348 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001349 }
1350
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001351 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001352 err = initsite();
1353 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001354 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001355 }
1356 }
Nick Coghland6009512014-11-20 21:39:37 +10001357 }
1358
Victor Stinnera7368ac2017-11-15 18:11:45 -08001359 if (PyErr_Occurred()) {
1360 goto handle_error;
1361 }
Nick Coghland6009512014-11-20 21:39:37 +10001362
Victor Stinnera7368ac2017-11-15 18:11:45 -08001363 *tstate_p = tstate;
1364 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001365
Nick Coghland6009512014-11-20 21:39:37 +10001366handle_error:
1367 /* Oops, it didn't work. Undo it all. */
1368
1369 PyErr_PrintEx(0);
1370 PyThreadState_Clear(tstate);
1371 PyThreadState_Swap(save_tstate);
1372 PyThreadState_Delete(tstate);
1373 PyInterpreterState_Delete(interp);
1374
Victor Stinnera7368ac2017-11-15 18:11:45 -08001375 *tstate_p = NULL;
1376 return _Py_INIT_OK();
1377}
1378
1379PyThreadState *
1380Py_NewInterpreter(void)
1381{
1382 PyThreadState *tstate;
1383 _PyInitError err = new_interpreter(&tstate);
1384 if (_Py_INIT_FAILED(err)) {
1385 _Py_FatalInitError(err);
1386 }
1387 return tstate;
1388
Nick Coghland6009512014-11-20 21:39:37 +10001389}
1390
1391/* Delete an interpreter and its last thread. This requires that the
1392 given thread state is current, that the thread has no remaining
1393 frames, and that it is its interpreter's only remaining thread.
1394 It is a fatal error to violate these constraints.
1395
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001396 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001397 everything, regardless.)
1398
1399 Locking: as above.
1400
1401*/
1402
1403void
1404Py_EndInterpreter(PyThreadState *tstate)
1405{
1406 PyInterpreterState *interp = tstate->interp;
1407
1408 if (tstate != PyThreadState_GET())
1409 Py_FatalError("Py_EndInterpreter: thread is not current");
1410 if (tstate->frame != NULL)
1411 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1412
1413 wait_for_thread_shutdown();
1414
Marcel Plch776407f2017-12-20 11:17:58 +01001415 call_py_exitfuncs(interp);
1416
Nick Coghland6009512014-11-20 21:39:37 +10001417 if (tstate != interp->tstate_head || tstate->next != NULL)
1418 Py_FatalError("Py_EndInterpreter: not the last thread");
1419
1420 PyImport_Cleanup();
1421 PyInterpreterState_Clear(interp);
1422 PyThreadState_Swap(NULL);
1423 PyInterpreterState_Delete(interp);
1424}
1425
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001426/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001427
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001428static _PyInitError
1429add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001430{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001431 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001432 m = PyImport_AddModule("__main__");
1433 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001434 return _Py_INIT_ERR("can't create __main__ module");
1435
Nick Coghland6009512014-11-20 21:39:37 +10001436 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001437 ann_dict = PyDict_New();
1438 if ((ann_dict == NULL) ||
1439 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001440 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001441 }
1442 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001443
Nick Coghland6009512014-11-20 21:39:37 +10001444 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1445 PyObject *bimod = PyImport_ImportModule("builtins");
1446 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001447 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001448 }
1449 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001450 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001451 }
1452 Py_DECREF(bimod);
1453 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001454
Nick Coghland6009512014-11-20 21:39:37 +10001455 /* Main is a little special - imp.is_builtin("__main__") will return
1456 * False, but BuiltinImporter is still the most appropriate initial
1457 * setting for its __loader__ attribute. A more suitable value will
1458 * be set if __main__ gets further initialized later in the startup
1459 * process.
1460 */
1461 loader = PyDict_GetItemString(d, "__loader__");
1462 if (loader == NULL || loader == Py_None) {
1463 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1464 "BuiltinImporter");
1465 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001466 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001467 }
1468 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001469 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001470 }
1471 Py_DECREF(loader);
1472 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001473 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001474}
1475
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001476static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001477initfsencoding(PyInterpreterState *interp)
1478{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001479 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001480
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001481 char *encoding = get_codec_name(config->filesystem_encoding);
1482 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001483 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001484 memory, import a module of the standard library failed, etc. */
1485 return _Py_INIT_ERR("failed to get the Python codec "
1486 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001487 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001488
1489 /* Update the filesystem encoding to the normalized Python codec name.
1490 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1491 (Python codec name). */
1492 PyMem_RawFree(config->filesystem_encoding);
1493 config->filesystem_encoding = encoding;
1494
1495 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1496 global configuration variables. */
1497 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1498 config->filesystem_errors) < 0) {
1499 return _Py_INIT_NO_MEMORY();
1500 }
1501
1502 /* PyUnicode can now use the Python codec rather than C implementation
1503 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001504 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001505 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001506}
1507
1508/* Import the site module (not into __main__ though) */
1509
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001510static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001511initsite(void)
1512{
1513 PyObject *m;
1514 m = PyImport_ImportModule("site");
1515 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001516 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001517 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001518 Py_DECREF(m);
1519 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001520}
1521
Victor Stinner874dbe82015-09-04 17:29:57 +02001522/* Check if a file descriptor is valid or not.
1523 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1524static int
1525is_valid_fd(int fd)
1526{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001527#ifdef __APPLE__
1528 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1529 and the other side of the pipe is closed, dup(1) succeed, whereas
1530 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1531 such error. */
1532 struct stat st;
1533 return (fstat(fd, &st) == 0);
1534#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001535 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001536 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001537 return 0;
1538 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001539 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1540 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1541 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001542 fd2 = dup(fd);
1543 if (fd2 >= 0)
1544 close(fd2);
1545 _Py_END_SUPPRESS_IPH
1546 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001547#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001548}
1549
1550/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001551static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001552create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001553 int fd, int write_mode, const char* name,
1554 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001555{
1556 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1557 const char* mode;
1558 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001559 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001560 int buffering, isatty;
1561 _Py_IDENTIFIER(open);
1562 _Py_IDENTIFIER(isatty);
1563 _Py_IDENTIFIER(TextIOWrapper);
1564 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001565 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001566
Victor Stinner874dbe82015-09-04 17:29:57 +02001567 if (!is_valid_fd(fd))
1568 Py_RETURN_NONE;
1569
Nick Coghland6009512014-11-20 21:39:37 +10001570 /* stdin is always opened in buffered mode, first because it shouldn't
1571 make a difference in common use cases, second because TextIOWrapper
1572 depends on the presence of a read1() method which only exists on
1573 buffered streams.
1574 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001575 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001576 buffering = 0;
1577 else
1578 buffering = -1;
1579 if (write_mode)
1580 mode = "wb";
1581 else
1582 mode = "rb";
1583 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1584 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001585 Py_None, Py_None, /* encoding, errors */
1586 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001587 if (buf == NULL)
1588 goto error;
1589
1590 if (buffering) {
1591 _Py_IDENTIFIER(raw);
1592 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1593 if (raw == NULL)
1594 goto error;
1595 }
1596 else {
1597 raw = buf;
1598 Py_INCREF(raw);
1599 }
1600
Steve Dower39294992016-08-30 21:22:36 -07001601#ifdef MS_WINDOWS
1602 /* Windows console IO is always UTF-8 encoded */
1603 if (PyWindowsConsoleIO_Check(raw))
1604 encoding = "utf-8";
1605#endif
1606
Nick Coghland6009512014-11-20 21:39:37 +10001607 text = PyUnicode_FromString(name);
1608 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1609 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001610 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001611 if (res == NULL)
1612 goto error;
1613 isatty = PyObject_IsTrue(res);
1614 Py_DECREF(res);
1615 if (isatty == -1)
1616 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001617 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001618 write_through = Py_True;
1619 else
1620 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001621 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001622 line_buffering = Py_True;
1623 else
1624 line_buffering = Py_False;
1625
1626 Py_CLEAR(raw);
1627 Py_CLEAR(text);
1628
1629#ifdef MS_WINDOWS
1630 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1631 newlines to "\n".
1632 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1633 newline = NULL;
1634#else
1635 /* sys.stdin: split lines at "\n".
1636 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1637 newline = "\n";
1638#endif
1639
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001640 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001641 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001642 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001643 Py_CLEAR(buf);
1644 if (stream == NULL)
1645 goto error;
1646
1647 if (write_mode)
1648 mode = "w";
1649 else
1650 mode = "r";
1651 text = PyUnicode_FromString(mode);
1652 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1653 goto error;
1654 Py_CLEAR(text);
1655 return stream;
1656
1657error:
1658 Py_XDECREF(buf);
1659 Py_XDECREF(stream);
1660 Py_XDECREF(text);
1661 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001662
Victor Stinner874dbe82015-09-04 17:29:57 +02001663 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1664 /* Issue #24891: the file descriptor was closed after the first
1665 is_valid_fd() check was called. Ignore the OSError and set the
1666 stream to None. */
1667 PyErr_Clear();
1668 Py_RETURN_NONE;
1669 }
1670 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001671}
1672
1673/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001674static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001675init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001676{
1677 PyObject *iomod = NULL, *wrapper;
1678 PyObject *bimod = NULL;
1679 PyObject *m;
1680 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001681 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001682 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001683 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001684 _PyCoreConfig *config = &interp->core_config;
1685
1686 char *codec_name = get_codec_name(config->stdio_encoding);
1687 if (codec_name == NULL) {
1688 return _Py_INIT_ERR("failed to get the Python codec name "
1689 "of the stdio encoding");
1690 }
1691 PyMem_RawFree(config->stdio_encoding);
1692 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001693
1694 /* Hack to avoid a nasty recursion issue when Python is invoked
1695 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1696 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1697 goto error;
1698 }
1699 Py_DECREF(m);
1700
1701 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1702 goto error;
1703 }
1704 Py_DECREF(m);
1705
1706 if (!(bimod = PyImport_ImportModule("builtins"))) {
1707 goto error;
1708 }
1709
1710 if (!(iomod = PyImport_ImportModule("io"))) {
1711 goto error;
1712 }
1713 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1714 goto error;
1715 }
1716
1717 /* Set builtins.open */
1718 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1719 Py_DECREF(wrapper);
1720 goto error;
1721 }
1722 Py_DECREF(wrapper);
1723
Nick Coghland6009512014-11-20 21:39:37 +10001724 /* Set sys.stdin */
1725 fd = fileno(stdin);
1726 /* Under some conditions stdin, stdout and stderr may not be connected
1727 * and fileno() may point to an invalid file descriptor. For example
1728 * GUI apps don't have valid standard streams by default.
1729 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001730 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001731 config->stdio_encoding,
1732 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001733 if (std == NULL)
1734 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001735 PySys_SetObject("__stdin__", std);
1736 _PySys_SetObjectId(&PyId_stdin, std);
1737 Py_DECREF(std);
1738
1739 /* Set sys.stdout */
1740 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001741 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001742 config->stdio_encoding,
1743 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001744 if (std == NULL)
1745 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001746 PySys_SetObject("__stdout__", std);
1747 _PySys_SetObjectId(&PyId_stdout, std);
1748 Py_DECREF(std);
1749
1750#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1751 /* Set sys.stderr, replaces the preliminary stderr */
1752 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001753 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001754 config->stdio_encoding,
1755 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001756 if (std == NULL)
1757 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001758
1759 /* Same as hack above, pre-import stderr's codec to avoid recursion
1760 when import.c tries to write to stderr in verbose mode. */
1761 encoding_attr = PyObject_GetAttrString(std, "encoding");
1762 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001763 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001764 if (std_encoding != NULL) {
1765 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1766 Py_XDECREF(codec_info);
1767 }
1768 Py_DECREF(encoding_attr);
1769 }
1770 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1771
1772 if (PySys_SetObject("__stderr__", std) < 0) {
1773 Py_DECREF(std);
1774 goto error;
1775 }
1776 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1777 Py_DECREF(std);
1778 goto error;
1779 }
1780 Py_DECREF(std);
1781#endif
1782
Victor Stinnera7368ac2017-11-15 18:11:45 -08001783 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001784
Victor Stinnera7368ac2017-11-15 18:11:45 -08001785error:
1786 res = _Py_INIT_ERR("can't initialize sys standard streams");
1787
1788done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001789 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001790
Nick Coghland6009512014-11-20 21:39:37 +10001791 Py_XDECREF(bimod);
1792 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001793 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001794}
1795
1796
Victor Stinner10dc4842015-03-24 12:01:30 +01001797static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001798_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001799{
Victor Stinner10dc4842015-03-24 12:01:30 +01001800 fputc('\n', stderr);
1801 fflush(stderr);
1802
1803 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001804 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001805}
Victor Stinner791da1c2016-03-14 16:53:12 +01001806
1807/* Print the current exception (if an exception is set) with its traceback,
1808 or display the current Python stack.
1809
1810 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1811 called on catastrophic cases.
1812
1813 Return 1 if the traceback was displayed, 0 otherwise. */
1814
1815static int
1816_Py_FatalError_PrintExc(int fd)
1817{
1818 PyObject *ferr, *res;
1819 PyObject *exception, *v, *tb;
1820 int has_tb;
1821
1822 if (PyThreadState_GET() == NULL) {
1823 /* The GIL is released: trying to acquire it is likely to deadlock,
1824 just give up. */
1825 return 0;
1826 }
1827
1828 PyErr_Fetch(&exception, &v, &tb);
1829 if (exception == NULL) {
1830 /* No current exception */
1831 return 0;
1832 }
1833
1834 ferr = _PySys_GetObjectId(&PyId_stderr);
1835 if (ferr == NULL || ferr == Py_None) {
1836 /* sys.stderr is not set yet or set to None,
1837 no need to try to display the exception */
1838 return 0;
1839 }
1840
1841 PyErr_NormalizeException(&exception, &v, &tb);
1842 if (tb == NULL) {
1843 tb = Py_None;
1844 Py_INCREF(tb);
1845 }
1846 PyException_SetTraceback(v, tb);
1847 if (exception == NULL) {
1848 /* PyErr_NormalizeException() failed */
1849 return 0;
1850 }
1851
1852 has_tb = (tb != Py_None);
1853 PyErr_Display(exception, v, tb);
1854 Py_XDECREF(exception);
1855 Py_XDECREF(v);
1856 Py_XDECREF(tb);
1857
1858 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001859 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001860 if (res == NULL)
1861 PyErr_Clear();
1862 else
1863 Py_DECREF(res);
1864
1865 return has_tb;
1866}
1867
Nick Coghland6009512014-11-20 21:39:37 +10001868/* Print fatal error message and abort */
1869
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001870#ifdef MS_WINDOWS
1871static void
1872fatal_output_debug(const char *msg)
1873{
1874 /* buffer of 256 bytes allocated on the stack */
1875 WCHAR buffer[256 / sizeof(WCHAR)];
1876 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1877 size_t msglen;
1878
1879 OutputDebugStringW(L"Fatal Python error: ");
1880
1881 msglen = strlen(msg);
1882 while (msglen) {
1883 size_t i;
1884
1885 if (buflen > msglen) {
1886 buflen = msglen;
1887 }
1888
1889 /* Convert the message to wchar_t. This uses a simple one-to-one
1890 conversion, assuming that the this error message actually uses
1891 ASCII only. If this ceases to be true, we will have to convert. */
1892 for (i=0; i < buflen; ++i) {
1893 buffer[i] = msg[i];
1894 }
1895 buffer[i] = L'\0';
1896 OutputDebugStringW(buffer);
1897
1898 msg += buflen;
1899 msglen -= buflen;
1900 }
1901 OutputDebugStringW(L"\n");
1902}
1903#endif
1904
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001905static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001906fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001907{
1908 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001909 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001910
1911 if (reentrant) {
1912 /* Py_FatalError() caused a second fatal error.
1913 Example: flush_std_files() raises a recursion error. */
1914 goto exit;
1915 }
1916 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001917
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001918 fprintf(stderr, "Fatal Python error: ");
1919 if (prefix) {
1920 fputs(prefix, stderr);
1921 fputs(": ", stderr);
1922 }
1923 if (msg) {
1924 fputs(msg, stderr);
1925 }
1926 else {
1927 fprintf(stderr, "<message not set>");
1928 }
1929 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001930 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001931
Victor Stinnere0deff32015-03-24 13:46:18 +01001932 /* Print the exception (if an exception is set) with its traceback,
1933 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001934 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001935 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001936 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001937
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001938 /* The main purpose of faulthandler is to display the traceback.
1939 This function already did its best to display a traceback.
1940 Disable faulthandler to prevent writing a second traceback
1941 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001942 _PyFaulthandler_Fini();
1943
Victor Stinner791da1c2016-03-14 16:53:12 +01001944 /* Check if the current Python thread hold the GIL */
1945 if (PyThreadState_GET() != NULL) {
1946 /* Flush sys.stdout and sys.stderr */
1947 flush_std_files();
1948 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001949
Nick Coghland6009512014-11-20 21:39:37 +10001950#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001951 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001952#endif /* MS_WINDOWS */
1953
1954exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001955 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01001956#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001957 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10001958#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001959 abort();
1960 }
1961 else {
1962 exit(status);
1963 }
1964}
1965
Victor Stinner19760862017-12-20 01:41:59 +01001966void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001967Py_FatalError(const char *msg)
1968{
1969 fatal_error(NULL, msg, -1);
1970}
1971
Victor Stinner19760862017-12-20 01:41:59 +01001972void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001973_Py_FatalInitError(_PyInitError err)
1974{
1975 /* On "user" error: exit with status 1.
1976 For all other errors, call abort(). */
1977 int status = err.user_err ? 1 : -1;
1978 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10001979}
1980
1981/* Clean up and exit */
1982
Victor Stinnerd7292b52016-06-17 12:29:00 +02001983# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001984
Nick Coghland6009512014-11-20 21:39:37 +10001985/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01001986void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10001987{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001988 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01001989
Antoine Pitroufc5db952017-12-13 02:29:07 +01001990 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01001991 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
1992
1993 is->pyexitfunc = func;
1994 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10001995}
1996
1997static void
Marcel Plch776407f2017-12-20 11:17:58 +01001998call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10001999{
Marcel Plch776407f2017-12-20 11:17:58 +01002000 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002001 return;
2002
Marcel Plch776407f2017-12-20 11:17:58 +01002003 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002004 PyErr_Clear();
2005}
2006
2007/* Wait until threading._shutdown completes, provided
2008 the threading module was imported in the first place.
2009 The shutdown routine will wait until all non-daemon
2010 "threading" threads have completed. */
2011static void
2012wait_for_thread_shutdown(void)
2013{
Nick Coghland6009512014-11-20 21:39:37 +10002014 _Py_IDENTIFIER(_shutdown);
2015 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002016 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002017 if (threading == NULL) {
2018 /* threading not imported */
2019 PyErr_Clear();
2020 return;
2021 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002022 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002023 if (result == NULL) {
2024 PyErr_WriteUnraisable(threading);
2025 }
2026 else {
2027 Py_DECREF(result);
2028 }
2029 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002030}
2031
2032#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002033int Py_AtExit(void (*func)(void))
2034{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002035 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002036 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002037 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002038 return 0;
2039}
2040
2041static void
2042call_ll_exitfuncs(void)
2043{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002044 while (_PyRuntime.nexitfuncs > 0)
2045 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002046
2047 fflush(stdout);
2048 fflush(stderr);
2049}
2050
Victor Stinnercfc88312018-08-01 16:41:25 +02002051void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002052Py_Exit(int sts)
2053{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002054 if (Py_FinalizeEx() < 0) {
2055 sts = 120;
2056 }
Nick Coghland6009512014-11-20 21:39:37 +10002057
2058 exit(sts);
2059}
2060
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002061static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002062initsigs(void)
2063{
2064#ifdef SIGPIPE
2065 PyOS_setsig(SIGPIPE, SIG_IGN);
2066#endif
2067#ifdef SIGXFZ
2068 PyOS_setsig(SIGXFZ, SIG_IGN);
2069#endif
2070#ifdef SIGXFSZ
2071 PyOS_setsig(SIGXFSZ, SIG_IGN);
2072#endif
2073 PyOS_InitInterrupts(); /* May imply initsignal() */
2074 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002075 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002076 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002077 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002078}
2079
2080
2081/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2082 *
2083 * All of the code in this function must only use async-signal-safe functions,
2084 * listed at `man 7 signal` or
2085 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2086 */
2087void
2088_Py_RestoreSignals(void)
2089{
2090#ifdef SIGPIPE
2091 PyOS_setsig(SIGPIPE, SIG_DFL);
2092#endif
2093#ifdef SIGXFZ
2094 PyOS_setsig(SIGXFZ, SIG_DFL);
2095#endif
2096#ifdef SIGXFSZ
2097 PyOS_setsig(SIGXFSZ, SIG_DFL);
2098#endif
2099}
2100
2101
2102/*
2103 * The file descriptor fd is considered ``interactive'' if either
2104 * a) isatty(fd) is TRUE, or
2105 * b) the -i flag was given, and the filename associated with
2106 * the descriptor is NULL or "<stdin>" or "???".
2107 */
2108int
2109Py_FdIsInteractive(FILE *fp, const char *filename)
2110{
2111 if (isatty((int)fileno(fp)))
2112 return 1;
2113 if (!Py_InteractiveFlag)
2114 return 0;
2115 return (filename == NULL) ||
2116 (strcmp(filename, "<stdin>") == 0) ||
2117 (strcmp(filename, "???") == 0);
2118}
2119
2120
Nick Coghland6009512014-11-20 21:39:37 +10002121/* Wrappers around sigaction() or signal(). */
2122
2123PyOS_sighandler_t
2124PyOS_getsig(int sig)
2125{
2126#ifdef HAVE_SIGACTION
2127 struct sigaction context;
2128 if (sigaction(sig, NULL, &context) == -1)
2129 return SIG_ERR;
2130 return context.sa_handler;
2131#else
2132 PyOS_sighandler_t handler;
2133/* Special signal handling for the secure CRT in Visual Studio 2005 */
2134#if defined(_MSC_VER) && _MSC_VER >= 1400
2135 switch (sig) {
2136 /* Only these signals are valid */
2137 case SIGINT:
2138 case SIGILL:
2139 case SIGFPE:
2140 case SIGSEGV:
2141 case SIGTERM:
2142 case SIGBREAK:
2143 case SIGABRT:
2144 break;
2145 /* Don't call signal() with other values or it will assert */
2146 default:
2147 return SIG_ERR;
2148 }
2149#endif /* _MSC_VER && _MSC_VER >= 1400 */
2150 handler = signal(sig, SIG_IGN);
2151 if (handler != SIG_ERR)
2152 signal(sig, handler);
2153 return handler;
2154#endif
2155}
2156
2157/*
2158 * All of the code in this function must only use async-signal-safe functions,
2159 * listed at `man 7 signal` or
2160 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2161 */
2162PyOS_sighandler_t
2163PyOS_setsig(int sig, PyOS_sighandler_t handler)
2164{
2165#ifdef HAVE_SIGACTION
2166 /* Some code in Modules/signalmodule.c depends on sigaction() being
2167 * used here if HAVE_SIGACTION is defined. Fix that if this code
2168 * changes to invalidate that assumption.
2169 */
2170 struct sigaction context, ocontext;
2171 context.sa_handler = handler;
2172 sigemptyset(&context.sa_mask);
2173 context.sa_flags = 0;
2174 if (sigaction(sig, &context, &ocontext) == -1)
2175 return SIG_ERR;
2176 return ocontext.sa_handler;
2177#else
2178 PyOS_sighandler_t oldhandler;
2179 oldhandler = signal(sig, handler);
2180#ifdef HAVE_SIGINTERRUPT
2181 siginterrupt(sig, 1);
2182#endif
2183 return oldhandler;
2184#endif
2185}
2186
2187#ifdef __cplusplus
2188}
2189#endif