blob: 5d5ec4a63200ce8b511e98d0d67cae7e7ee8a657 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinner27e2d1f2018-11-01 00:52:28 +01007#include "pycore_context.h"
Victor Stinner353933e2018-11-23 13:08:26 +01008#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01009#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010010#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010011#include "pycore_pylifecycle.h"
12#include "pycore_pymem.h"
13#include "pycore_pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100014#include "grammar.h"
15#include "node.h"
16#include "token.h"
17#include "parsetok.h"
18#include "errcode.h"
19#include "code.h"
20#include "symtable.h"
21#include "ast.h"
22#include "marshal.h"
23#include "osdefs.h"
24#include <locale.h>
25
26#ifdef HAVE_SIGNAL_H
27#include <signal.h>
28#endif
29
30#ifdef MS_WINDOWS
31#include "malloc.h" /* for alloca */
32#endif
33
34#ifdef HAVE_LANGINFO_H
35#include <langinfo.h>
36#endif
37
38#ifdef MS_WINDOWS
39#undef BYTE
40#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070041
42extern PyTypeObject PyWindowsConsoleIO_Type;
43#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100044#endif
45
46_Py_IDENTIFIER(flush);
47_Py_IDENTIFIER(name);
48_Py_IDENTIFIER(stdin);
49_Py_IDENTIFIER(stdout);
50_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060051_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100052
53#ifdef __cplusplus
54extern "C" {
55#endif
56
Nick Coghland6009512014-11-20 21:39:37 +100057extern grammar _PyParser_Grammar; /* From graminit.c */
58
59/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError add_main_module(PyInterpreterState *interp);
61static _PyInitError initfsencoding(PyInterpreterState *interp);
62static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010063static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080064static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010065static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100066static void wait_for_thread_shutdown(void);
67static void call_ll_exitfuncs(void);
Nick Coghland6009512014-11-20 21:39:37 +100068
Victor Stinnerf7e5b562017-11-15 15:48:08 -080069_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060070
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060072_PyRuntime_Initialize(void)
73{
74 /* XXX We only initialize once in the process, which aligns with
75 the static initialization of the former globals now found in
76 _PyRuntime. However, _PyRuntime *should* be initialized with
77 every Py_Initialize() call, but doing so breaks the runtime.
78 This is because the runtime state is not properly finalized
79 currently. */
80 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081 if (initialized) {
82 return _Py_INIT_OK();
83 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060084 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080085
86 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087}
88
89void
90_PyRuntime_Finalize(void)
91{
92 _PyRuntimeState_Fini(&_PyRuntime);
93}
94
95int
96_Py_IsFinalizing(void)
97{
98 return _PyRuntime.finalizing != NULL;
99}
100
Nick Coghland6009512014-11-20 21:39:37 +1000101/* Hack to force loading of object files */
102int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
103 PyOS_mystrnicmp; /* Python/pystrcmp.o */
104
105/* PyModule_GetWarningsModule is no longer necessary as of 2.6
106since _warnings is builtin. This API should not be used. */
107PyObject *
108PyModule_GetWarningsModule(void)
109{
110 return PyImport_ImportModule("warnings");
111}
112
Eric Snowc7ec9982017-05-23 23:00:52 -0700113
Eric Snow1abcf672017-05-23 21:46:51 -0700114/* APIs to access the initialization flags
115 *
116 * Can be called prior to Py_Initialize.
117 */
Nick Coghland6009512014-11-20 21:39:37 +1000118
Eric Snow1abcf672017-05-23 21:46:51 -0700119int
120_Py_IsCoreInitialized(void)
121{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700123}
Nick Coghland6009512014-11-20 21:39:37 +1000124
125int
126Py_IsInitialized(void)
127{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600128 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000129}
130
Nick Coghlan6ea41862017-06-11 13:16:15 +1000131
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000132/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
133 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000134 initializations fail, a fatal error is issued and the function does
135 not return. On return, the first thread and interpreter state have
136 been created.
137
138 Locking: you must hold the interpreter lock while calling this.
139 (If the lock has not yet been initialized, that's equivalent to
140 having the lock, but you cannot use multiple threads.)
141
142*/
143
Nick Coghland6009512014-11-20 21:39:37 +1000144static char*
145get_codec_name(const char *encoding)
146{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200147 const char *name_utf8;
148 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000149 PyObject *codec, *name = NULL;
150
151 codec = _PyCodec_Lookup(encoding);
152 if (!codec)
153 goto error;
154
155 name = _PyObject_GetAttrId(codec, &PyId_name);
156 Py_CLEAR(codec);
157 if (!name)
158 goto error;
159
Serhiy Storchaka06515832016-11-20 09:13:07 +0200160 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000161 if (name_utf8 == NULL)
162 goto error;
163 name_str = _PyMem_RawStrdup(name_utf8);
164 Py_DECREF(name);
165 if (name_str == NULL) {
166 PyErr_NoMemory();
167 return NULL;
168 }
169 return name_str;
170
171error:
172 Py_XDECREF(codec);
173 Py_XDECREF(name);
174 return NULL;
175}
176
Nick Coghland6009512014-11-20 21:39:37 +1000177
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800178static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700179initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000180{
181 PyObject *importlib;
182 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000183 PyObject *value;
184
185 /* Import _importlib through its frozen version, _frozen_importlib. */
186 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800187 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000188 }
189 else if (Py_VerboseFlag) {
190 PySys_FormatStderr("import _frozen_importlib # frozen\n");
191 }
192 importlib = PyImport_AddModule("_frozen_importlib");
193 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800194 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000195 }
196 interp->importlib = importlib;
197 Py_INCREF(interp->importlib);
198
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300199 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
200 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800201 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300202 Py_INCREF(interp->import_func);
203
Victor Stinnercd6e6942015-09-18 09:11:57 +0200204 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800205 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000206 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800207 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000208 }
209 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200210 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000211 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600212 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800213 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000214 }
215
Victor Stinnercd6e6942015-09-18 09:11:57 +0200216 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000217 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
218 if (value == NULL) {
219 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800220 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000221 }
222 Py_DECREF(value);
223 Py_DECREF(impmod);
224
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800225 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000226}
227
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800228static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700229initexternalimport(PyInterpreterState *interp)
230{
231 PyObject *value;
232 value = PyObject_CallMethod(interp->importlib,
233 "_install_external_importers", "");
234 if (value == NULL) {
235 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800236 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700237 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200238 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300239 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700240}
Nick Coghland6009512014-11-20 21:39:37 +1000241
Nick Coghlan6ea41862017-06-11 13:16:15 +1000242/* Helper functions to better handle the legacy C locale
243 *
244 * The legacy C locale assumes ASCII as the default text encoding, which
245 * causes problems not only for the CPython runtime, but also other
246 * components like GNU readline.
247 *
248 * Accordingly, when the CLI detects it, it attempts to coerce it to a
249 * more capable UTF-8 based alternative as follows:
250 *
251 * if (_Py_LegacyLocaleDetected()) {
252 * _Py_CoerceLegacyLocale();
253 * }
254 *
255 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
256 *
257 * Locale coercion also impacts the default error handler for the standard
258 * streams: while the usual default is "strict", the default for the legacy
259 * C locale and for any of the coercion target locales is "surrogateescape".
260 */
261
262int
263_Py_LegacyLocaleDetected(void)
264{
265#ifndef MS_WINDOWS
266 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000267 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
268 * the POSIX locale as a simple alias for the C locale, so
269 * we may also want to check for that explicitly.
270 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000271 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
272 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
273#else
274 /* Windows uses code pages instead of locales, so no locale is legacy */
275 return 0;
276#endif
277}
278
Nick Coghlaneb817952017-06-18 12:29:42 +1000279static const char *_C_LOCALE_WARNING =
280 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
281 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
282 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
283 "locales is recommended.\n";
284
Nick Coghlaneb817952017-06-18 12:29:42 +1000285static void
Victor Stinner94540602017-12-16 04:54:22 +0100286_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000287{
Victor Stinner06e76082018-09-19 14:56:36 -0700288 if (core_config->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200289 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000290 }
291}
292
Nick Coghlan6ea41862017-06-11 13:16:15 +1000293typedef struct _CandidateLocale {
294 const char *locale_name; /* The locale to try as a coercion target */
295} _LocaleCoercionTarget;
296
297static _LocaleCoercionTarget _TARGET_LOCALES[] = {
298 {"C.UTF-8"},
299 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000300 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000301 {NULL}
302};
303
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200304
305int
306_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000307{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200308 const _LocaleCoercionTarget *target = NULL;
309 for (target = _TARGET_LOCALES; target->locale_name; target++) {
310 if (strcmp(ctype_loc, target->locale_name) == 0) {
311 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200313 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200314 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315}
316
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200317
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100319static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000320 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
321 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
322
323static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200324_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000325{
326 const char *newloc = target->locale_name;
327
328 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100329 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000330
331 /* Set the relevant locale environment variable */
332 if (setenv("LC_CTYPE", newloc, 1)) {
333 fprintf(stderr,
334 "Error setting LC_CTYPE, skipping C locale coercion\n");
335 return;
336 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200337 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100338 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000339 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000340
341 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100342 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000343}
344#endif
345
346void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200347_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000348{
349#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200350 char *oldloc = NULL;
351
352 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
353 if (oldloc == NULL) {
354 return;
355 }
356
Victor Stinner94540602017-12-16 04:54:22 +0100357 const char *locale_override = getenv("LC_ALL");
358 if (locale_override == NULL || *locale_override == '\0') {
359 /* LC_ALL is also not set (or is set to an empty string) */
360 const _LocaleCoercionTarget *target = NULL;
361 for (target = _TARGET_LOCALES; target->locale_name; target++) {
362 const char *new_locale = setlocale(LC_CTYPE,
363 target->locale_name);
364 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100365#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100366defined(HAVE_LANGINFO_H) && defined(CODESET)
367 /* Also ensure that nl_langinfo works in this locale */
368 char *codeset = nl_langinfo(CODESET);
369 if (!codeset || *codeset == '\0') {
370 /* CODESET is not set or empty, so skip coercion */
371 new_locale = NULL;
372 _Py_SetLocaleFromEnv(LC_CTYPE);
373 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000374 }
Victor Stinner94540602017-12-16 04:54:22 +0100375#endif
376 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200377 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200378 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000379 }
380 }
381 }
382 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200383
384 setlocale(LC_CTYPE, oldloc);
385
386done:
387 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000388#endif
389}
390
xdegaye1588be62017-11-12 12:45:59 +0100391/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
392 * isolate the idiosyncrasies of different libc implementations. It reads the
393 * appropriate environment variable and uses its value to select the locale for
394 * 'category'. */
395char *
396_Py_SetLocaleFromEnv(int category)
397{
Victor Stinner353933e2018-11-23 13:08:26 +0100398 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100399#ifdef __ANDROID__
400 const char *locale;
401 const char **pvar;
402#ifdef PY_COERCE_C_LOCALE
403 const char *coerce_c_locale;
404#endif
405 const char *utf8_locale = "C.UTF-8";
406 const char *env_var_set[] = {
407 "LC_ALL",
408 "LC_CTYPE",
409 "LANG",
410 NULL,
411 };
412
413 /* Android setlocale(category, "") doesn't check the environment variables
414 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
415 * check the environment variables listed in env_var_set. */
416 for (pvar=env_var_set; *pvar; pvar++) {
417 locale = getenv(*pvar);
418 if (locale != NULL && *locale != '\0') {
419 if (strcmp(locale, utf8_locale) == 0 ||
420 strcmp(locale, "en_US.UTF-8") == 0) {
421 return setlocale(category, utf8_locale);
422 }
423 return setlocale(category, "C");
424 }
425 }
426
427 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
428 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
429 * Quote from POSIX section "8.2 Internationalization Variables":
430 * "4. If the LANG environment variable is not set or is set to the empty
431 * string, the implementation-defined default locale shall be used." */
432
433#ifdef PY_COERCE_C_LOCALE
434 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
435 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
436 /* Some other ported code may check the environment variables (e.g. in
437 * extension modules), so we make sure that they match the locale
438 * configuration */
439 if (setenv("LC_CTYPE", utf8_locale, 1)) {
440 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
441 "environment variable to %s\n", utf8_locale);
442 }
443 }
444#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100445 res = setlocale(category, utf8_locale);
446#else /* !defined(__ANDROID__) */
447 res = setlocale(category, "");
448#endif
449 _Py_ResetForceASCII();
450 return res;
xdegaye1588be62017-11-12 12:45:59 +0100451}
452
Nick Coghlan6ea41862017-06-11 13:16:15 +1000453
Eric Snow1abcf672017-05-23 21:46:51 -0700454/* Global initializations. Can be undone by Py_Finalize(). Don't
455 call this twice without an intervening Py_Finalize() call.
456
Victor Stinner1dc6e392018-07-25 02:49:17 +0200457 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700458 must have a corresponding call to Py_Finalize.
459
460 Locking: you must hold the interpreter lock while calling these APIs.
461 (If the lock has not yet been initialized, that's equivalent to
462 having the lock, but you cannot use multiple threads.)
463
464*/
465
Victor Stinner1dc6e392018-07-25 02:49:17 +0200466static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100467_Py_Initialize_ReconfigureCore(PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200468 const _PyCoreConfig *core_config)
469{
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100470 PyThreadState *tstate = _PyThreadState_GET();
471 if (!tstate) {
472 return _Py_INIT_ERR("failed to read thread state");
473 }
474
475 PyInterpreterState *interp = tstate->interp;
476 if (interp == NULL) {
477 return _Py_INIT_ERR("can't make main interpreter");
478 }
479 *interp_p = interp;
480
481 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
482 Py_Initialize() ignores the new configuration. */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200483 if (core_config->allocator != NULL) {
484 const char *allocator = _PyMem_GetAllocatorsName();
485 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
486 return _Py_INIT_USER_ERR("cannot modify memory allocator "
487 "after first Py_Initialize()");
488 }
489 }
490
491 _PyCoreConfig_SetGlobalConfig(core_config);
492
493 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
494 return _Py_INIT_ERR("failed to copy core config");
495 }
496 core_config = &interp->core_config;
497
498 if (core_config->_install_importlib) {
499 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
500 if (_Py_INIT_FAILED(err)) {
501 return err;
502 }
503 }
504 return _Py_INIT_OK();
505}
506
507
Victor Stinner1dc6e392018-07-25 02:49:17 +0200508static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100509pycore_init_runtime(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000510{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200511 if (_PyRuntime.initialized) {
512 return _Py_INIT_ERR("main interpreter already initialized");
513 }
Victor Stinnerda273412017-12-15 01:46:02 +0100514
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200515 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000516
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100517 _PyInitError err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800518 if (_Py_INIT_FAILED(err)) {
519 return err;
520 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600521
Victor Stinner31e99082017-12-20 23:41:38 +0100522 if (core_config->allocator != NULL) {
523 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
524 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
525 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800526 }
527
Eric Snow1abcf672017-05-23 21:46:51 -0700528 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
529 * threads behave a little more gracefully at interpreter shutdown.
530 * We clobber it here so the new interpreter can start with a clean
531 * slate.
532 *
533 * However, this may still lead to misbehaviour if there are daemon
534 * threads still hanging around from a previous Py_Initialize/Finalize
535 * pair :(
536 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600537 _PyRuntime.finalizing = NULL;
538
Victor Stinnerda273412017-12-15 01:46:02 +0100539 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800540 if (_Py_INIT_FAILED(err)) {
541 return err;
542 }
543
Victor Stinnera7368ac2017-11-15 18:11:45 -0800544 err = _PyInterpreterState_Enable(&_PyRuntime);
545 if (_Py_INIT_FAILED(err)) {
546 return err;
547 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100548 return _Py_INIT_OK();
549}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800550
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100551
552static _PyInitError
553pycore_create_interpreter(const _PyCoreConfig *core_config,
554 PyInterpreterState **interp_p)
555{
556 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100557 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800558 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100559 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200560 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100561
562 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
563 return _Py_INIT_ERR("failed to copy core config");
564 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200565 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000566
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200567 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000568 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800569 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000570 (void) PyThreadState_Swap(tstate);
571
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000572 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000573 destroying the GIL might fail when it is being referenced from
574 another running thread (see issue #9901).
575 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000576 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000577 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100578
Nick Coghland6009512014-11-20 21:39:37 +1000579 /* Auto-thread-state API */
580 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000581
Victor Stinner2914bb32018-01-29 11:57:45 +0100582 /* Create the GIL */
583 PyEval_InitThreads();
584
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100585 return _Py_INIT_OK();
586}
Nick Coghland6009512014-11-20 21:39:37 +1000587
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100588
589static _PyInitError
590pycore_init_types(void)
591{
Victor Stinnerab672812019-01-23 15:04:40 +0100592 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100593 if (_Py_INIT_FAILED(err)) {
594 return err;
595 }
596
597 err = _PyUnicode_Init();
598 if (_Py_INIT_FAILED(err)) {
599 return err;
600 }
601
602 if (_PyStructSequence_Init() < 0) {
603 return _Py_INIT_ERR("can't initialize structseq");
604 }
605
606 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800607 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100608 }
Nick Coghland6009512014-11-20 21:39:37 +1000609
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100610 err = _PyExc_Init();
611 if (_Py_INIT_FAILED(err)) {
612 return err;
613 }
614
615 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800616 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100617 }
Nick Coghland6009512014-11-20 21:39:37 +1000618
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100619 if (!_PyContext_Init()) {
620 return _Py_INIT_ERR("can't init context");
621 }
622 return _Py_INIT_OK();
623}
624
625
626static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100627pycore_init_builtins(PyInterpreterState *interp)
628{
629 PyObject *bimod = _PyBuiltin_Init();
630 if (bimod == NULL) {
631 return _Py_INIT_ERR("can't initialize builtins modules");
632 }
633 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
634
635 interp->builtins = PyModule_GetDict(bimod);
636 if (interp->builtins == NULL) {
637 return _Py_INIT_ERR("can't initialize builtins dict");
638 }
639 Py_INCREF(interp->builtins);
640
641 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
642 if (_Py_INIT_FAILED(err)) {
643 return err;
644 }
645 return _Py_INIT_OK();
646}
647
648
649static _PyInitError
650pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
651{
652 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800653 if (_Py_INIT_FAILED(err)) {
654 return err;
655 }
Nick Coghland6009512014-11-20 21:39:37 +1000656
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800657 err = _PyImportHooks_Init();
658 if (_Py_INIT_FAILED(err)) {
659 return err;
660 }
Nick Coghland6009512014-11-20 21:39:37 +1000661
662 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100663 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100664 return _Py_INIT_ERR("can't initialize warnings");
665 }
Nick Coghland6009512014-11-20 21:39:37 +1000666
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100667 if (interp->core_config._install_importlib) {
668 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200669 if (_Py_INIT_FAILED(err)) {
670 return err;
671 }
672 }
673
Eric Snow1abcf672017-05-23 21:46:51 -0700674 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100675 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800676 err = initimport(interp, sysmod);
677 if (_Py_INIT_FAILED(err)) {
678 return err;
679 }
Eric Snow1abcf672017-05-23 21:46:51 -0700680 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100681 return _Py_INIT_OK();
682}
683
684
685static _PyInitError
686_Py_InitializeCore_impl(PyInterpreterState **interp_p,
687 const _PyCoreConfig *core_config)
688{
689 PyInterpreterState *interp;
690
691 _PyInitError err = pycore_init_runtime(core_config);
692 if (_Py_INIT_FAILED(err)) {
693 return err;
694 }
695
696 err = pycore_create_interpreter(core_config, &interp);
697 if (_Py_INIT_FAILED(err)) {
698 return err;
699 }
700 core_config = &interp->core_config;
701 *interp_p = interp;
702
703 err = pycore_init_types();
704 if (_Py_INIT_FAILED(err)) {
705 return err;
706 }
707
708 PyObject *sysmod;
Victor Stinnerab672812019-01-23 15:04:40 +0100709 err = _PySys_Create(interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100710 if (_Py_INIT_FAILED(err)) {
711 return err;
712 }
713
714 err = pycore_init_builtins(interp);
715 if (_Py_INIT_FAILED(err)) {
716 return err;
717 }
718
719 err = pycore_init_import_warnings(interp, sysmod);
720 if (_Py_INIT_FAILED(err)) {
721 return err;
722 }
Eric Snow1abcf672017-05-23 21:46:51 -0700723
724 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600725 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800726 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700727}
728
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100729/* Begin interpreter initialization
730 *
731 * On return, the first thread and interpreter state have been created,
732 * but the compiler, signal handling, multithreading and
733 * multiple interpreter support, and codec infrastructure are not yet
734 * available.
735 *
736 * The import system will support builtin and frozen modules only.
737 * The only supported io is writing to sys.stderr
738 *
739 * If any operation invoked by this function fails, a fatal error is
740 * issued and the function does not return.
741 *
742 * Any code invoked from this function should *not* assume it has access
743 * to the Python C API (unless the API is explicitly listed as being
744 * safe to call without calling Py_Initialize first)
745 */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200746_PyInitError
747_Py_InitializeCore(PyInterpreterState **interp_p,
748 const _PyCoreConfig *src_config)
749{
750 assert(src_config != NULL);
751
Victor Stinner1dc6e392018-07-25 02:49:17 +0200752 PyMemAllocatorEx old_alloc;
753 _PyInitError err;
754
755 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
756 (and the input configuration is read only). */
757 _PyCoreConfig config = _PyCoreConfig_INIT;
758
Victor Stinner177d9212018-08-29 11:25:15 +0200759 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200760 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200761
Victor Stinner1dc6e392018-07-25 02:49:17 +0200762 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
763 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
764 err = _PyCoreConfig_Read(&config);
765 }
766 else {
767 err = _Py_INIT_ERR("failed to copy core config");
768 }
769 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
770
771 if (_Py_INIT_FAILED(err)) {
772 goto done;
773 }
774
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100775 if (!_PyRuntime.core_initialized) {
776 err = _Py_InitializeCore_impl(interp_p, &config);
777 }
778 else {
779 err = _Py_Initialize_ReconfigureCore(interp_p, &config);
780 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200781
782done:
783 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
784 _PyCoreConfig_Clear(&config);
785 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
786
787 return err;
788}
789
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200790/* Py_Initialize() has already been called: update the main interpreter
791 configuration. Example of bpo-34008: Py_Main() called after
792 Py_Initialize(). */
793static _PyInitError
794_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
795 const _PyMainInterpreterConfig *config)
796{
797 if (config->argv != NULL) {
798 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
799 if (res < 0) {
800 return _Py_INIT_ERR("fail to set sys.argv");
801 }
802 }
803 return _Py_INIT_OK();
804}
805
Eric Snowc7ec9982017-05-23 23:00:52 -0700806/* Update interpreter state based on supplied configuration settings
807 *
808 * After calling this function, most of the restrictions on the interpreter
809 * are lifted. The only remaining incomplete settings are those related
810 * to the main module (sys.argv[0], __main__ metadata)
811 *
812 * Calling this when the interpreter is not initializing, is already
813 * initialized or without a valid current thread state is a fatal error.
814 * Other errors should be reported as normal Python exceptions with a
815 * non-zero return code.
816 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800817_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200818_Py_InitializeMainInterpreter(PyInterpreterState *interp,
819 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700820{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600821 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800822 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700823 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700824
Victor Stinner1dc6e392018-07-25 02:49:17 +0200825 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100826 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
827 return _Py_INIT_ERR("failed to copy main interpreter config");
828 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200829 config = &interp->config;
830 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700831
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200832 if (_PyRuntime.initialized) {
833 return _Py_ReconfigureMainInterpreter(interp, config);
834 }
835
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200836 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700837 /* Special mode for freeze_importlib: run with no import system
838 *
839 * This means anything which needs support from extension modules
840 * or pure Python code in the standard library won't work.
841 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600842 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800843 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700844 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100845
Victor Stinner33c377e2017-12-05 15:12:41 +0100846 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800847 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100848 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200849
Victor Stinnerab672812019-01-23 15:04:40 +0100850 if (_PySys_InitMain(interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800851 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100852 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800853
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200854 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800855 if (_Py_INIT_FAILED(err)) {
856 return err;
857 }
Nick Coghland6009512014-11-20 21:39:37 +1000858
859 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200860 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800861 if (_Py_INIT_FAILED(err)) {
862 return err;
863 }
Nick Coghland6009512014-11-20 21:39:37 +1000864
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800865 err = initfsencoding(interp);
866 if (_Py_INIT_FAILED(err)) {
867 return err;
868 }
Nick Coghland6009512014-11-20 21:39:37 +1000869
Victor Stinner1f151112017-11-23 10:43:14 +0100870 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800871 err = initsigs(); /* Signal handling stuff, including initintr() */
872 if (_Py_INIT_FAILED(err)) {
873 return err;
874 }
875 }
Nick Coghland6009512014-11-20 21:39:37 +1000876
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200877 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800878 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200879 }
Nick Coghland6009512014-11-20 21:39:37 +1000880
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800881 err = add_main_module(interp);
882 if (_Py_INIT_FAILED(err)) {
883 return err;
884 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800885
Victor Stinner91106cd2017-12-13 12:29:09 +0100886 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800887 if (_Py_INIT_FAILED(err)) {
888 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800889 }
Nick Coghland6009512014-11-20 21:39:37 +1000890
891 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100892 PyObject *warnoptions = PySys_GetObject("warnoptions");
893 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100894 {
Nick Coghland6009512014-11-20 21:39:37 +1000895 PyObject *warnings_module = PyImport_ImportModule("warnings");
896 if (warnings_module == NULL) {
897 fprintf(stderr, "'import warnings' failed; traceback:\n");
898 PyErr_Print();
899 }
900 Py_XDECREF(warnings_module);
901 }
902
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600903 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700904
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200905 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800906 err = initsite(); /* Module site */
907 if (_Py_INIT_FAILED(err)) {
908 return err;
909 }
910 }
Victor Stinnercf215042018-08-29 22:56:06 +0200911
912#ifndef MS_WINDOWS
913 _emit_stderr_warning_for_legacy_locale(core_config);
914#endif
915
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800916 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000917}
918
Eric Snowc7ec9982017-05-23 23:00:52 -0700919#undef _INIT_DEBUG_PRINT
920
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800921_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200922_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700923{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700924 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800925 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200926 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200928 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800929 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200930 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100931
Victor Stinner9cfc0022017-12-20 19:36:46 +0100932 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200933 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100934 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200935 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800936 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100937 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800938 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200939 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800940 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200941 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700942}
943
944
945void
Nick Coghland6009512014-11-20 21:39:37 +1000946Py_InitializeEx(int install_sigs)
947{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200948 if (_PyRuntime.initialized) {
949 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
950 return;
951 }
952
953 _PyInitError err;
954 _PyCoreConfig config = _PyCoreConfig_INIT;
955 config.install_signal_handlers = install_sigs;
956
957 err = _Py_InitializeFromConfig(&config);
958 _PyCoreConfig_Clear(&config);
959
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800960 if (_Py_INIT_FAILED(err)) {
961 _Py_FatalInitError(err);
962 }
Nick Coghland6009512014-11-20 21:39:37 +1000963}
964
965void
966Py_Initialize(void)
967{
968 Py_InitializeEx(1);
969}
970
971
972#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000973extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000974#endif
975
976/* Flush stdout and stderr */
977
978static int
979file_is_closed(PyObject *fobj)
980{
981 int r;
982 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
983 if (tmp == NULL) {
984 PyErr_Clear();
985 return 0;
986 }
987 r = PyObject_IsTrue(tmp);
988 Py_DECREF(tmp);
989 if (r < 0)
990 PyErr_Clear();
991 return r > 0;
992}
993
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000994static int
Nick Coghland6009512014-11-20 21:39:37 +1000995flush_std_files(void)
996{
997 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
998 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
999 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001000 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001001
1002 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001003 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001004 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001005 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001006 status = -1;
1007 }
Nick Coghland6009512014-11-20 21:39:37 +10001008 else
1009 Py_DECREF(tmp);
1010 }
1011
1012 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001013 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001014 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001015 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001016 status = -1;
1017 }
Nick Coghland6009512014-11-20 21:39:37 +10001018 else
1019 Py_DECREF(tmp);
1020 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001021
1022 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001023}
1024
1025/* Undo the effect of Py_Initialize().
1026
1027 Beware: if multiple interpreter and/or thread states exist, these
1028 are not wiped out; only the current thread and interpreter state
1029 are deleted. But since everything else is deleted, those other
1030 interpreter and thread states should no longer be used.
1031
1032 (XXX We should do better, e.g. wipe out all interpreters and
1033 threads.)
1034
1035 Locking: as above.
1036
1037*/
1038
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001039int
1040Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001041{
1042 PyInterpreterState *interp;
1043 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001044 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001045
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001046 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001047 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001048
1049 wait_for_thread_shutdown();
1050
Marcel Plch776407f2017-12-20 11:17:58 +01001051 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001052 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001053 interp = tstate->interp;
1054
Nick Coghland6009512014-11-20 21:39:37 +10001055 /* The interpreter is still entirely intact at this point, and the
1056 * exit funcs may be relying on that. In particular, if some thread
1057 * or exit func is still waiting to do an import, the import machinery
1058 * expects Py_IsInitialized() to return true. So don't say the
1059 * interpreter is uninitialized until after the exit funcs have run.
1060 * Note that Threading.py uses an exit func to do a join on all the
1061 * threads created thru it, so this also protects pending imports in
1062 * the threads created via Threading.
1063 */
Nick Coghland6009512014-11-20 21:39:37 +10001064
Marcel Plch776407f2017-12-20 11:17:58 +01001065 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001066
Victor Stinnerda273412017-12-15 01:46:02 +01001067 /* Copy the core config, PyInterpreterState_Delete() free
1068 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001069#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001070 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001071#endif
1072#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001073 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001074#endif
1075#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001076 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001077#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001078
Nick Coghland6009512014-11-20 21:39:37 +10001079 /* Remaining threads (e.g. daemon threads) will automatically exit
1080 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001081 _PyRuntime.finalizing = tstate;
1082 _PyRuntime.initialized = 0;
1083 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001084
Victor Stinnere0deff32015-03-24 13:46:18 +01001085 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001086 if (flush_std_files() < 0) {
1087 status = -1;
1088 }
Nick Coghland6009512014-11-20 21:39:37 +10001089
1090 /* Disable signal handling */
1091 PyOS_FiniInterrupts();
1092
1093 /* Collect garbage. This may call finalizers; it's nice to call these
1094 * before all modules are destroyed.
1095 * XXX If a __del__ or weakref callback is triggered here, and tries to
1096 * XXX import a module, bad things can happen, because Python no
1097 * XXX longer believes it's initialized.
1098 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1099 * XXX is easy to provoke that way. I've also seen, e.g.,
1100 * XXX Exception exceptions.ImportError: 'No module named sha'
1101 * XXX in <function callback at 0x008F5718> ignored
1102 * XXX but I'm unclear on exactly how that one happens. In any case,
1103 * XXX I haven't seen a real-life report of either of these.
1104 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001105 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001106#ifdef COUNT_ALLOCS
1107 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1108 each collection might release some types from the type
1109 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001110 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001111 /* nothing */;
1112#endif
Eric Snowdae02762017-09-14 00:35:58 -07001113
Nick Coghland6009512014-11-20 21:39:37 +10001114 /* Destroy all modules */
1115 PyImport_Cleanup();
1116
Victor Stinnere0deff32015-03-24 13:46:18 +01001117 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001118 if (flush_std_files() < 0) {
1119 status = -1;
1120 }
Nick Coghland6009512014-11-20 21:39:37 +10001121
1122 /* Collect final garbage. This disposes of cycles created by
1123 * class definitions, for example.
1124 * XXX This is disabled because it caused too many problems. If
1125 * XXX a __del__ or weakref callback triggers here, Python code has
1126 * XXX a hard time running, because even the sys module has been
1127 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1128 * XXX One symptom is a sequence of information-free messages
1129 * XXX coming from threads (if a __del__ or callback is invoked,
1130 * XXX other threads can execute too, and any exception they encounter
1131 * XXX triggers a comedy of errors as subsystem after subsystem
1132 * XXX fails to find what it *expects* to find in sys to help report
1133 * XXX the exception and consequent unexpected failures). I've also
1134 * XXX seen segfaults then, after adding print statements to the
1135 * XXX Python code getting called.
1136 */
1137#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001138 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001139#endif
1140
1141 /* Disable tracemalloc after all Python objects have been destroyed,
1142 so it is possible to use tracemalloc in objects destructor. */
1143 _PyTraceMalloc_Fini();
1144
1145 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1146 _PyImport_Fini();
1147
1148 /* Cleanup typeobject.c's internal caches. */
1149 _PyType_Fini();
1150
1151 /* unload faulthandler module */
1152 _PyFaulthandler_Fini();
1153
1154 /* Debugging stuff */
1155#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001156 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001157#endif
1158 /* dump hash stats */
1159 _PyHash_Fini();
1160
Eric Snowdae02762017-09-14 00:35:58 -07001161#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001162 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001163 _PyDebug_PrintTotalRefs();
1164 }
Eric Snowdae02762017-09-14 00:35:58 -07001165#endif
Nick Coghland6009512014-11-20 21:39:37 +10001166
1167#ifdef Py_TRACE_REFS
1168 /* Display all objects still alive -- this can invoke arbitrary
1169 * __repr__ overrides, so requires a mostly-intact interpreter.
1170 * Alas, a lot of stuff may still be alive now that will be cleaned
1171 * up later.
1172 */
Victor Stinnerda273412017-12-15 01:46:02 +01001173 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001174 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001175 }
Nick Coghland6009512014-11-20 21:39:37 +10001176#endif /* Py_TRACE_REFS */
1177
1178 /* Clear interpreter state and all thread states. */
1179 PyInterpreterState_Clear(interp);
1180
1181 /* Now we decref the exception classes. After this point nothing
1182 can raise an exception. That's okay, because each Fini() method
1183 below has been checked to make sure no exceptions are ever
1184 raised.
1185 */
1186
1187 _PyExc_Fini();
1188
1189 /* Sundry finalizers */
1190 PyMethod_Fini();
1191 PyFrame_Fini();
1192 PyCFunction_Fini();
1193 PyTuple_Fini();
1194 PyList_Fini();
1195 PySet_Fini();
1196 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001197 PyLong_Fini();
1198 PyFloat_Fini();
1199 PyDict_Fini();
1200 PySlice_Fini();
1201 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001202 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001203 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001204 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001205 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001206
1207 /* Cleanup Unicode implementation */
1208 _PyUnicode_Fini();
1209
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001210 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001211
1212 /* XXX Still allocated:
1213 - various static ad-hoc pointers to interned strings
1214 - int and float free list blocks
1215 - whatever various modules and libraries allocate
1216 */
1217
1218 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1219
1220 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001221 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001222
1223 /* Delete current thread. After this, many C API calls become crashy. */
1224 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001225
Nick Coghland6009512014-11-20 21:39:37 +10001226 PyInterpreterState_Delete(interp);
1227
1228#ifdef Py_TRACE_REFS
1229 /* Display addresses (& refcnts) of all objects still alive.
1230 * An address can be used to find the repr of the object, printed
1231 * above by _Py_PrintReferences.
1232 */
Victor Stinnerda273412017-12-15 01:46:02 +01001233 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001234 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001235 }
Nick Coghland6009512014-11-20 21:39:37 +10001236#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001237#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001238 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001239 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001240 }
Nick Coghland6009512014-11-20 21:39:37 +10001241#endif
1242
1243 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001244
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001245 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001246 return status;
1247}
1248
1249void
1250Py_Finalize(void)
1251{
1252 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001253}
1254
1255/* Create and initialize a new interpreter and thread, and return the
1256 new thread. This requires that Py_Initialize() has been called
1257 first.
1258
1259 Unsuccessful initialization yields a NULL pointer. Note that *no*
1260 exception information is available even in this case -- the
1261 exception information is held in the thread, and there is no
1262 thread.
1263
1264 Locking: as above.
1265
1266*/
1267
Victor Stinnera7368ac2017-11-15 18:11:45 -08001268static _PyInitError
1269new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001270{
1271 PyInterpreterState *interp;
1272 PyThreadState *tstate, *save_tstate;
1273 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001274 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001275
Victor Stinnera7368ac2017-11-15 18:11:45 -08001276 if (!_PyRuntime.initialized) {
1277 return _Py_INIT_ERR("Py_Initialize must be called first");
1278 }
Nick Coghland6009512014-11-20 21:39:37 +10001279
Victor Stinner8a1be612016-03-14 22:07:55 +01001280 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1281 interpreters: disable PyGILState_Check(). */
1282 _PyGILState_check_enabled = 0;
1283
Nick Coghland6009512014-11-20 21:39:37 +10001284 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001285 if (interp == NULL) {
1286 *tstate_p = NULL;
1287 return _Py_INIT_OK();
1288 }
Nick Coghland6009512014-11-20 21:39:37 +10001289
1290 tstate = PyThreadState_New(interp);
1291 if (tstate == NULL) {
1292 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001293 *tstate_p = NULL;
1294 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001295 }
1296
1297 save_tstate = PyThreadState_Swap(tstate);
1298
Eric Snow1abcf672017-05-23 21:46:51 -07001299 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001300 _PyCoreConfig *core_config;
1301 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001302 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001303 core_config = &save_tstate->interp->core_config;
1304 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001305 } else {
1306 /* No current thread state, copy from the main interpreter */
1307 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001308 core_config = &main_interp->core_config;
1309 config = &main_interp->config;
1310 }
1311
1312 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1313 return _Py_INIT_ERR("failed to copy core config");
1314 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001315 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001316 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1317 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001318 }
1319
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001320 err = _PyExc_Init();
1321 if (_Py_INIT_FAILED(err)) {
1322 return err;
1323 }
1324
Nick Coghland6009512014-11-20 21:39:37 +10001325 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001326 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001327 if (modules == NULL) {
1328 return _Py_INIT_ERR("can't make modules dictionary");
1329 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001330 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001331
Eric Snowd393c1b2017-09-14 12:18:12 -06001332 sysmod = _PyImport_FindBuiltin("sys", modules);
1333 if (sysmod != NULL) {
1334 interp->sysdict = PyModule_GetDict(sysmod);
1335 if (interp->sysdict == NULL)
1336 goto handle_error;
1337 Py_INCREF(interp->sysdict);
1338 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerab672812019-01-23 15:04:40 +01001339 if (_PySys_InitMain(interp) < 0) {
1340 return _Py_INIT_ERR("can't finish initializing sys");
1341 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001342 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001343 else if (PyErr_Occurred()) {
1344 goto handle_error;
1345 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001346
1347 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001348 if (bimod != NULL) {
1349 interp->builtins = PyModule_GetDict(bimod);
1350 if (interp->builtins == NULL)
1351 goto handle_error;
1352 Py_INCREF(interp->builtins);
1353 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001354 else if (PyErr_Occurred()) {
1355 goto handle_error;
1356 }
Nick Coghland6009512014-11-20 21:39:37 +10001357
Nick Coghland6009512014-11-20 21:39:37 +10001358 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001359 err = _PyBuiltins_AddExceptions(bimod);
1360 if (_Py_INIT_FAILED(err)) {
1361 return err;
1362 }
Nick Coghland6009512014-11-20 21:39:37 +10001363
Victor Stinnerab672812019-01-23 15:04:40 +01001364 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1365 if (_Py_INIT_FAILED(err)) {
1366 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001367 }
Nick Coghland6009512014-11-20 21:39:37 +10001368
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001369 err = _PyImportHooks_Init();
1370 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001371 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001372 }
Nick Coghland6009512014-11-20 21:39:37 +10001373
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001374 err = initimport(interp, sysmod);
1375 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001376 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001377 }
Nick Coghland6009512014-11-20 21:39:37 +10001378
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001379 err = initexternalimport(interp);
1380 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001381 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001382 }
Nick Coghland6009512014-11-20 21:39:37 +10001383
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001384 err = initfsencoding(interp);
1385 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001386 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001387 }
1388
Victor Stinner91106cd2017-12-13 12:29:09 +01001389 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001390 if (_Py_INIT_FAILED(err)) {
1391 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001392 }
1393
1394 err = add_main_module(interp);
1395 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001396 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001397 }
1398
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001399 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001400 err = initsite();
1401 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001402 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001403 }
1404 }
Nick Coghland6009512014-11-20 21:39:37 +10001405 }
1406
Victor Stinnera7368ac2017-11-15 18:11:45 -08001407 if (PyErr_Occurred()) {
1408 goto handle_error;
1409 }
Nick Coghland6009512014-11-20 21:39:37 +10001410
Victor Stinnera7368ac2017-11-15 18:11:45 -08001411 *tstate_p = tstate;
1412 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001413
Nick Coghland6009512014-11-20 21:39:37 +10001414handle_error:
1415 /* Oops, it didn't work. Undo it all. */
1416
1417 PyErr_PrintEx(0);
1418 PyThreadState_Clear(tstate);
1419 PyThreadState_Swap(save_tstate);
1420 PyThreadState_Delete(tstate);
1421 PyInterpreterState_Delete(interp);
1422
Victor Stinnera7368ac2017-11-15 18:11:45 -08001423 *tstate_p = NULL;
1424 return _Py_INIT_OK();
1425}
1426
1427PyThreadState *
1428Py_NewInterpreter(void)
1429{
1430 PyThreadState *tstate;
1431 _PyInitError err = new_interpreter(&tstate);
1432 if (_Py_INIT_FAILED(err)) {
1433 _Py_FatalInitError(err);
1434 }
1435 return tstate;
1436
Nick Coghland6009512014-11-20 21:39:37 +10001437}
1438
1439/* Delete an interpreter and its last thread. This requires that the
1440 given thread state is current, that the thread has no remaining
1441 frames, and that it is its interpreter's only remaining thread.
1442 It is a fatal error to violate these constraints.
1443
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001444 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001445 everything, regardless.)
1446
1447 Locking: as above.
1448
1449*/
1450
1451void
1452Py_EndInterpreter(PyThreadState *tstate)
1453{
1454 PyInterpreterState *interp = tstate->interp;
1455
Victor Stinner50b48572018-11-01 01:51:40 +01001456 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001457 Py_FatalError("Py_EndInterpreter: thread is not current");
1458 if (tstate->frame != NULL)
1459 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1460
1461 wait_for_thread_shutdown();
1462
Marcel Plch776407f2017-12-20 11:17:58 +01001463 call_py_exitfuncs(interp);
1464
Nick Coghland6009512014-11-20 21:39:37 +10001465 if (tstate != interp->tstate_head || tstate->next != NULL)
1466 Py_FatalError("Py_EndInterpreter: not the last thread");
1467
1468 PyImport_Cleanup();
1469 PyInterpreterState_Clear(interp);
1470 PyThreadState_Swap(NULL);
1471 PyInterpreterState_Delete(interp);
1472}
1473
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001474/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001475
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001476static _PyInitError
1477add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001478{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001479 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001480 m = PyImport_AddModule("__main__");
1481 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001482 return _Py_INIT_ERR("can't create __main__ module");
1483
Nick Coghland6009512014-11-20 21:39:37 +10001484 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001485 ann_dict = PyDict_New();
1486 if ((ann_dict == NULL) ||
1487 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001488 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001489 }
1490 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001491
Nick Coghland6009512014-11-20 21:39:37 +10001492 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1493 PyObject *bimod = PyImport_ImportModule("builtins");
1494 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001495 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001496 }
1497 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001499 }
1500 Py_DECREF(bimod);
1501 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001502
Nick Coghland6009512014-11-20 21:39:37 +10001503 /* Main is a little special - imp.is_builtin("__main__") will return
1504 * False, but BuiltinImporter is still the most appropriate initial
1505 * setting for its __loader__ attribute. A more suitable value will
1506 * be set if __main__ gets further initialized later in the startup
1507 * process.
1508 */
1509 loader = PyDict_GetItemString(d, "__loader__");
1510 if (loader == NULL || loader == Py_None) {
1511 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1512 "BuiltinImporter");
1513 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001514 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001515 }
1516 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001518 }
1519 Py_DECREF(loader);
1520 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001521 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001522}
1523
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001525initfsencoding(PyInterpreterState *interp)
1526{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001527 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001528
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001529 char *encoding = get_codec_name(config->filesystem_encoding);
1530 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001531 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001532 memory, import a module of the standard library failed, etc. */
1533 return _Py_INIT_ERR("failed to get the Python codec "
1534 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001535 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001536
1537 /* Update the filesystem encoding to the normalized Python codec name.
1538 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1539 (Python codec name). */
1540 PyMem_RawFree(config->filesystem_encoding);
1541 config->filesystem_encoding = encoding;
1542
1543 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1544 global configuration variables. */
1545 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1546 config->filesystem_errors) < 0) {
1547 return _Py_INIT_NO_MEMORY();
1548 }
1549
1550 /* PyUnicode can now use the Python codec rather than C implementation
1551 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001552 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001553 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001554}
1555
1556/* Import the site module (not into __main__ though) */
1557
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001558static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001559initsite(void)
1560{
1561 PyObject *m;
1562 m = PyImport_ImportModule("site");
1563 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001564 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001565 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001566 Py_DECREF(m);
1567 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001568}
1569
Victor Stinner874dbe82015-09-04 17:29:57 +02001570/* Check if a file descriptor is valid or not.
1571 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1572static int
1573is_valid_fd(int fd)
1574{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001575#ifdef __APPLE__
1576 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1577 and the other side of the pipe is closed, dup(1) succeed, whereas
1578 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1579 such error. */
1580 struct stat st;
1581 return (fstat(fd, &st) == 0);
1582#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001583 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001584 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001585 return 0;
1586 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001587 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1588 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1589 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001590 fd2 = dup(fd);
1591 if (fd2 >= 0)
1592 close(fd2);
1593 _Py_END_SUPPRESS_IPH
1594 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001595#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001596}
1597
1598/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001599static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001600create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001601 int fd, int write_mode, const char* name,
1602 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001603{
1604 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1605 const char* mode;
1606 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001607 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001608 int buffering, isatty;
1609 _Py_IDENTIFIER(open);
1610 _Py_IDENTIFIER(isatty);
1611 _Py_IDENTIFIER(TextIOWrapper);
1612 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001613 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001614
Victor Stinner874dbe82015-09-04 17:29:57 +02001615 if (!is_valid_fd(fd))
1616 Py_RETURN_NONE;
1617
Nick Coghland6009512014-11-20 21:39:37 +10001618 /* stdin is always opened in buffered mode, first because it shouldn't
1619 make a difference in common use cases, second because TextIOWrapper
1620 depends on the presence of a read1() method which only exists on
1621 buffered streams.
1622 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001623 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001624 buffering = 0;
1625 else
1626 buffering = -1;
1627 if (write_mode)
1628 mode = "wb";
1629 else
1630 mode = "rb";
1631 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1632 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001633 Py_None, Py_None, /* encoding, errors */
1634 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001635 if (buf == NULL)
1636 goto error;
1637
1638 if (buffering) {
1639 _Py_IDENTIFIER(raw);
1640 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1641 if (raw == NULL)
1642 goto error;
1643 }
1644 else {
1645 raw = buf;
1646 Py_INCREF(raw);
1647 }
1648
Steve Dower39294992016-08-30 21:22:36 -07001649#ifdef MS_WINDOWS
1650 /* Windows console IO is always UTF-8 encoded */
1651 if (PyWindowsConsoleIO_Check(raw))
1652 encoding = "utf-8";
1653#endif
1654
Nick Coghland6009512014-11-20 21:39:37 +10001655 text = PyUnicode_FromString(name);
1656 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1657 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001658 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001659 if (res == NULL)
1660 goto error;
1661 isatty = PyObject_IsTrue(res);
1662 Py_DECREF(res);
1663 if (isatty == -1)
1664 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001665 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001666 write_through = Py_True;
1667 else
1668 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001669 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001670 line_buffering = Py_True;
1671 else
1672 line_buffering = Py_False;
1673
1674 Py_CLEAR(raw);
1675 Py_CLEAR(text);
1676
1677#ifdef MS_WINDOWS
1678 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1679 newlines to "\n".
1680 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1681 newline = NULL;
1682#else
1683 /* sys.stdin: split lines at "\n".
1684 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1685 newline = "\n";
1686#endif
1687
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001688 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001689 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001690 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001691 Py_CLEAR(buf);
1692 if (stream == NULL)
1693 goto error;
1694
1695 if (write_mode)
1696 mode = "w";
1697 else
1698 mode = "r";
1699 text = PyUnicode_FromString(mode);
1700 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1701 goto error;
1702 Py_CLEAR(text);
1703 return stream;
1704
1705error:
1706 Py_XDECREF(buf);
1707 Py_XDECREF(stream);
1708 Py_XDECREF(text);
1709 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001710
Victor Stinner874dbe82015-09-04 17:29:57 +02001711 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1712 /* Issue #24891: the file descriptor was closed after the first
1713 is_valid_fd() check was called. Ignore the OSError and set the
1714 stream to None. */
1715 PyErr_Clear();
1716 Py_RETURN_NONE;
1717 }
1718 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001719}
1720
1721/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001722static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001723init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001724{
1725 PyObject *iomod = NULL, *wrapper;
1726 PyObject *bimod = NULL;
1727 PyObject *m;
1728 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001729 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001730 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001731 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001732 _PyCoreConfig *config = &interp->core_config;
1733
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001734 /* Check that stdin is not a directory
1735 Using shell redirection, you can redirect stdin to a directory,
1736 crashing the Python interpreter. Catch this common mistake here
1737 and output a useful error message. Note that under MS Windows,
1738 the shell already prevents that. */
1739#ifndef MS_WINDOWS
1740 struct _Py_stat_struct sb;
1741 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1742 S_ISDIR(sb.st_mode)) {
1743 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1744 "cannot continue");
1745 }
1746#endif
1747
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001748 char *codec_name = get_codec_name(config->stdio_encoding);
1749 if (codec_name == NULL) {
1750 return _Py_INIT_ERR("failed to get the Python codec name "
1751 "of the stdio encoding");
1752 }
1753 PyMem_RawFree(config->stdio_encoding);
1754 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001755
1756 /* Hack to avoid a nasty recursion issue when Python is invoked
1757 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1758 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1759 goto error;
1760 }
1761 Py_DECREF(m);
1762
1763 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1764 goto error;
1765 }
1766 Py_DECREF(m);
1767
1768 if (!(bimod = PyImport_ImportModule("builtins"))) {
1769 goto error;
1770 }
1771
1772 if (!(iomod = PyImport_ImportModule("io"))) {
1773 goto error;
1774 }
1775 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1776 goto error;
1777 }
1778
1779 /* Set builtins.open */
1780 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1781 Py_DECREF(wrapper);
1782 goto error;
1783 }
1784 Py_DECREF(wrapper);
1785
Nick Coghland6009512014-11-20 21:39:37 +10001786 /* Set sys.stdin */
1787 fd = fileno(stdin);
1788 /* Under some conditions stdin, stdout and stderr may not be connected
1789 * and fileno() may point to an invalid file descriptor. For example
1790 * GUI apps don't have valid standard streams by default.
1791 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001792 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001793 config->stdio_encoding,
1794 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001795 if (std == NULL)
1796 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001797 PySys_SetObject("__stdin__", std);
1798 _PySys_SetObjectId(&PyId_stdin, std);
1799 Py_DECREF(std);
1800
1801 /* Set sys.stdout */
1802 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001803 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001804 config->stdio_encoding,
1805 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001806 if (std == NULL)
1807 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001808 PySys_SetObject("__stdout__", std);
1809 _PySys_SetObjectId(&PyId_stdout, std);
1810 Py_DECREF(std);
1811
1812#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1813 /* Set sys.stderr, replaces the preliminary stderr */
1814 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001815 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001816 config->stdio_encoding,
1817 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001818 if (std == NULL)
1819 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001820
1821 /* Same as hack above, pre-import stderr's codec to avoid recursion
1822 when import.c tries to write to stderr in verbose mode. */
1823 encoding_attr = PyObject_GetAttrString(std, "encoding");
1824 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001825 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001826 if (std_encoding != NULL) {
1827 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1828 Py_XDECREF(codec_info);
1829 }
1830 Py_DECREF(encoding_attr);
1831 }
1832 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1833
1834 if (PySys_SetObject("__stderr__", std) < 0) {
1835 Py_DECREF(std);
1836 goto error;
1837 }
1838 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1839 Py_DECREF(std);
1840 goto error;
1841 }
1842 Py_DECREF(std);
1843#endif
1844
Victor Stinnera7368ac2017-11-15 18:11:45 -08001845 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001846
Victor Stinnera7368ac2017-11-15 18:11:45 -08001847error:
1848 res = _Py_INIT_ERR("can't initialize sys standard streams");
1849
1850done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001851 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001852
Nick Coghland6009512014-11-20 21:39:37 +10001853 Py_XDECREF(bimod);
1854 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001855 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001856}
1857
1858
Victor Stinner10dc4842015-03-24 12:01:30 +01001859static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001860_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001861{
Victor Stinner10dc4842015-03-24 12:01:30 +01001862 fputc('\n', stderr);
1863 fflush(stderr);
1864
1865 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001866 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001867}
Victor Stinner791da1c2016-03-14 16:53:12 +01001868
1869/* Print the current exception (if an exception is set) with its traceback,
1870 or display the current Python stack.
1871
1872 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1873 called on catastrophic cases.
1874
1875 Return 1 if the traceback was displayed, 0 otherwise. */
1876
1877static int
1878_Py_FatalError_PrintExc(int fd)
1879{
1880 PyObject *ferr, *res;
1881 PyObject *exception, *v, *tb;
1882 int has_tb;
1883
Victor Stinner791da1c2016-03-14 16:53:12 +01001884 PyErr_Fetch(&exception, &v, &tb);
1885 if (exception == NULL) {
1886 /* No current exception */
1887 return 0;
1888 }
1889
1890 ferr = _PySys_GetObjectId(&PyId_stderr);
1891 if (ferr == NULL || ferr == Py_None) {
1892 /* sys.stderr is not set yet or set to None,
1893 no need to try to display the exception */
1894 return 0;
1895 }
1896
1897 PyErr_NormalizeException(&exception, &v, &tb);
1898 if (tb == NULL) {
1899 tb = Py_None;
1900 Py_INCREF(tb);
1901 }
1902 PyException_SetTraceback(v, tb);
1903 if (exception == NULL) {
1904 /* PyErr_NormalizeException() failed */
1905 return 0;
1906 }
1907
1908 has_tb = (tb != Py_None);
1909 PyErr_Display(exception, v, tb);
1910 Py_XDECREF(exception);
1911 Py_XDECREF(v);
1912 Py_XDECREF(tb);
1913
1914 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001915 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001916 if (res == NULL)
1917 PyErr_Clear();
1918 else
1919 Py_DECREF(res);
1920
1921 return has_tb;
1922}
1923
Nick Coghland6009512014-11-20 21:39:37 +10001924/* Print fatal error message and abort */
1925
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001926#ifdef MS_WINDOWS
1927static void
1928fatal_output_debug(const char *msg)
1929{
1930 /* buffer of 256 bytes allocated on the stack */
1931 WCHAR buffer[256 / sizeof(WCHAR)];
1932 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1933 size_t msglen;
1934
1935 OutputDebugStringW(L"Fatal Python error: ");
1936
1937 msglen = strlen(msg);
1938 while (msglen) {
1939 size_t i;
1940
1941 if (buflen > msglen) {
1942 buflen = msglen;
1943 }
1944
1945 /* Convert the message to wchar_t. This uses a simple one-to-one
1946 conversion, assuming that the this error message actually uses
1947 ASCII only. If this ceases to be true, we will have to convert. */
1948 for (i=0; i < buflen; ++i) {
1949 buffer[i] = msg[i];
1950 }
1951 buffer[i] = L'\0';
1952 OutputDebugStringW(buffer);
1953
1954 msg += buflen;
1955 msglen -= buflen;
1956 }
1957 OutputDebugStringW(L"\n");
1958}
1959#endif
1960
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001961static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001962fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001963{
1964 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001965 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001966
1967 if (reentrant) {
1968 /* Py_FatalError() caused a second fatal error.
1969 Example: flush_std_files() raises a recursion error. */
1970 goto exit;
1971 }
1972 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001973
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001974 fprintf(stderr, "Fatal Python error: ");
1975 if (prefix) {
1976 fputs(prefix, stderr);
1977 fputs(": ", stderr);
1978 }
1979 if (msg) {
1980 fputs(msg, stderr);
1981 }
1982 else {
1983 fprintf(stderr, "<message not set>");
1984 }
1985 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001986 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001987
Victor Stinner3a228ab2018-11-01 00:26:41 +01001988 /* Check if the current thread has a Python thread state
1989 and holds the GIL */
1990 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
1991 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01001992 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01001993 if (tss_tstate != tstate) {
1994 /* The Python thread does not hold the GIL */
1995 tss_tstate = NULL;
1996 }
1997 }
1998 else {
1999 /* Py_FatalError() has been called from a C thread
2000 which has no Python thread state. */
2001 }
2002 int has_tstate_and_gil = (tss_tstate != NULL);
2003
2004 if (has_tstate_and_gil) {
2005 /* If an exception is set, print the exception with its traceback */
2006 if (!_Py_FatalError_PrintExc(fd)) {
2007 /* No exception is set, or an exception is set without traceback */
2008 _Py_FatalError_DumpTracebacks(fd);
2009 }
2010 }
2011 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002012 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002013 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002014
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002015 /* The main purpose of faulthandler is to display the traceback.
2016 This function already did its best to display a traceback.
2017 Disable faulthandler to prevent writing a second traceback
2018 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002019 _PyFaulthandler_Fini();
2020
Victor Stinner791da1c2016-03-14 16:53:12 +01002021 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002022 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002023 /* Flush sys.stdout and sys.stderr */
2024 flush_std_files();
2025 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002026
Nick Coghland6009512014-11-20 21:39:37 +10002027#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002028 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002029#endif /* MS_WINDOWS */
2030
2031exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002032 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002033#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002034 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002035#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002036 abort();
2037 }
2038 else {
2039 exit(status);
2040 }
2041}
2042
Victor Stinner19760862017-12-20 01:41:59 +01002043void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002044Py_FatalError(const char *msg)
2045{
2046 fatal_error(NULL, msg, -1);
2047}
2048
Victor Stinner19760862017-12-20 01:41:59 +01002049void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002050_Py_FatalInitError(_PyInitError err)
2051{
2052 /* On "user" error: exit with status 1.
2053 For all other errors, call abort(). */
2054 int status = err.user_err ? 1 : -1;
2055 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002056}
2057
2058/* Clean up and exit */
2059
Victor Stinnerd7292b52016-06-17 12:29:00 +02002060# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002061
Nick Coghland6009512014-11-20 21:39:37 +10002062/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002063void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002064{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002065 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002066
Antoine Pitroufc5db952017-12-13 02:29:07 +01002067 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002068 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2069
2070 is->pyexitfunc = func;
2071 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002072}
2073
2074static void
Marcel Plch776407f2017-12-20 11:17:58 +01002075call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002076{
Marcel Plch776407f2017-12-20 11:17:58 +01002077 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002078 return;
2079
Marcel Plch776407f2017-12-20 11:17:58 +01002080 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002081 PyErr_Clear();
2082}
2083
2084/* Wait until threading._shutdown completes, provided
2085 the threading module was imported in the first place.
2086 The shutdown routine will wait until all non-daemon
2087 "threading" threads have completed. */
2088static void
2089wait_for_thread_shutdown(void)
2090{
Nick Coghland6009512014-11-20 21:39:37 +10002091 _Py_IDENTIFIER(_shutdown);
2092 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002093 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002094 if (threading == NULL) {
2095 /* threading not imported */
2096 PyErr_Clear();
2097 return;
2098 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002099 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002100 if (result == NULL) {
2101 PyErr_WriteUnraisable(threading);
2102 }
2103 else {
2104 Py_DECREF(result);
2105 }
2106 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002107}
2108
2109#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002110int Py_AtExit(void (*func)(void))
2111{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002112 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002113 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002114 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002115 return 0;
2116}
2117
2118static void
2119call_ll_exitfuncs(void)
2120{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002121 while (_PyRuntime.nexitfuncs > 0)
2122 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002123
2124 fflush(stdout);
2125 fflush(stderr);
2126}
2127
Victor Stinnercfc88312018-08-01 16:41:25 +02002128void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002129Py_Exit(int sts)
2130{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002131 if (Py_FinalizeEx() < 0) {
2132 sts = 120;
2133 }
Nick Coghland6009512014-11-20 21:39:37 +10002134
2135 exit(sts);
2136}
2137
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002138static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002139initsigs(void)
2140{
2141#ifdef SIGPIPE
2142 PyOS_setsig(SIGPIPE, SIG_IGN);
2143#endif
2144#ifdef SIGXFZ
2145 PyOS_setsig(SIGXFZ, SIG_IGN);
2146#endif
2147#ifdef SIGXFSZ
2148 PyOS_setsig(SIGXFSZ, SIG_IGN);
2149#endif
2150 PyOS_InitInterrupts(); /* May imply initsignal() */
2151 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002152 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002153 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002154 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002155}
2156
2157
2158/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2159 *
2160 * All of the code in this function must only use async-signal-safe functions,
2161 * listed at `man 7 signal` or
2162 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2163 */
2164void
2165_Py_RestoreSignals(void)
2166{
2167#ifdef SIGPIPE
2168 PyOS_setsig(SIGPIPE, SIG_DFL);
2169#endif
2170#ifdef SIGXFZ
2171 PyOS_setsig(SIGXFZ, SIG_DFL);
2172#endif
2173#ifdef SIGXFSZ
2174 PyOS_setsig(SIGXFSZ, SIG_DFL);
2175#endif
2176}
2177
2178
2179/*
2180 * The file descriptor fd is considered ``interactive'' if either
2181 * a) isatty(fd) is TRUE, or
2182 * b) the -i flag was given, and the filename associated with
2183 * the descriptor is NULL or "<stdin>" or "???".
2184 */
2185int
2186Py_FdIsInteractive(FILE *fp, const char *filename)
2187{
2188 if (isatty((int)fileno(fp)))
2189 return 1;
2190 if (!Py_InteractiveFlag)
2191 return 0;
2192 return (filename == NULL) ||
2193 (strcmp(filename, "<stdin>") == 0) ||
2194 (strcmp(filename, "???") == 0);
2195}
2196
2197
Nick Coghland6009512014-11-20 21:39:37 +10002198/* Wrappers around sigaction() or signal(). */
2199
2200PyOS_sighandler_t
2201PyOS_getsig(int sig)
2202{
2203#ifdef HAVE_SIGACTION
2204 struct sigaction context;
2205 if (sigaction(sig, NULL, &context) == -1)
2206 return SIG_ERR;
2207 return context.sa_handler;
2208#else
2209 PyOS_sighandler_t handler;
2210/* Special signal handling for the secure CRT in Visual Studio 2005 */
2211#if defined(_MSC_VER) && _MSC_VER >= 1400
2212 switch (sig) {
2213 /* Only these signals are valid */
2214 case SIGINT:
2215 case SIGILL:
2216 case SIGFPE:
2217 case SIGSEGV:
2218 case SIGTERM:
2219 case SIGBREAK:
2220 case SIGABRT:
2221 break;
2222 /* Don't call signal() with other values or it will assert */
2223 default:
2224 return SIG_ERR;
2225 }
2226#endif /* _MSC_VER && _MSC_VER >= 1400 */
2227 handler = signal(sig, SIG_IGN);
2228 if (handler != SIG_ERR)
2229 signal(sig, handler);
2230 return handler;
2231#endif
2232}
2233
2234/*
2235 * All of the code in this function must only use async-signal-safe functions,
2236 * listed at `man 7 signal` or
2237 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2238 */
2239PyOS_sighandler_t
2240PyOS_setsig(int sig, PyOS_sighandler_t handler)
2241{
2242#ifdef HAVE_SIGACTION
2243 /* Some code in Modules/signalmodule.c depends on sigaction() being
2244 * used here if HAVE_SIGACTION is defined. Fix that if this code
2245 * changes to invalidate that assumption.
2246 */
2247 struct sigaction context, ocontext;
2248 context.sa_handler = handler;
2249 sigemptyset(&context.sa_mask);
2250 context.sa_flags = 0;
2251 if (sigaction(sig, &context, &ocontext) == -1)
2252 return SIG_ERR;
2253 return ocontext.sa_handler;
2254#else
2255 PyOS_sighandler_t oldhandler;
2256 oldhandler = signal(sig, handler);
2257#ifdef HAVE_SIGINTERRUPT
2258 siginterrupt(sig, 1);
2259#endif
2260 return oldhandler;
2261#endif
2262}
2263
2264#ifdef __cplusplus
2265}
2266#endif