blob: 8d0075a48db6ff0578787ac359ba5599430446df [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
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080069int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080070_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060071
Victor Stinnerf7e5b562017-11-15 15:48:08 -080072_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073_PyRuntime_Initialize(void)
74{
75 /* XXX We only initialize once in the process, which aligns with
76 the static initialization of the former globals now found in
77 _PyRuntime. However, _PyRuntime *should* be initialized with
78 every Py_Initialize() call, but doing so breaks the runtime.
79 This is because the runtime state is not properly finalized
80 currently. */
81 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080082 if (initialized) {
83 return _Py_INIT_OK();
84 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060085 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080086
87 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
89
90void
91_PyRuntime_Finalize(void)
92{
93 _PyRuntimeState_Fini(&_PyRuntime);
94}
95
96int
97_Py_IsFinalizing(void)
98{
99 return _PyRuntime.finalizing != NULL;
100}
101
Nick Coghland6009512014-11-20 21:39:37 +1000102/* Hack to force loading of object files */
103int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
104 PyOS_mystrnicmp; /* Python/pystrcmp.o */
105
106/* PyModule_GetWarningsModule is no longer necessary as of 2.6
107since _warnings is builtin. This API should not be used. */
108PyObject *
109PyModule_GetWarningsModule(void)
110{
111 return PyImport_ImportModule("warnings");
112}
113
Eric Snowc7ec9982017-05-23 23:00:52 -0700114
Eric Snow1abcf672017-05-23 21:46:51 -0700115/* APIs to access the initialization flags
116 *
117 * Can be called prior to Py_Initialize.
118 */
Nick Coghland6009512014-11-20 21:39:37 +1000119
Eric Snow1abcf672017-05-23 21:46:51 -0700120int
121_Py_IsCoreInitialized(void)
122{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600123 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700124}
Nick Coghland6009512014-11-20 21:39:37 +1000125
126int
127Py_IsInitialized(void)
128{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600129 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000130}
131
Nick Coghlan6ea41862017-06-11 13:16:15 +1000132
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000133/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
134 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000135 initializations fail, a fatal error is issued and the function does
136 not return. On return, the first thread and interpreter state have
137 been created.
138
139 Locking: you must hold the interpreter lock while calling this.
140 (If the lock has not yet been initialized, that's equivalent to
141 having the lock, but you cannot use multiple threads.)
142
143*/
144
Nick Coghland6009512014-11-20 21:39:37 +1000145static char*
146get_codec_name(const char *encoding)
147{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200148 const char *name_utf8;
149 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000150 PyObject *codec, *name = NULL;
151
152 codec = _PyCodec_Lookup(encoding);
153 if (!codec)
154 goto error;
155
156 name = _PyObject_GetAttrId(codec, &PyId_name);
157 Py_CLEAR(codec);
158 if (!name)
159 goto error;
160
Serhiy Storchaka06515832016-11-20 09:13:07 +0200161 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000162 if (name_utf8 == NULL)
163 goto error;
164 name_str = _PyMem_RawStrdup(name_utf8);
165 Py_DECREF(name);
166 if (name_str == NULL) {
167 PyErr_NoMemory();
168 return NULL;
169 }
170 return name_str;
171
172error:
173 Py_XDECREF(codec);
174 Py_XDECREF(name);
175 return NULL;
176}
177
Nick Coghland6009512014-11-20 21:39:37 +1000178
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800179static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700180initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000181{
182 PyObject *importlib;
183 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000184 PyObject *value;
185
186 /* Import _importlib through its frozen version, _frozen_importlib. */
187 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800188 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000189 }
190 else if (Py_VerboseFlag) {
191 PySys_FormatStderr("import _frozen_importlib # frozen\n");
192 }
193 importlib = PyImport_AddModule("_frozen_importlib");
194 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800195 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000196 }
197 interp->importlib = importlib;
198 Py_INCREF(interp->importlib);
199
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300200 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
201 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800202 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300203 Py_INCREF(interp->import_func);
204
Victor Stinnercd6e6942015-09-18 09:11:57 +0200205 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800206 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000207 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800208 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000209 }
210 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200211 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000212 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600213 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800214 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000215 }
216
Victor Stinnercd6e6942015-09-18 09:11:57 +0200217 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000218 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
219 if (value == NULL) {
220 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800221 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000222 }
223 Py_DECREF(value);
224 Py_DECREF(impmod);
225
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800226 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000227}
228
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800229static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700230initexternalimport(PyInterpreterState *interp)
231{
232 PyObject *value;
233 value = PyObject_CallMethod(interp->importlib,
234 "_install_external_importers", "");
235 if (value == NULL) {
236 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800237 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700238 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200239 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300240 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700241}
Nick Coghland6009512014-11-20 21:39:37 +1000242
Nick Coghlan6ea41862017-06-11 13:16:15 +1000243/* Helper functions to better handle the legacy C locale
244 *
245 * The legacy C locale assumes ASCII as the default text encoding, which
246 * causes problems not only for the CPython runtime, but also other
247 * components like GNU readline.
248 *
249 * Accordingly, when the CLI detects it, it attempts to coerce it to a
250 * more capable UTF-8 based alternative as follows:
251 *
252 * if (_Py_LegacyLocaleDetected()) {
253 * _Py_CoerceLegacyLocale();
254 * }
255 *
256 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
257 *
258 * Locale coercion also impacts the default error handler for the standard
259 * streams: while the usual default is "strict", the default for the legacy
260 * C locale and for any of the coercion target locales is "surrogateescape".
261 */
262
263int
264_Py_LegacyLocaleDetected(void)
265{
266#ifndef MS_WINDOWS
267 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000268 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
269 * the POSIX locale as a simple alias for the C locale, so
270 * we may also want to check for that explicitly.
271 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000272 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
273 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
274#else
275 /* Windows uses code pages instead of locales, so no locale is legacy */
276 return 0;
277#endif
278}
279
Nick Coghlaneb817952017-06-18 12:29:42 +1000280static const char *_C_LOCALE_WARNING =
281 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
282 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
283 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
284 "locales is recommended.\n";
285
Nick Coghlaneb817952017-06-18 12:29:42 +1000286static void
Victor Stinner94540602017-12-16 04:54:22 +0100287_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000288{
Victor Stinner06e76082018-09-19 14:56:36 -0700289 if (core_config->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200290 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000291 }
292}
293
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294typedef struct _CandidateLocale {
295 const char *locale_name; /* The locale to try as a coercion target */
296} _LocaleCoercionTarget;
297
298static _LocaleCoercionTarget _TARGET_LOCALES[] = {
299 {"C.UTF-8"},
300 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000301 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302 {NULL}
303};
304
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200305
306int
307_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000308{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200309 const _LocaleCoercionTarget *target = NULL;
310 for (target = _TARGET_LOCALES; target->locale_name; target++) {
311 if (strcmp(ctype_loc, target->locale_name) == 0) {
312 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200314 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200315 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000316}
317
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200318
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100320static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000321 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
322 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
323
324static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200325_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000326{
327 const char *newloc = target->locale_name;
328
329 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100330 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000331
332 /* Set the relevant locale environment variable */
333 if (setenv("LC_CTYPE", newloc, 1)) {
334 fprintf(stderr,
335 "Error setting LC_CTYPE, skipping C locale coercion\n");
336 return;
337 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200338 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100339 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000340 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000341
342 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100343 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000344}
345#endif
346
347void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200348_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000349{
350#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200351 char *oldloc = NULL;
352
353 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
354 if (oldloc == NULL) {
355 return;
356 }
357
Victor Stinner94540602017-12-16 04:54:22 +0100358 const char *locale_override = getenv("LC_ALL");
359 if (locale_override == NULL || *locale_override == '\0') {
360 /* LC_ALL is also not set (or is set to an empty string) */
361 const _LocaleCoercionTarget *target = NULL;
362 for (target = _TARGET_LOCALES; target->locale_name; target++) {
363 const char *new_locale = setlocale(LC_CTYPE,
364 target->locale_name);
365 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100366#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100367defined(HAVE_LANGINFO_H) && defined(CODESET)
368 /* Also ensure that nl_langinfo works in this locale */
369 char *codeset = nl_langinfo(CODESET);
370 if (!codeset || *codeset == '\0') {
371 /* CODESET is not set or empty, so skip coercion */
372 new_locale = NULL;
373 _Py_SetLocaleFromEnv(LC_CTYPE);
374 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000375 }
Victor Stinner94540602017-12-16 04:54:22 +0100376#endif
377 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200378 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200379 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000380 }
381 }
382 }
383 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200384
385 setlocale(LC_CTYPE, oldloc);
386
387done:
388 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000389#endif
390}
391
xdegaye1588be62017-11-12 12:45:59 +0100392/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
393 * isolate the idiosyncrasies of different libc implementations. It reads the
394 * appropriate environment variable and uses its value to select the locale for
395 * 'category'. */
396char *
397_Py_SetLocaleFromEnv(int category)
398{
Victor Stinner353933e2018-11-23 13:08:26 +0100399 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100400#ifdef __ANDROID__
401 const char *locale;
402 const char **pvar;
403#ifdef PY_COERCE_C_LOCALE
404 const char *coerce_c_locale;
405#endif
406 const char *utf8_locale = "C.UTF-8";
407 const char *env_var_set[] = {
408 "LC_ALL",
409 "LC_CTYPE",
410 "LANG",
411 NULL,
412 };
413
414 /* Android setlocale(category, "") doesn't check the environment variables
415 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
416 * check the environment variables listed in env_var_set. */
417 for (pvar=env_var_set; *pvar; pvar++) {
418 locale = getenv(*pvar);
419 if (locale != NULL && *locale != '\0') {
420 if (strcmp(locale, utf8_locale) == 0 ||
421 strcmp(locale, "en_US.UTF-8") == 0) {
422 return setlocale(category, utf8_locale);
423 }
424 return setlocale(category, "C");
425 }
426 }
427
428 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
429 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
430 * Quote from POSIX section "8.2 Internationalization Variables":
431 * "4. If the LANG environment variable is not set or is set to the empty
432 * string, the implementation-defined default locale shall be used." */
433
434#ifdef PY_COERCE_C_LOCALE
435 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
436 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
437 /* Some other ported code may check the environment variables (e.g. in
438 * extension modules), so we make sure that they match the locale
439 * configuration */
440 if (setenv("LC_CTYPE", utf8_locale, 1)) {
441 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
442 "environment variable to %s\n", utf8_locale);
443 }
444 }
445#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100446 res = setlocale(category, utf8_locale);
447#else /* !defined(__ANDROID__) */
448 res = setlocale(category, "");
449#endif
450 _Py_ResetForceASCII();
451 return res;
xdegaye1588be62017-11-12 12:45:59 +0100452}
453
Nick Coghlan6ea41862017-06-11 13:16:15 +1000454
Eric Snow1abcf672017-05-23 21:46:51 -0700455/* Global initializations. Can be undone by Py_Finalize(). Don't
456 call this twice without an intervening Py_Finalize() call.
457
Victor Stinner1dc6e392018-07-25 02:49:17 +0200458 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700459 must have a corresponding call to Py_Finalize.
460
461 Locking: you must hold the interpreter lock while calling these APIs.
462 (If the lock has not yet been initialized, that's equivalent to
463 having the lock, but you cannot use multiple threads.)
464
465*/
466
Victor Stinner1dc6e392018-07-25 02:49:17 +0200467static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100468_Py_Initialize_ReconfigureCore(PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200469 const _PyCoreConfig *core_config)
470{
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100471 PyThreadState *tstate = _PyThreadState_GET();
472 if (!tstate) {
473 return _Py_INIT_ERR("failed to read thread state");
474 }
475
476 PyInterpreterState *interp = tstate->interp;
477 if (interp == NULL) {
478 return _Py_INIT_ERR("can't make main interpreter");
479 }
480 *interp_p = interp;
481
482 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
483 Py_Initialize() ignores the new configuration. */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200484 if (core_config->allocator != NULL) {
485 const char *allocator = _PyMem_GetAllocatorsName();
486 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
487 return _Py_INIT_USER_ERR("cannot modify memory allocator "
488 "after first Py_Initialize()");
489 }
490 }
491
492 _PyCoreConfig_SetGlobalConfig(core_config);
493
494 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
495 return _Py_INIT_ERR("failed to copy core config");
496 }
497 core_config = &interp->core_config;
498
499 if (core_config->_install_importlib) {
500 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
501 if (_Py_INIT_FAILED(err)) {
502 return err;
503 }
504 }
505 return _Py_INIT_OK();
506}
507
508
Victor Stinner1dc6e392018-07-25 02:49:17 +0200509static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100510pycore_init_runtime(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000511{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200512 if (_PyRuntime.initialized) {
513 return _Py_INIT_ERR("main interpreter already initialized");
514 }
Victor Stinnerda273412017-12-15 01:46:02 +0100515
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200516 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000517
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100518 _PyInitError err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800519 if (_Py_INIT_FAILED(err)) {
520 return err;
521 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600522
Victor Stinner31e99082017-12-20 23:41:38 +0100523 if (core_config->allocator != NULL) {
524 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
525 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
526 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800527 }
528
Eric Snow1abcf672017-05-23 21:46:51 -0700529 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
530 * threads behave a little more gracefully at interpreter shutdown.
531 * We clobber it here so the new interpreter can start with a clean
532 * slate.
533 *
534 * However, this may still lead to misbehaviour if there are daemon
535 * threads still hanging around from a previous Py_Initialize/Finalize
536 * pair :(
537 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600538 _PyRuntime.finalizing = NULL;
539
Victor Stinnerda273412017-12-15 01:46:02 +0100540 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800541 if (_Py_INIT_FAILED(err)) {
542 return err;
543 }
544
Victor Stinnera7368ac2017-11-15 18:11:45 -0800545 err = _PyInterpreterState_Enable(&_PyRuntime);
546 if (_Py_INIT_FAILED(err)) {
547 return err;
548 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100549 return _Py_INIT_OK();
550}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800551
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100552
553static _PyInitError
554pycore_create_interpreter(const _PyCoreConfig *core_config,
555 PyInterpreterState **interp_p)
556{
557 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100558 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800559 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100560 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200561 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100562
563 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
564 return _Py_INIT_ERR("failed to copy core config");
565 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200566 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000567
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200568 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000569 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800570 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000571 (void) PyThreadState_Swap(tstate);
572
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000573 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000574 destroying the GIL might fail when it is being referenced from
575 another running thread (see issue #9901).
576 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000577 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000578 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100579
Nick Coghland6009512014-11-20 21:39:37 +1000580 /* Auto-thread-state API */
581 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000582
Victor Stinner2914bb32018-01-29 11:57:45 +0100583 /* Create the GIL */
584 PyEval_InitThreads();
585
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100586 return _Py_INIT_OK();
587}
Nick Coghland6009512014-11-20 21:39:37 +1000588
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100589
590static _PyInitError
591pycore_init_types(void)
592{
Victor Stinnerab672812019-01-23 15:04:40 +0100593 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100594 if (_Py_INIT_FAILED(err)) {
595 return err;
596 }
597
598 err = _PyUnicode_Init();
599 if (_Py_INIT_FAILED(err)) {
600 return err;
601 }
602
603 if (_PyStructSequence_Init() < 0) {
604 return _Py_INIT_ERR("can't initialize structseq");
605 }
606
607 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800608 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100609 }
Nick Coghland6009512014-11-20 21:39:37 +1000610
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100611 err = _PyExc_Init();
612 if (_Py_INIT_FAILED(err)) {
613 return err;
614 }
615
616 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800617 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100618 }
Nick Coghland6009512014-11-20 21:39:37 +1000619
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100620 if (!_PyContext_Init()) {
621 return _Py_INIT_ERR("can't init context");
622 }
623 return _Py_INIT_OK();
624}
625
626
627static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100628pycore_init_builtins(PyInterpreterState *interp)
629{
630 PyObject *bimod = _PyBuiltin_Init();
631 if (bimod == NULL) {
632 return _Py_INIT_ERR("can't initialize builtins modules");
633 }
634 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
635
636 interp->builtins = PyModule_GetDict(bimod);
637 if (interp->builtins == NULL) {
638 return _Py_INIT_ERR("can't initialize builtins dict");
639 }
640 Py_INCREF(interp->builtins);
641
642 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
643 if (_Py_INIT_FAILED(err)) {
644 return err;
645 }
646 return _Py_INIT_OK();
647}
648
649
650static _PyInitError
651pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
652{
653 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800654 if (_Py_INIT_FAILED(err)) {
655 return err;
656 }
Nick Coghland6009512014-11-20 21:39:37 +1000657
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800658 err = _PyImportHooks_Init();
659 if (_Py_INIT_FAILED(err)) {
660 return err;
661 }
Nick Coghland6009512014-11-20 21:39:37 +1000662
663 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100664 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100665 return _Py_INIT_ERR("can't initialize warnings");
666 }
Nick Coghland6009512014-11-20 21:39:37 +1000667
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100668 if (interp->core_config._install_importlib) {
669 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200670 if (_Py_INIT_FAILED(err)) {
671 return err;
672 }
673 }
674
Eric Snow1abcf672017-05-23 21:46:51 -0700675 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100676 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800677 err = initimport(interp, sysmod);
678 if (_Py_INIT_FAILED(err)) {
679 return err;
680 }
Eric Snow1abcf672017-05-23 21:46:51 -0700681 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100682 return _Py_INIT_OK();
683}
684
685
686static _PyInitError
687_Py_InitializeCore_impl(PyInterpreterState **interp_p,
688 const _PyCoreConfig *core_config)
689{
690 PyInterpreterState *interp;
691
692 _PyInitError err = pycore_init_runtime(core_config);
693 if (_Py_INIT_FAILED(err)) {
694 return err;
695 }
696
697 err = pycore_create_interpreter(core_config, &interp);
698 if (_Py_INIT_FAILED(err)) {
699 return err;
700 }
701 core_config = &interp->core_config;
702 *interp_p = interp;
703
704 err = pycore_init_types();
705 if (_Py_INIT_FAILED(err)) {
706 return err;
707 }
708
709 PyObject *sysmod;
Victor Stinnerab672812019-01-23 15:04:40 +0100710 err = _PySys_Create(interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100711 if (_Py_INIT_FAILED(err)) {
712 return err;
713 }
714
715 err = pycore_init_builtins(interp);
716 if (_Py_INIT_FAILED(err)) {
717 return err;
718 }
719
720 err = pycore_init_import_warnings(interp, sysmod);
721 if (_Py_INIT_FAILED(err)) {
722 return err;
723 }
Eric Snow1abcf672017-05-23 21:46:51 -0700724
725 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600726 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800727 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700728}
729
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100730/* Begin interpreter initialization
731 *
732 * On return, the first thread and interpreter state have been created,
733 * but the compiler, signal handling, multithreading and
734 * multiple interpreter support, and codec infrastructure are not yet
735 * available.
736 *
737 * The import system will support builtin and frozen modules only.
738 * The only supported io is writing to sys.stderr
739 *
740 * If any operation invoked by this function fails, a fatal error is
741 * issued and the function does not return.
742 *
743 * Any code invoked from this function should *not* assume it has access
744 * to the Python C API (unless the API is explicitly listed as being
745 * safe to call without calling Py_Initialize first)
746 */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200747_PyInitError
748_Py_InitializeCore(PyInterpreterState **interp_p,
749 const _PyCoreConfig *src_config)
750{
751 assert(src_config != NULL);
752
Victor Stinner1dc6e392018-07-25 02:49:17 +0200753 PyMemAllocatorEx old_alloc;
754 _PyInitError err;
755
756 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
757 (and the input configuration is read only). */
758 _PyCoreConfig config = _PyCoreConfig_INIT;
759
Victor Stinner177d9212018-08-29 11:25:15 +0200760 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200761 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200762
Victor Stinner1dc6e392018-07-25 02:49:17 +0200763 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
764 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
765 err = _PyCoreConfig_Read(&config);
766 }
767 else {
768 err = _Py_INIT_ERR("failed to copy core config");
769 }
770 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
771
772 if (_Py_INIT_FAILED(err)) {
773 goto done;
774 }
775
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100776 if (!_PyRuntime.core_initialized) {
777 err = _Py_InitializeCore_impl(interp_p, &config);
778 }
779 else {
780 err = _Py_Initialize_ReconfigureCore(interp_p, &config);
781 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200782
783done:
784 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
785 _PyCoreConfig_Clear(&config);
786 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
787
788 return err;
789}
790
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200791/* Py_Initialize() has already been called: update the main interpreter
792 configuration. Example of bpo-34008: Py_Main() called after
793 Py_Initialize(). */
794static _PyInitError
795_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
796 const _PyMainInterpreterConfig *config)
797{
798 if (config->argv != NULL) {
799 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
800 if (res < 0) {
801 return _Py_INIT_ERR("fail to set sys.argv");
802 }
803 }
804 return _Py_INIT_OK();
805}
806
Eric Snowc7ec9982017-05-23 23:00:52 -0700807/* Update interpreter state based on supplied configuration settings
808 *
809 * After calling this function, most of the restrictions on the interpreter
810 * are lifted. The only remaining incomplete settings are those related
811 * to the main module (sys.argv[0], __main__ metadata)
812 *
813 * Calling this when the interpreter is not initializing, is already
814 * initialized or without a valid current thread state is a fatal error.
815 * Other errors should be reported as normal Python exceptions with a
816 * non-zero return code.
817 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800818_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200819_Py_InitializeMainInterpreter(PyInterpreterState *interp,
820 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700821{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600822 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800823 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700824 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700825
Victor Stinner1dc6e392018-07-25 02:49:17 +0200826 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100827 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
828 return _Py_INIT_ERR("failed to copy main interpreter config");
829 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200830 config = &interp->config;
831 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700832
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200833 if (_PyRuntime.initialized) {
834 return _Py_ReconfigureMainInterpreter(interp, config);
835 }
836
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200837 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700838 /* Special mode for freeze_importlib: run with no import system
839 *
840 * This means anything which needs support from extension modules
841 * or pure Python code in the standard library won't work.
842 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600843 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800844 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700845 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100846
Victor Stinner33c377e2017-12-05 15:12:41 +0100847 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800848 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100849 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200850
Victor Stinnerab672812019-01-23 15:04:40 +0100851 if (_PySys_InitMain(interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800852 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100853 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800854
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200855 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800856 if (_Py_INIT_FAILED(err)) {
857 return err;
858 }
Nick Coghland6009512014-11-20 21:39:37 +1000859
860 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200861 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800862 if (_Py_INIT_FAILED(err)) {
863 return err;
864 }
Nick Coghland6009512014-11-20 21:39:37 +1000865
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800866 err = initfsencoding(interp);
867 if (_Py_INIT_FAILED(err)) {
868 return err;
869 }
Nick Coghland6009512014-11-20 21:39:37 +1000870
Victor Stinner1f151112017-11-23 10:43:14 +0100871 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800872 err = initsigs(); /* Signal handling stuff, including initintr() */
873 if (_Py_INIT_FAILED(err)) {
874 return err;
875 }
876 }
Nick Coghland6009512014-11-20 21:39:37 +1000877
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200878 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800879 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200880 }
Nick Coghland6009512014-11-20 21:39:37 +1000881
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800882 err = add_main_module(interp);
883 if (_Py_INIT_FAILED(err)) {
884 return err;
885 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800886
Victor Stinner91106cd2017-12-13 12:29:09 +0100887 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800888 if (_Py_INIT_FAILED(err)) {
889 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800890 }
Nick Coghland6009512014-11-20 21:39:37 +1000891
892 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100893 PyObject *warnoptions = PySys_GetObject("warnoptions");
894 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100895 {
Nick Coghland6009512014-11-20 21:39:37 +1000896 PyObject *warnings_module = PyImport_ImportModule("warnings");
897 if (warnings_module == NULL) {
898 fprintf(stderr, "'import warnings' failed; traceback:\n");
899 PyErr_Print();
900 }
901 Py_XDECREF(warnings_module);
902 }
903
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600904 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700905
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200906 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800907 err = initsite(); /* Module site */
908 if (_Py_INIT_FAILED(err)) {
909 return err;
910 }
911 }
Victor Stinnercf215042018-08-29 22:56:06 +0200912
913#ifndef MS_WINDOWS
914 _emit_stderr_warning_for_legacy_locale(core_config);
915#endif
916
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800917 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000918}
919
Eric Snowc7ec9982017-05-23 23:00:52 -0700920#undef _INIT_DEBUG_PRINT
921
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800922_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200923_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700924{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700925 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800926 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200927 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800928 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200929 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800930 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200931 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100932
Victor Stinner9cfc0022017-12-20 19:36:46 +0100933 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200934 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100935 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200936 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800937 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100938 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800939 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200940 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800941 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200942 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700943}
944
945
946void
Nick Coghland6009512014-11-20 21:39:37 +1000947Py_InitializeEx(int install_sigs)
948{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200949 if (_PyRuntime.initialized) {
950 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
951 return;
952 }
953
954 _PyInitError err;
955 _PyCoreConfig config = _PyCoreConfig_INIT;
956 config.install_signal_handlers = install_sigs;
957
958 err = _Py_InitializeFromConfig(&config);
959 _PyCoreConfig_Clear(&config);
960
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800961 if (_Py_INIT_FAILED(err)) {
962 _Py_FatalInitError(err);
963 }
Nick Coghland6009512014-11-20 21:39:37 +1000964}
965
966void
967Py_Initialize(void)
968{
969 Py_InitializeEx(1);
970}
971
972
973#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000974extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000975#endif
976
977/* Flush stdout and stderr */
978
979static int
980file_is_closed(PyObject *fobj)
981{
982 int r;
983 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
984 if (tmp == NULL) {
985 PyErr_Clear();
986 return 0;
987 }
988 r = PyObject_IsTrue(tmp);
989 Py_DECREF(tmp);
990 if (r < 0)
991 PyErr_Clear();
992 return r > 0;
993}
994
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000995static int
Nick Coghland6009512014-11-20 21:39:37 +1000996flush_std_files(void)
997{
998 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
999 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1000 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001001 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001002
1003 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001004 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001005 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001006 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001007 status = -1;
1008 }
Nick Coghland6009512014-11-20 21:39:37 +10001009 else
1010 Py_DECREF(tmp);
1011 }
1012
1013 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001014 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001015 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001016 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001017 status = -1;
1018 }
Nick Coghland6009512014-11-20 21:39:37 +10001019 else
1020 Py_DECREF(tmp);
1021 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001022
1023 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001024}
1025
1026/* Undo the effect of Py_Initialize().
1027
1028 Beware: if multiple interpreter and/or thread states exist, these
1029 are not wiped out; only the current thread and interpreter state
1030 are deleted. But since everything else is deleted, those other
1031 interpreter and thread states should no longer be used.
1032
1033 (XXX We should do better, e.g. wipe out all interpreters and
1034 threads.)
1035
1036 Locking: as above.
1037
1038*/
1039
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001040int
1041Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001042{
1043 PyInterpreterState *interp;
1044 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001045 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001046
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001047 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001048 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001049
1050 wait_for_thread_shutdown();
1051
Marcel Plch776407f2017-12-20 11:17:58 +01001052 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001053 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001054 interp = tstate->interp;
1055
Nick Coghland6009512014-11-20 21:39:37 +10001056 /* The interpreter is still entirely intact at this point, and the
1057 * exit funcs may be relying on that. In particular, if some thread
1058 * or exit func is still waiting to do an import, the import machinery
1059 * expects Py_IsInitialized() to return true. So don't say the
1060 * interpreter is uninitialized until after the exit funcs have run.
1061 * Note that Threading.py uses an exit func to do a join on all the
1062 * threads created thru it, so this also protects pending imports in
1063 * the threads created via Threading.
1064 */
Nick Coghland6009512014-11-20 21:39:37 +10001065
Marcel Plch776407f2017-12-20 11:17:58 +01001066 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001067
Victor Stinnerda273412017-12-15 01:46:02 +01001068 /* Copy the core config, PyInterpreterState_Delete() free
1069 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001070#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001071 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001072#endif
1073#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001074 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001075#endif
1076#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001077 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001078#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001079
Nick Coghland6009512014-11-20 21:39:37 +10001080 /* Remaining threads (e.g. daemon threads) will automatically exit
1081 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001082 _PyRuntime.finalizing = tstate;
1083 _PyRuntime.initialized = 0;
1084 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001085
Victor Stinnere0deff32015-03-24 13:46:18 +01001086 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001087 if (flush_std_files() < 0) {
1088 status = -1;
1089 }
Nick Coghland6009512014-11-20 21:39:37 +10001090
1091 /* Disable signal handling */
1092 PyOS_FiniInterrupts();
1093
1094 /* Collect garbage. This may call finalizers; it's nice to call these
1095 * before all modules are destroyed.
1096 * XXX If a __del__ or weakref callback is triggered here, and tries to
1097 * XXX import a module, bad things can happen, because Python no
1098 * XXX longer believes it's initialized.
1099 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1100 * XXX is easy to provoke that way. I've also seen, e.g.,
1101 * XXX Exception exceptions.ImportError: 'No module named sha'
1102 * XXX in <function callback at 0x008F5718> ignored
1103 * XXX but I'm unclear on exactly how that one happens. In any case,
1104 * XXX I haven't seen a real-life report of either of these.
1105 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001106 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001107#ifdef COUNT_ALLOCS
1108 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1109 each collection might release some types from the type
1110 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001111 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001112 /* nothing */;
1113#endif
Eric Snowdae02762017-09-14 00:35:58 -07001114
Nick Coghland6009512014-11-20 21:39:37 +10001115 /* Destroy all modules */
1116 PyImport_Cleanup();
1117
Victor Stinnere0deff32015-03-24 13:46:18 +01001118 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001119 if (flush_std_files() < 0) {
1120 status = -1;
1121 }
Nick Coghland6009512014-11-20 21:39:37 +10001122
1123 /* Collect final garbage. This disposes of cycles created by
1124 * class definitions, for example.
1125 * XXX This is disabled because it caused too many problems. If
1126 * XXX a __del__ or weakref callback triggers here, Python code has
1127 * XXX a hard time running, because even the sys module has been
1128 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1129 * XXX One symptom is a sequence of information-free messages
1130 * XXX coming from threads (if a __del__ or callback is invoked,
1131 * XXX other threads can execute too, and any exception they encounter
1132 * XXX triggers a comedy of errors as subsystem after subsystem
1133 * XXX fails to find what it *expects* to find in sys to help report
1134 * XXX the exception and consequent unexpected failures). I've also
1135 * XXX seen segfaults then, after adding print statements to the
1136 * XXX Python code getting called.
1137 */
1138#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001139 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001140#endif
1141
1142 /* Disable tracemalloc after all Python objects have been destroyed,
1143 so it is possible to use tracemalloc in objects destructor. */
1144 _PyTraceMalloc_Fini();
1145
1146 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1147 _PyImport_Fini();
1148
1149 /* Cleanup typeobject.c's internal caches. */
1150 _PyType_Fini();
1151
1152 /* unload faulthandler module */
1153 _PyFaulthandler_Fini();
1154
1155 /* Debugging stuff */
1156#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001157 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001158#endif
1159 /* dump hash stats */
1160 _PyHash_Fini();
1161
Eric Snowdae02762017-09-14 00:35:58 -07001162#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001163 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001164 _PyDebug_PrintTotalRefs();
1165 }
Eric Snowdae02762017-09-14 00:35:58 -07001166#endif
Nick Coghland6009512014-11-20 21:39:37 +10001167
1168#ifdef Py_TRACE_REFS
1169 /* Display all objects still alive -- this can invoke arbitrary
1170 * __repr__ overrides, so requires a mostly-intact interpreter.
1171 * Alas, a lot of stuff may still be alive now that will be cleaned
1172 * up later.
1173 */
Victor Stinnerda273412017-12-15 01:46:02 +01001174 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001175 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001176 }
Nick Coghland6009512014-11-20 21:39:37 +10001177#endif /* Py_TRACE_REFS */
1178
1179 /* Clear interpreter state and all thread states. */
1180 PyInterpreterState_Clear(interp);
1181
1182 /* Now we decref the exception classes. After this point nothing
1183 can raise an exception. That's okay, because each Fini() method
1184 below has been checked to make sure no exceptions are ever
1185 raised.
1186 */
1187
1188 _PyExc_Fini();
1189
1190 /* Sundry finalizers */
1191 PyMethod_Fini();
1192 PyFrame_Fini();
1193 PyCFunction_Fini();
1194 PyTuple_Fini();
1195 PyList_Fini();
1196 PySet_Fini();
1197 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001198 PyLong_Fini();
1199 PyFloat_Fini();
1200 PyDict_Fini();
1201 PySlice_Fini();
1202 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001203 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001204 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001205 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001206 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001207
1208 /* Cleanup Unicode implementation */
1209 _PyUnicode_Fini();
1210
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001211 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001212
1213 /* XXX Still allocated:
1214 - various static ad-hoc pointers to interned strings
1215 - int and float free list blocks
1216 - whatever various modules and libraries allocate
1217 */
1218
1219 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1220
1221 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001222 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001223
1224 /* Delete current thread. After this, many C API calls become crashy. */
1225 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001226
Nick Coghland6009512014-11-20 21:39:37 +10001227 PyInterpreterState_Delete(interp);
1228
1229#ifdef Py_TRACE_REFS
1230 /* Display addresses (& refcnts) of all objects still alive.
1231 * An address can be used to find the repr of the object, printed
1232 * above by _Py_PrintReferences.
1233 */
Victor Stinnerda273412017-12-15 01:46:02 +01001234 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001235 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001236 }
Nick Coghland6009512014-11-20 21:39:37 +10001237#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001238#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001239 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001240 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001241 }
Nick Coghland6009512014-11-20 21:39:37 +10001242#endif
1243
1244 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001245
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001246 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001247 return status;
1248}
1249
1250void
1251Py_Finalize(void)
1252{
1253 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001254}
1255
1256/* Create and initialize a new interpreter and thread, and return the
1257 new thread. This requires that Py_Initialize() has been called
1258 first.
1259
1260 Unsuccessful initialization yields a NULL pointer. Note that *no*
1261 exception information is available even in this case -- the
1262 exception information is held in the thread, and there is no
1263 thread.
1264
1265 Locking: as above.
1266
1267*/
1268
Victor Stinnera7368ac2017-11-15 18:11:45 -08001269static _PyInitError
1270new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001271{
1272 PyInterpreterState *interp;
1273 PyThreadState *tstate, *save_tstate;
1274 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001275 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001276
Victor Stinnera7368ac2017-11-15 18:11:45 -08001277 if (!_PyRuntime.initialized) {
1278 return _Py_INIT_ERR("Py_Initialize must be called first");
1279 }
Nick Coghland6009512014-11-20 21:39:37 +10001280
Victor Stinner8a1be612016-03-14 22:07:55 +01001281 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1282 interpreters: disable PyGILState_Check(). */
1283 _PyGILState_check_enabled = 0;
1284
Nick Coghland6009512014-11-20 21:39:37 +10001285 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001286 if (interp == NULL) {
1287 *tstate_p = NULL;
1288 return _Py_INIT_OK();
1289 }
Nick Coghland6009512014-11-20 21:39:37 +10001290
1291 tstate = PyThreadState_New(interp);
1292 if (tstate == NULL) {
1293 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001294 *tstate_p = NULL;
1295 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001296 }
1297
1298 save_tstate = PyThreadState_Swap(tstate);
1299
Eric Snow1abcf672017-05-23 21:46:51 -07001300 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001301 _PyCoreConfig *core_config;
1302 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001303 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001304 core_config = &save_tstate->interp->core_config;
1305 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001306 } else {
1307 /* No current thread state, copy from the main interpreter */
1308 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001309 core_config = &main_interp->core_config;
1310 config = &main_interp->config;
1311 }
1312
1313 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1314 return _Py_INIT_ERR("failed to copy core config");
1315 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001316 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001317 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1318 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001319 }
1320
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001321 err = _PyExc_Init();
1322 if (_Py_INIT_FAILED(err)) {
1323 return err;
1324 }
1325
Nick Coghland6009512014-11-20 21:39:37 +10001326 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001327 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001328 if (modules == NULL) {
1329 return _Py_INIT_ERR("can't make modules dictionary");
1330 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001331 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001332
Eric Snowd393c1b2017-09-14 12:18:12 -06001333 sysmod = _PyImport_FindBuiltin("sys", modules);
1334 if (sysmod != NULL) {
1335 interp->sysdict = PyModule_GetDict(sysmod);
1336 if (interp->sysdict == NULL)
1337 goto handle_error;
1338 Py_INCREF(interp->sysdict);
1339 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerab672812019-01-23 15:04:40 +01001340 if (_PySys_InitMain(interp) < 0) {
1341 return _Py_INIT_ERR("can't finish initializing sys");
1342 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001343 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001344 else if (PyErr_Occurred()) {
1345 goto handle_error;
1346 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001347
1348 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001349 if (bimod != NULL) {
1350 interp->builtins = PyModule_GetDict(bimod);
1351 if (interp->builtins == NULL)
1352 goto handle_error;
1353 Py_INCREF(interp->builtins);
1354 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001355 else if (PyErr_Occurred()) {
1356 goto handle_error;
1357 }
Nick Coghland6009512014-11-20 21:39:37 +10001358
Nick Coghland6009512014-11-20 21:39:37 +10001359 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001360 err = _PyBuiltins_AddExceptions(bimod);
1361 if (_Py_INIT_FAILED(err)) {
1362 return err;
1363 }
Nick Coghland6009512014-11-20 21:39:37 +10001364
Victor Stinnerab672812019-01-23 15:04:40 +01001365 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1366 if (_Py_INIT_FAILED(err)) {
1367 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001368 }
Nick Coghland6009512014-11-20 21:39:37 +10001369
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001370 err = _PyImportHooks_Init();
1371 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001372 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001373 }
Nick Coghland6009512014-11-20 21:39:37 +10001374
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001375 err = initimport(interp, sysmod);
1376 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001377 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001378 }
Nick Coghland6009512014-11-20 21:39:37 +10001379
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001380 err = initexternalimport(interp);
1381 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001382 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001383 }
Nick Coghland6009512014-11-20 21:39:37 +10001384
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001385 err = initfsencoding(interp);
1386 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001387 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001388 }
1389
Victor Stinner91106cd2017-12-13 12:29:09 +01001390 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001391 if (_Py_INIT_FAILED(err)) {
1392 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001393 }
1394
1395 err = add_main_module(interp);
1396 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001397 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001398 }
1399
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001400 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001401 err = initsite();
1402 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001403 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001404 }
1405 }
Nick Coghland6009512014-11-20 21:39:37 +10001406 }
1407
Victor Stinnera7368ac2017-11-15 18:11:45 -08001408 if (PyErr_Occurred()) {
1409 goto handle_error;
1410 }
Nick Coghland6009512014-11-20 21:39:37 +10001411
Victor Stinnera7368ac2017-11-15 18:11:45 -08001412 *tstate_p = tstate;
1413 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001414
Nick Coghland6009512014-11-20 21:39:37 +10001415handle_error:
1416 /* Oops, it didn't work. Undo it all. */
1417
1418 PyErr_PrintEx(0);
1419 PyThreadState_Clear(tstate);
1420 PyThreadState_Swap(save_tstate);
1421 PyThreadState_Delete(tstate);
1422 PyInterpreterState_Delete(interp);
1423
Victor Stinnera7368ac2017-11-15 18:11:45 -08001424 *tstate_p = NULL;
1425 return _Py_INIT_OK();
1426}
1427
1428PyThreadState *
1429Py_NewInterpreter(void)
1430{
1431 PyThreadState *tstate;
1432 _PyInitError err = new_interpreter(&tstate);
1433 if (_Py_INIT_FAILED(err)) {
1434 _Py_FatalInitError(err);
1435 }
1436 return tstate;
1437
Nick Coghland6009512014-11-20 21:39:37 +10001438}
1439
1440/* Delete an interpreter and its last thread. This requires that the
1441 given thread state is current, that the thread has no remaining
1442 frames, and that it is its interpreter's only remaining thread.
1443 It is a fatal error to violate these constraints.
1444
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001445 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001446 everything, regardless.)
1447
1448 Locking: as above.
1449
1450*/
1451
1452void
1453Py_EndInterpreter(PyThreadState *tstate)
1454{
1455 PyInterpreterState *interp = tstate->interp;
1456
Victor Stinner50b48572018-11-01 01:51:40 +01001457 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001458 Py_FatalError("Py_EndInterpreter: thread is not current");
1459 if (tstate->frame != NULL)
1460 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1461
1462 wait_for_thread_shutdown();
1463
Marcel Plch776407f2017-12-20 11:17:58 +01001464 call_py_exitfuncs(interp);
1465
Nick Coghland6009512014-11-20 21:39:37 +10001466 if (tstate != interp->tstate_head || tstate->next != NULL)
1467 Py_FatalError("Py_EndInterpreter: not the last thread");
1468
1469 PyImport_Cleanup();
1470 PyInterpreterState_Clear(interp);
1471 PyThreadState_Swap(NULL);
1472 PyInterpreterState_Delete(interp);
1473}
1474
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001475/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001476
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001477static _PyInitError
1478add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001479{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001480 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001481 m = PyImport_AddModule("__main__");
1482 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001483 return _Py_INIT_ERR("can't create __main__ module");
1484
Nick Coghland6009512014-11-20 21:39:37 +10001485 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001486 ann_dict = PyDict_New();
1487 if ((ann_dict == NULL) ||
1488 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001489 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001490 }
1491 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001492
Nick Coghland6009512014-11-20 21:39:37 +10001493 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1494 PyObject *bimod = PyImport_ImportModule("builtins");
1495 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001496 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001497 }
1498 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001499 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001500 }
1501 Py_DECREF(bimod);
1502 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001503
Nick Coghland6009512014-11-20 21:39:37 +10001504 /* Main is a little special - imp.is_builtin("__main__") will return
1505 * False, but BuiltinImporter is still the most appropriate initial
1506 * setting for its __loader__ attribute. A more suitable value will
1507 * be set if __main__ gets further initialized later in the startup
1508 * process.
1509 */
1510 loader = PyDict_GetItemString(d, "__loader__");
1511 if (loader == NULL || loader == Py_None) {
1512 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1513 "BuiltinImporter");
1514 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001516 }
1517 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001518 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001519 }
1520 Py_DECREF(loader);
1521 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001522 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001523}
1524
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001525static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001526initfsencoding(PyInterpreterState *interp)
1527{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001528 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001529
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001530 char *encoding = get_codec_name(config->filesystem_encoding);
1531 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001532 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001533 memory, import a module of the standard library failed, etc. */
1534 return _Py_INIT_ERR("failed to get the Python codec "
1535 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001536 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001537
1538 /* Update the filesystem encoding to the normalized Python codec name.
1539 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1540 (Python codec name). */
1541 PyMem_RawFree(config->filesystem_encoding);
1542 config->filesystem_encoding = encoding;
1543
1544 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1545 global configuration variables. */
1546 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1547 config->filesystem_errors) < 0) {
1548 return _Py_INIT_NO_MEMORY();
1549 }
1550
1551 /* PyUnicode can now use the Python codec rather than C implementation
1552 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001553 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001554 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001555}
1556
1557/* Import the site module (not into __main__ though) */
1558
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001559static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001560initsite(void)
1561{
1562 PyObject *m;
1563 m = PyImport_ImportModule("site");
1564 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001565 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001566 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001567 Py_DECREF(m);
1568 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001569}
1570
Victor Stinner874dbe82015-09-04 17:29:57 +02001571/* Check if a file descriptor is valid or not.
1572 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1573static int
1574is_valid_fd(int fd)
1575{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001576#ifdef __APPLE__
1577 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1578 and the other side of the pipe is closed, dup(1) succeed, whereas
1579 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1580 such error. */
1581 struct stat st;
1582 return (fstat(fd, &st) == 0);
1583#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001584 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001585 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001586 return 0;
1587 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001588 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1589 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1590 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001591 fd2 = dup(fd);
1592 if (fd2 >= 0)
1593 close(fd2);
1594 _Py_END_SUPPRESS_IPH
1595 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001596#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001597}
1598
1599/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001600static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001601create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001602 int fd, int write_mode, const char* name,
1603 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001604{
1605 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1606 const char* mode;
1607 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001608 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001609 int buffering, isatty;
1610 _Py_IDENTIFIER(open);
1611 _Py_IDENTIFIER(isatty);
1612 _Py_IDENTIFIER(TextIOWrapper);
1613 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001614 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001615
Victor Stinner874dbe82015-09-04 17:29:57 +02001616 if (!is_valid_fd(fd))
1617 Py_RETURN_NONE;
1618
Nick Coghland6009512014-11-20 21:39:37 +10001619 /* stdin is always opened in buffered mode, first because it shouldn't
1620 make a difference in common use cases, second because TextIOWrapper
1621 depends on the presence of a read1() method which only exists on
1622 buffered streams.
1623 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001624 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001625 buffering = 0;
1626 else
1627 buffering = -1;
1628 if (write_mode)
1629 mode = "wb";
1630 else
1631 mode = "rb";
1632 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1633 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001634 Py_None, Py_None, /* encoding, errors */
1635 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001636 if (buf == NULL)
1637 goto error;
1638
1639 if (buffering) {
1640 _Py_IDENTIFIER(raw);
1641 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1642 if (raw == NULL)
1643 goto error;
1644 }
1645 else {
1646 raw = buf;
1647 Py_INCREF(raw);
1648 }
1649
Steve Dower39294992016-08-30 21:22:36 -07001650#ifdef MS_WINDOWS
1651 /* Windows console IO is always UTF-8 encoded */
1652 if (PyWindowsConsoleIO_Check(raw))
1653 encoding = "utf-8";
1654#endif
1655
Nick Coghland6009512014-11-20 21:39:37 +10001656 text = PyUnicode_FromString(name);
1657 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1658 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001659 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001660 if (res == NULL)
1661 goto error;
1662 isatty = PyObject_IsTrue(res);
1663 Py_DECREF(res);
1664 if (isatty == -1)
1665 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001666 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001667 write_through = Py_True;
1668 else
1669 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001670 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001671 line_buffering = Py_True;
1672 else
1673 line_buffering = Py_False;
1674
1675 Py_CLEAR(raw);
1676 Py_CLEAR(text);
1677
1678#ifdef MS_WINDOWS
1679 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1680 newlines to "\n".
1681 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1682 newline = NULL;
1683#else
1684 /* sys.stdin: split lines at "\n".
1685 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1686 newline = "\n";
1687#endif
1688
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001689 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001690 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001691 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001692 Py_CLEAR(buf);
1693 if (stream == NULL)
1694 goto error;
1695
1696 if (write_mode)
1697 mode = "w";
1698 else
1699 mode = "r";
1700 text = PyUnicode_FromString(mode);
1701 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1702 goto error;
1703 Py_CLEAR(text);
1704 return stream;
1705
1706error:
1707 Py_XDECREF(buf);
1708 Py_XDECREF(stream);
1709 Py_XDECREF(text);
1710 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001711
Victor Stinner874dbe82015-09-04 17:29:57 +02001712 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1713 /* Issue #24891: the file descriptor was closed after the first
1714 is_valid_fd() check was called. Ignore the OSError and set the
1715 stream to None. */
1716 PyErr_Clear();
1717 Py_RETURN_NONE;
1718 }
1719 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001720}
1721
1722/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001723static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001724init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001725{
1726 PyObject *iomod = NULL, *wrapper;
1727 PyObject *bimod = NULL;
1728 PyObject *m;
1729 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001730 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001731 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001732 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001733 _PyCoreConfig *config = &interp->core_config;
1734
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001735 /* Check that stdin is not a directory
1736 Using shell redirection, you can redirect stdin to a directory,
1737 crashing the Python interpreter. Catch this common mistake here
1738 and output a useful error message. Note that under MS Windows,
1739 the shell already prevents that. */
1740#ifndef MS_WINDOWS
1741 struct _Py_stat_struct sb;
1742 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1743 S_ISDIR(sb.st_mode)) {
1744 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1745 "cannot continue");
1746 }
1747#endif
1748
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001749 char *codec_name = get_codec_name(config->stdio_encoding);
1750 if (codec_name == NULL) {
1751 return _Py_INIT_ERR("failed to get the Python codec name "
1752 "of the stdio encoding");
1753 }
1754 PyMem_RawFree(config->stdio_encoding);
1755 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001756
1757 /* Hack to avoid a nasty recursion issue when Python is invoked
1758 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1759 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1760 goto error;
1761 }
1762 Py_DECREF(m);
1763
1764 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1765 goto error;
1766 }
1767 Py_DECREF(m);
1768
1769 if (!(bimod = PyImport_ImportModule("builtins"))) {
1770 goto error;
1771 }
1772
1773 if (!(iomod = PyImport_ImportModule("io"))) {
1774 goto error;
1775 }
1776 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1777 goto error;
1778 }
1779
1780 /* Set builtins.open */
1781 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1782 Py_DECREF(wrapper);
1783 goto error;
1784 }
1785 Py_DECREF(wrapper);
1786
Nick Coghland6009512014-11-20 21:39:37 +10001787 /* Set sys.stdin */
1788 fd = fileno(stdin);
1789 /* Under some conditions stdin, stdout and stderr may not be connected
1790 * and fileno() may point to an invalid file descriptor. For example
1791 * GUI apps don't have valid standard streams by default.
1792 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001793 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001794 config->stdio_encoding,
1795 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001796 if (std == NULL)
1797 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001798 PySys_SetObject("__stdin__", std);
1799 _PySys_SetObjectId(&PyId_stdin, std);
1800 Py_DECREF(std);
1801
1802 /* Set sys.stdout */
1803 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001804 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001805 config->stdio_encoding,
1806 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001807 if (std == NULL)
1808 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001809 PySys_SetObject("__stdout__", std);
1810 _PySys_SetObjectId(&PyId_stdout, std);
1811 Py_DECREF(std);
1812
1813#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1814 /* Set sys.stderr, replaces the preliminary stderr */
1815 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001816 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001817 config->stdio_encoding,
1818 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001819 if (std == NULL)
1820 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001821
1822 /* Same as hack above, pre-import stderr's codec to avoid recursion
1823 when import.c tries to write to stderr in verbose mode. */
1824 encoding_attr = PyObject_GetAttrString(std, "encoding");
1825 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001826 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001827 if (std_encoding != NULL) {
1828 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1829 Py_XDECREF(codec_info);
1830 }
1831 Py_DECREF(encoding_attr);
1832 }
1833 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1834
1835 if (PySys_SetObject("__stderr__", std) < 0) {
1836 Py_DECREF(std);
1837 goto error;
1838 }
1839 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1840 Py_DECREF(std);
1841 goto error;
1842 }
1843 Py_DECREF(std);
1844#endif
1845
Victor Stinnera7368ac2017-11-15 18:11:45 -08001846 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001847
Victor Stinnera7368ac2017-11-15 18:11:45 -08001848error:
1849 res = _Py_INIT_ERR("can't initialize sys standard streams");
1850
1851done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001852 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001853
Nick Coghland6009512014-11-20 21:39:37 +10001854 Py_XDECREF(bimod);
1855 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001856 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001857}
1858
1859
Victor Stinner10dc4842015-03-24 12:01:30 +01001860static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001861_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001862{
Victor Stinner10dc4842015-03-24 12:01:30 +01001863 fputc('\n', stderr);
1864 fflush(stderr);
1865
1866 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001867 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001868}
Victor Stinner791da1c2016-03-14 16:53:12 +01001869
1870/* Print the current exception (if an exception is set) with its traceback,
1871 or display the current Python stack.
1872
1873 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1874 called on catastrophic cases.
1875
1876 Return 1 if the traceback was displayed, 0 otherwise. */
1877
1878static int
1879_Py_FatalError_PrintExc(int fd)
1880{
1881 PyObject *ferr, *res;
1882 PyObject *exception, *v, *tb;
1883 int has_tb;
1884
Victor Stinner791da1c2016-03-14 16:53:12 +01001885 PyErr_Fetch(&exception, &v, &tb);
1886 if (exception == NULL) {
1887 /* No current exception */
1888 return 0;
1889 }
1890
1891 ferr = _PySys_GetObjectId(&PyId_stderr);
1892 if (ferr == NULL || ferr == Py_None) {
1893 /* sys.stderr is not set yet or set to None,
1894 no need to try to display the exception */
1895 return 0;
1896 }
1897
1898 PyErr_NormalizeException(&exception, &v, &tb);
1899 if (tb == NULL) {
1900 tb = Py_None;
1901 Py_INCREF(tb);
1902 }
1903 PyException_SetTraceback(v, tb);
1904 if (exception == NULL) {
1905 /* PyErr_NormalizeException() failed */
1906 return 0;
1907 }
1908
1909 has_tb = (tb != Py_None);
1910 PyErr_Display(exception, v, tb);
1911 Py_XDECREF(exception);
1912 Py_XDECREF(v);
1913 Py_XDECREF(tb);
1914
1915 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001916 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001917 if (res == NULL)
1918 PyErr_Clear();
1919 else
1920 Py_DECREF(res);
1921
1922 return has_tb;
1923}
1924
Nick Coghland6009512014-11-20 21:39:37 +10001925/* Print fatal error message and abort */
1926
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001927#ifdef MS_WINDOWS
1928static void
1929fatal_output_debug(const char *msg)
1930{
1931 /* buffer of 256 bytes allocated on the stack */
1932 WCHAR buffer[256 / sizeof(WCHAR)];
1933 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1934 size_t msglen;
1935
1936 OutputDebugStringW(L"Fatal Python error: ");
1937
1938 msglen = strlen(msg);
1939 while (msglen) {
1940 size_t i;
1941
1942 if (buflen > msglen) {
1943 buflen = msglen;
1944 }
1945
1946 /* Convert the message to wchar_t. This uses a simple one-to-one
1947 conversion, assuming that the this error message actually uses
1948 ASCII only. If this ceases to be true, we will have to convert. */
1949 for (i=0; i < buflen; ++i) {
1950 buffer[i] = msg[i];
1951 }
1952 buffer[i] = L'\0';
1953 OutputDebugStringW(buffer);
1954
1955 msg += buflen;
1956 msglen -= buflen;
1957 }
1958 OutputDebugStringW(L"\n");
1959}
1960#endif
1961
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001962static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001963fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001964{
1965 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001966 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001967
1968 if (reentrant) {
1969 /* Py_FatalError() caused a second fatal error.
1970 Example: flush_std_files() raises a recursion error. */
1971 goto exit;
1972 }
1973 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001974
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975 fprintf(stderr, "Fatal Python error: ");
1976 if (prefix) {
1977 fputs(prefix, stderr);
1978 fputs(": ", stderr);
1979 }
1980 if (msg) {
1981 fputs(msg, stderr);
1982 }
1983 else {
1984 fprintf(stderr, "<message not set>");
1985 }
1986 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001987 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001988
Victor Stinner3a228ab2018-11-01 00:26:41 +01001989 /* Check if the current thread has a Python thread state
1990 and holds the GIL */
1991 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
1992 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01001993 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01001994 if (tss_tstate != tstate) {
1995 /* The Python thread does not hold the GIL */
1996 tss_tstate = NULL;
1997 }
1998 }
1999 else {
2000 /* Py_FatalError() has been called from a C thread
2001 which has no Python thread state. */
2002 }
2003 int has_tstate_and_gil = (tss_tstate != NULL);
2004
2005 if (has_tstate_and_gil) {
2006 /* If an exception is set, print the exception with its traceback */
2007 if (!_Py_FatalError_PrintExc(fd)) {
2008 /* No exception is set, or an exception is set without traceback */
2009 _Py_FatalError_DumpTracebacks(fd);
2010 }
2011 }
2012 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002013 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002014 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002015
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002016 /* The main purpose of faulthandler is to display the traceback.
2017 This function already did its best to display a traceback.
2018 Disable faulthandler to prevent writing a second traceback
2019 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002020 _PyFaulthandler_Fini();
2021
Victor Stinner791da1c2016-03-14 16:53:12 +01002022 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002023 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002024 /* Flush sys.stdout and sys.stderr */
2025 flush_std_files();
2026 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002027
Nick Coghland6009512014-11-20 21:39:37 +10002028#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002029 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002030#endif /* MS_WINDOWS */
2031
2032exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002033 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002034#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002035 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002036#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002037 abort();
2038 }
2039 else {
2040 exit(status);
2041 }
2042}
2043
Victor Stinner19760862017-12-20 01:41:59 +01002044void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002045Py_FatalError(const char *msg)
2046{
2047 fatal_error(NULL, msg, -1);
2048}
2049
Victor Stinner19760862017-12-20 01:41:59 +01002050void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002051_Py_FatalInitError(_PyInitError err)
2052{
2053 /* On "user" error: exit with status 1.
2054 For all other errors, call abort(). */
2055 int status = err.user_err ? 1 : -1;
2056 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002057}
2058
2059/* Clean up and exit */
2060
Victor Stinnerd7292b52016-06-17 12:29:00 +02002061# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002062
Nick Coghland6009512014-11-20 21:39:37 +10002063/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002064void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002065{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002066 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002067
Antoine Pitroufc5db952017-12-13 02:29:07 +01002068 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002069 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2070
2071 is->pyexitfunc = func;
2072 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002073}
2074
2075static void
Marcel Plch776407f2017-12-20 11:17:58 +01002076call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002077{
Marcel Plch776407f2017-12-20 11:17:58 +01002078 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002079 return;
2080
Marcel Plch776407f2017-12-20 11:17:58 +01002081 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002082 PyErr_Clear();
2083}
2084
2085/* Wait until threading._shutdown completes, provided
2086 the threading module was imported in the first place.
2087 The shutdown routine will wait until all non-daemon
2088 "threading" threads have completed. */
2089static void
2090wait_for_thread_shutdown(void)
2091{
Nick Coghland6009512014-11-20 21:39:37 +10002092 _Py_IDENTIFIER(_shutdown);
2093 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002094 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002095 if (threading == NULL) {
2096 /* threading not imported */
2097 PyErr_Clear();
2098 return;
2099 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002100 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002101 if (result == NULL) {
2102 PyErr_WriteUnraisable(threading);
2103 }
2104 else {
2105 Py_DECREF(result);
2106 }
2107 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002108}
2109
2110#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002111int Py_AtExit(void (*func)(void))
2112{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002113 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002114 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002115 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002116 return 0;
2117}
2118
2119static void
2120call_ll_exitfuncs(void)
2121{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002122 while (_PyRuntime.nexitfuncs > 0)
2123 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002124
2125 fflush(stdout);
2126 fflush(stderr);
2127}
2128
Victor Stinnercfc88312018-08-01 16:41:25 +02002129void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002130Py_Exit(int sts)
2131{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002132 if (Py_FinalizeEx() < 0) {
2133 sts = 120;
2134 }
Nick Coghland6009512014-11-20 21:39:37 +10002135
2136 exit(sts);
2137}
2138
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002139static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002140initsigs(void)
2141{
2142#ifdef SIGPIPE
2143 PyOS_setsig(SIGPIPE, SIG_IGN);
2144#endif
2145#ifdef SIGXFZ
2146 PyOS_setsig(SIGXFZ, SIG_IGN);
2147#endif
2148#ifdef SIGXFSZ
2149 PyOS_setsig(SIGXFSZ, SIG_IGN);
2150#endif
2151 PyOS_InitInterrupts(); /* May imply initsignal() */
2152 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002153 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002154 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002155 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002156}
2157
2158
2159/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2160 *
2161 * All of the code in this function must only use async-signal-safe functions,
2162 * listed at `man 7 signal` or
2163 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2164 */
2165void
2166_Py_RestoreSignals(void)
2167{
2168#ifdef SIGPIPE
2169 PyOS_setsig(SIGPIPE, SIG_DFL);
2170#endif
2171#ifdef SIGXFZ
2172 PyOS_setsig(SIGXFZ, SIG_DFL);
2173#endif
2174#ifdef SIGXFSZ
2175 PyOS_setsig(SIGXFSZ, SIG_DFL);
2176#endif
2177}
2178
2179
2180/*
2181 * The file descriptor fd is considered ``interactive'' if either
2182 * a) isatty(fd) is TRUE, or
2183 * b) the -i flag was given, and the filename associated with
2184 * the descriptor is NULL or "<stdin>" or "???".
2185 */
2186int
2187Py_FdIsInteractive(FILE *fp, const char *filename)
2188{
2189 if (isatty((int)fileno(fp)))
2190 return 1;
2191 if (!Py_InteractiveFlag)
2192 return 0;
2193 return (filename == NULL) ||
2194 (strcmp(filename, "<stdin>") == 0) ||
2195 (strcmp(filename, "???") == 0);
2196}
2197
2198
Nick Coghland6009512014-11-20 21:39:37 +10002199/* Wrappers around sigaction() or signal(). */
2200
2201PyOS_sighandler_t
2202PyOS_getsig(int sig)
2203{
2204#ifdef HAVE_SIGACTION
2205 struct sigaction context;
2206 if (sigaction(sig, NULL, &context) == -1)
2207 return SIG_ERR;
2208 return context.sa_handler;
2209#else
2210 PyOS_sighandler_t handler;
2211/* Special signal handling for the secure CRT in Visual Studio 2005 */
2212#if defined(_MSC_VER) && _MSC_VER >= 1400
2213 switch (sig) {
2214 /* Only these signals are valid */
2215 case SIGINT:
2216 case SIGILL:
2217 case SIGFPE:
2218 case SIGSEGV:
2219 case SIGTERM:
2220 case SIGBREAK:
2221 case SIGABRT:
2222 break;
2223 /* Don't call signal() with other values or it will assert */
2224 default:
2225 return SIG_ERR;
2226 }
2227#endif /* _MSC_VER && _MSC_VER >= 1400 */
2228 handler = signal(sig, SIG_IGN);
2229 if (handler != SIG_ERR)
2230 signal(sig, handler);
2231 return handler;
2232#endif
2233}
2234
2235/*
2236 * All of the code in this function must only use async-signal-safe functions,
2237 * listed at `man 7 signal` or
2238 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2239 */
2240PyOS_sighandler_t
2241PyOS_setsig(int sig, PyOS_sighandler_t handler)
2242{
2243#ifdef HAVE_SIGACTION
2244 /* Some code in Modules/signalmodule.c depends on sigaction() being
2245 * used here if HAVE_SIGACTION is defined. Fix that if this code
2246 * changes to invalidate that assumption.
2247 */
2248 struct sigaction context, ocontext;
2249 context.sa_handler = handler;
2250 sigemptyset(&context.sa_mask);
2251 context.sa_flags = 0;
2252 if (sigaction(sig, &context, &ocontext) == -1)
2253 return SIG_ERR;
2254 return ocontext.sa_handler;
2255#else
2256 PyOS_sighandler_t oldhandler;
2257 oldhandler = signal(sig, handler);
2258#ifdef HAVE_SIGINTERRUPT
2259 siginterrupt(sig, 1);
2260#endif
2261 return oldhandler;
2262#endif
2263}
2264
2265#ifdef __cplusplus
2266}
2267#endif