blob: eb0fdddb4b3acf395faa103cdcacaabdd3d5e8a9 [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 Stinner34be807c2016-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 Stinner34be807c2016-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
Eric Snowef4ac962019-02-24 15:40:47 -08001462 // Mark as finalizing.
1463 if (interp->ceval.pending.lock != NULL) {
1464 PyThread_acquire_lock(interp->ceval.pending.lock, 1);
1465 }
1466 interp->finalizing = 1;
1467 if (interp->ceval.pending.lock != NULL) {
1468 PyThread_release_lock(interp->ceval.pending.lock);
1469 }
1470
1471 // Wrap up existing threads.
Nick Coghland6009512014-11-20 21:39:37 +10001472 wait_for_thread_shutdown();
1473
Eric Snowef4ac962019-02-24 15:40:47 -08001474 // Make any pending calls.
1475 if (_Py_atomic_load_relaxed(
1476 &(interp->ceval.pending.calls_to_do)))
1477 {
1478 // XXX Ensure that the interpreter is running in the current thread?
1479 if (_Py_MakePendingCalls(interp) < 0) {
1480 PyObject *exc, *val, *tb;
1481 PyErr_Fetch(&exc, &val, &tb);
1482 PyErr_BadInternalCall();
1483 _PyErr_ChainExceptions(exc, val, tb);
1484 PyErr_Print();
1485 }
1486 }
1487
Marcel Plch776407f2017-12-20 11:17:58 +01001488 call_py_exitfuncs(interp);
1489
Nick Coghland6009512014-11-20 21:39:37 +10001490 if (tstate != interp->tstate_head || tstate->next != NULL)
1491 Py_FatalError("Py_EndInterpreter: not the last thread");
1492
1493 PyImport_Cleanup();
1494 PyInterpreterState_Clear(interp);
1495 PyThreadState_Swap(NULL);
1496 PyInterpreterState_Delete(interp);
1497}
1498
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001499/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001500
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001501static _PyInitError
1502add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001503{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001504 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001505 m = PyImport_AddModule("__main__");
1506 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001507 return _Py_INIT_ERR("can't create __main__ module");
1508
Nick Coghland6009512014-11-20 21:39:37 +10001509 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001510 ann_dict = PyDict_New();
1511 if ((ann_dict == NULL) ||
1512 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001513 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001514 }
1515 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001516
Nick Coghland6009512014-11-20 21:39:37 +10001517 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1518 PyObject *bimod = PyImport_ImportModule("builtins");
1519 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001520 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001521 }
1522 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001523 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001524 }
1525 Py_DECREF(bimod);
1526 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001527
Nick Coghland6009512014-11-20 21:39:37 +10001528 /* Main is a little special - imp.is_builtin("__main__") will return
1529 * False, but BuiltinImporter is still the most appropriate initial
1530 * setting for its __loader__ attribute. A more suitable value will
1531 * be set if __main__ gets further initialized later in the startup
1532 * process.
1533 */
1534 loader = PyDict_GetItemString(d, "__loader__");
1535 if (loader == NULL || loader == Py_None) {
1536 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1537 "BuiltinImporter");
1538 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001539 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001540 }
1541 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001542 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001543 }
1544 Py_DECREF(loader);
1545 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001546 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001547}
1548
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001549static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001550initfsencoding(PyInterpreterState *interp)
1551{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001552 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001553
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001554 char *encoding = get_codec_name(config->filesystem_encoding);
1555 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001556 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001557 memory, import a module of the standard library failed, etc. */
1558 return _Py_INIT_ERR("failed to get the Python codec "
1559 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001560 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001561
1562 /* Update the filesystem encoding to the normalized Python codec name.
1563 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1564 (Python codec name). */
1565 PyMem_RawFree(config->filesystem_encoding);
1566 config->filesystem_encoding = encoding;
1567
1568 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1569 global configuration variables. */
1570 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1571 config->filesystem_errors) < 0) {
1572 return _Py_INIT_NO_MEMORY();
1573 }
1574
1575 /* PyUnicode can now use the Python codec rather than C implementation
1576 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001577 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001578 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001579}
1580
1581/* Import the site module (not into __main__ though) */
1582
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001583static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001584initsite(void)
1585{
1586 PyObject *m;
1587 m = PyImport_ImportModule("site");
1588 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001589 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001590 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001591 Py_DECREF(m);
1592 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001593}
1594
Victor Stinner874dbe82015-09-04 17:29:57 +02001595/* Check if a file descriptor is valid or not.
1596 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1597static int
1598is_valid_fd(int fd)
1599{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001600#ifdef __APPLE__
1601 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1602 and the other side of the pipe is closed, dup(1) succeed, whereas
1603 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1604 such error. */
1605 struct stat st;
1606 return (fstat(fd, &st) == 0);
1607#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001608 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001609 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001610 return 0;
1611 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001612 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1613 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1614 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001615 fd2 = dup(fd);
1616 if (fd2 >= 0)
1617 close(fd2);
1618 _Py_END_SUPPRESS_IPH
1619 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001620#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001621}
1622
1623/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001624static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001625create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001626 int fd, int write_mode, const char* name,
1627 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001628{
1629 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1630 const char* mode;
1631 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001632 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001633 int buffering, isatty;
1634 _Py_IDENTIFIER(open);
1635 _Py_IDENTIFIER(isatty);
1636 _Py_IDENTIFIER(TextIOWrapper);
1637 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001638 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001639
Victor Stinner874dbe82015-09-04 17:29:57 +02001640 if (!is_valid_fd(fd))
1641 Py_RETURN_NONE;
1642
Nick Coghland6009512014-11-20 21:39:37 +10001643 /* stdin is always opened in buffered mode, first because it shouldn't
1644 make a difference in common use cases, second because TextIOWrapper
1645 depends on the presence of a read1() method which only exists on
1646 buffered streams.
1647 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001648 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001649 buffering = 0;
1650 else
1651 buffering = -1;
1652 if (write_mode)
1653 mode = "wb";
1654 else
1655 mode = "rb";
1656 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1657 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001658 Py_None, Py_None, /* encoding, errors */
1659 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001660 if (buf == NULL)
1661 goto error;
1662
1663 if (buffering) {
1664 _Py_IDENTIFIER(raw);
1665 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1666 if (raw == NULL)
1667 goto error;
1668 }
1669 else {
1670 raw = buf;
1671 Py_INCREF(raw);
1672 }
1673
Steve Dower39294992016-08-30 21:22:36 -07001674#ifdef MS_WINDOWS
1675 /* Windows console IO is always UTF-8 encoded */
1676 if (PyWindowsConsoleIO_Check(raw))
1677 encoding = "utf-8";
1678#endif
1679
Nick Coghland6009512014-11-20 21:39:37 +10001680 text = PyUnicode_FromString(name);
1681 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1682 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001683 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001684 if (res == NULL)
1685 goto error;
1686 isatty = PyObject_IsTrue(res);
1687 Py_DECREF(res);
1688 if (isatty == -1)
1689 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001690 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001691 write_through = Py_True;
1692 else
1693 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001694 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001695 line_buffering = Py_True;
1696 else
1697 line_buffering = Py_False;
1698
1699 Py_CLEAR(raw);
1700 Py_CLEAR(text);
1701
1702#ifdef MS_WINDOWS
1703 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1704 newlines to "\n".
1705 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1706 newline = NULL;
1707#else
1708 /* sys.stdin: split lines at "\n".
1709 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1710 newline = "\n";
1711#endif
1712
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001713 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001714 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001715 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001716 Py_CLEAR(buf);
1717 if (stream == NULL)
1718 goto error;
1719
1720 if (write_mode)
1721 mode = "w";
1722 else
1723 mode = "r";
1724 text = PyUnicode_FromString(mode);
1725 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1726 goto error;
1727 Py_CLEAR(text);
1728 return stream;
1729
1730error:
1731 Py_XDECREF(buf);
1732 Py_XDECREF(stream);
1733 Py_XDECREF(text);
1734 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001735
Victor Stinner874dbe82015-09-04 17:29:57 +02001736 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1737 /* Issue #24891: the file descriptor was closed after the first
1738 is_valid_fd() check was called. Ignore the OSError and set the
1739 stream to None. */
1740 PyErr_Clear();
1741 Py_RETURN_NONE;
1742 }
1743 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001744}
1745
1746/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001747static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001748init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001749{
1750 PyObject *iomod = NULL, *wrapper;
1751 PyObject *bimod = NULL;
1752 PyObject *m;
1753 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001754 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001755 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001756 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001757 _PyCoreConfig *config = &interp->core_config;
1758
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001759 /* Check that stdin is not a directory
1760 Using shell redirection, you can redirect stdin to a directory,
1761 crashing the Python interpreter. Catch this common mistake here
1762 and output a useful error message. Note that under MS Windows,
1763 the shell already prevents that. */
1764#ifndef MS_WINDOWS
1765 struct _Py_stat_struct sb;
1766 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1767 S_ISDIR(sb.st_mode)) {
1768 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1769 "cannot continue");
1770 }
1771#endif
1772
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001773 char *codec_name = get_codec_name(config->stdio_encoding);
1774 if (codec_name == NULL) {
1775 return _Py_INIT_ERR("failed to get the Python codec name "
1776 "of the stdio encoding");
1777 }
1778 PyMem_RawFree(config->stdio_encoding);
1779 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001780
1781 /* Hack to avoid a nasty recursion issue when Python is invoked
1782 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1783 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1784 goto error;
1785 }
1786 Py_DECREF(m);
1787
1788 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1789 goto error;
1790 }
1791 Py_DECREF(m);
1792
1793 if (!(bimod = PyImport_ImportModule("builtins"))) {
1794 goto error;
1795 }
1796
1797 if (!(iomod = PyImport_ImportModule("io"))) {
1798 goto error;
1799 }
1800 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1801 goto error;
1802 }
1803
1804 /* Set builtins.open */
1805 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1806 Py_DECREF(wrapper);
1807 goto error;
1808 }
1809 Py_DECREF(wrapper);
1810
Nick Coghland6009512014-11-20 21:39:37 +10001811 /* Set sys.stdin */
1812 fd = fileno(stdin);
1813 /* Under some conditions stdin, stdout and stderr may not be connected
1814 * and fileno() may point to an invalid file descriptor. For example
1815 * GUI apps don't have valid standard streams by default.
1816 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001817 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001818 config->stdio_encoding,
1819 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001820 if (std == NULL)
1821 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001822 PySys_SetObject("__stdin__", std);
1823 _PySys_SetObjectId(&PyId_stdin, std);
1824 Py_DECREF(std);
1825
1826 /* Set sys.stdout */
1827 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001828 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001829 config->stdio_encoding,
1830 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001831 if (std == NULL)
1832 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001833 PySys_SetObject("__stdout__", std);
1834 _PySys_SetObjectId(&PyId_stdout, std);
1835 Py_DECREF(std);
1836
1837#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1838 /* Set sys.stderr, replaces the preliminary stderr */
1839 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001840 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001841 config->stdio_encoding,
1842 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001843 if (std == NULL)
1844 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001845
1846 /* Same as hack above, pre-import stderr's codec to avoid recursion
1847 when import.c tries to write to stderr in verbose mode. */
1848 encoding_attr = PyObject_GetAttrString(std, "encoding");
1849 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001850 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001851 if (std_encoding != NULL) {
1852 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1853 Py_XDECREF(codec_info);
1854 }
1855 Py_DECREF(encoding_attr);
1856 }
1857 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1858
1859 if (PySys_SetObject("__stderr__", std) < 0) {
1860 Py_DECREF(std);
1861 goto error;
1862 }
1863 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1864 Py_DECREF(std);
1865 goto error;
1866 }
1867 Py_DECREF(std);
1868#endif
1869
Victor Stinnera7368ac2017-11-15 18:11:45 -08001870 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001871
Victor Stinnera7368ac2017-11-15 18:11:45 -08001872error:
1873 res = _Py_INIT_ERR("can't initialize sys standard streams");
1874
1875done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001876 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001877
Nick Coghland6009512014-11-20 21:39:37 +10001878 Py_XDECREF(bimod);
1879 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001880 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001881}
1882
1883
Victor Stinner10dc4842015-03-24 12:01:30 +01001884static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001885_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001886{
Victor Stinner10dc4842015-03-24 12:01:30 +01001887 fputc('\n', stderr);
1888 fflush(stderr);
1889
1890 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001891 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001892}
Victor Stinner791da1c2016-03-14 16:53:12 +01001893
1894/* Print the current exception (if an exception is set) with its traceback,
1895 or display the current Python stack.
1896
1897 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1898 called on catastrophic cases.
1899
1900 Return 1 if the traceback was displayed, 0 otherwise. */
1901
1902static int
1903_Py_FatalError_PrintExc(int fd)
1904{
1905 PyObject *ferr, *res;
1906 PyObject *exception, *v, *tb;
1907 int has_tb;
1908
Victor Stinner791da1c2016-03-14 16:53:12 +01001909 PyErr_Fetch(&exception, &v, &tb);
1910 if (exception == NULL) {
1911 /* No current exception */
1912 return 0;
1913 }
1914
1915 ferr = _PySys_GetObjectId(&PyId_stderr);
1916 if (ferr == NULL || ferr == Py_None) {
1917 /* sys.stderr is not set yet or set to None,
1918 no need to try to display the exception */
1919 return 0;
1920 }
1921
1922 PyErr_NormalizeException(&exception, &v, &tb);
1923 if (tb == NULL) {
1924 tb = Py_None;
1925 Py_INCREF(tb);
1926 }
1927 PyException_SetTraceback(v, tb);
1928 if (exception == NULL) {
1929 /* PyErr_NormalizeException() failed */
1930 return 0;
1931 }
1932
1933 has_tb = (tb != Py_None);
1934 PyErr_Display(exception, v, tb);
1935 Py_XDECREF(exception);
1936 Py_XDECREF(v);
1937 Py_XDECREF(tb);
1938
1939 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001940 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001941 if (res == NULL)
1942 PyErr_Clear();
1943 else
1944 Py_DECREF(res);
1945
1946 return has_tb;
1947}
1948
Nick Coghland6009512014-11-20 21:39:37 +10001949/* Print fatal error message and abort */
1950
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001951#ifdef MS_WINDOWS
1952static void
1953fatal_output_debug(const char *msg)
1954{
1955 /* buffer of 256 bytes allocated on the stack */
1956 WCHAR buffer[256 / sizeof(WCHAR)];
1957 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1958 size_t msglen;
1959
1960 OutputDebugStringW(L"Fatal Python error: ");
1961
1962 msglen = strlen(msg);
1963 while (msglen) {
1964 size_t i;
1965
1966 if (buflen > msglen) {
1967 buflen = msglen;
1968 }
1969
1970 /* Convert the message to wchar_t. This uses a simple one-to-one
1971 conversion, assuming that the this error message actually uses
1972 ASCII only. If this ceases to be true, we will have to convert. */
1973 for (i=0; i < buflen; ++i) {
1974 buffer[i] = msg[i];
1975 }
1976 buffer[i] = L'\0';
1977 OutputDebugStringW(buffer);
1978
1979 msg += buflen;
1980 msglen -= buflen;
1981 }
1982 OutputDebugStringW(L"\n");
1983}
1984#endif
1985
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001986static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001987fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001988{
1989 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001990 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001991
1992 if (reentrant) {
1993 /* Py_FatalError() caused a second fatal error.
1994 Example: flush_std_files() raises a recursion error. */
1995 goto exit;
1996 }
1997 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001998
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001999 fprintf(stderr, "Fatal Python error: ");
2000 if (prefix) {
2001 fputs(prefix, stderr);
2002 fputs(": ", stderr);
2003 }
2004 if (msg) {
2005 fputs(msg, stderr);
2006 }
2007 else {
2008 fprintf(stderr, "<message not set>");
2009 }
2010 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002011 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002012
Victor Stinner3a228ab2018-11-01 00:26:41 +01002013 /* Check if the current thread has a Python thread state
2014 and holds the GIL */
2015 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2016 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002017 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002018 if (tss_tstate != tstate) {
2019 /* The Python thread does not hold the GIL */
2020 tss_tstate = NULL;
2021 }
2022 }
2023 else {
2024 /* Py_FatalError() has been called from a C thread
2025 which has no Python thread state. */
2026 }
2027 int has_tstate_and_gil = (tss_tstate != NULL);
2028
2029 if (has_tstate_and_gil) {
2030 /* If an exception is set, print the exception with its traceback */
2031 if (!_Py_FatalError_PrintExc(fd)) {
2032 /* No exception is set, or an exception is set without traceback */
2033 _Py_FatalError_DumpTracebacks(fd);
2034 }
2035 }
2036 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002037 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002038 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002039
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002040 /* The main purpose of faulthandler is to display the traceback.
2041 This function already did its best to display a traceback.
2042 Disable faulthandler to prevent writing a second traceback
2043 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002044 _PyFaulthandler_Fini();
2045
Victor Stinner791da1c2016-03-14 16:53:12 +01002046 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002047 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002048 /* Flush sys.stdout and sys.stderr */
2049 flush_std_files();
2050 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002051
Nick Coghland6009512014-11-20 21:39:37 +10002052#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002053 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002054#endif /* MS_WINDOWS */
2055
2056exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002057 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002058#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002059 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002060#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002061 abort();
2062 }
2063 else {
2064 exit(status);
2065 }
2066}
2067
Victor Stinner19760862017-12-20 01:41:59 +01002068void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002069Py_FatalError(const char *msg)
2070{
2071 fatal_error(NULL, msg, -1);
2072}
2073
Victor Stinner19760862017-12-20 01:41:59 +01002074void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002075_Py_FatalInitError(_PyInitError err)
2076{
2077 /* On "user" error: exit with status 1.
2078 For all other errors, call abort(). */
2079 int status = err.user_err ? 1 : -1;
2080 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002081}
2082
2083/* Clean up and exit */
2084
Victor Stinnerd7292b52016-06-17 12:29:00 +02002085# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002086
Nick Coghland6009512014-11-20 21:39:37 +10002087/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002088void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002089{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002090 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002091
Antoine Pitroufc5db952017-12-13 02:29:07 +01002092 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002093 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2094
2095 is->pyexitfunc = func;
2096 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002097}
2098
2099static void
Marcel Plch776407f2017-12-20 11:17:58 +01002100call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002101{
Marcel Plch776407f2017-12-20 11:17:58 +01002102 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002103 return;
2104
Marcel Plch776407f2017-12-20 11:17:58 +01002105 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002106 PyErr_Clear();
2107}
2108
2109/* Wait until threading._shutdown completes, provided
2110 the threading module was imported in the first place.
2111 The shutdown routine will wait until all non-daemon
2112 "threading" threads have completed. */
2113static void
2114wait_for_thread_shutdown(void)
2115{
Nick Coghland6009512014-11-20 21:39:37 +10002116 _Py_IDENTIFIER(_shutdown);
2117 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002118 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002119 if (threading == NULL) {
2120 /* threading not imported */
2121 PyErr_Clear();
2122 return;
2123 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002124 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002125 if (result == NULL) {
2126 PyErr_WriteUnraisable(threading);
2127 }
2128 else {
2129 Py_DECREF(result);
2130 }
2131 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002132}
2133
2134#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002135int Py_AtExit(void (*func)(void))
2136{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002137 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002138 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002139 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002140 return 0;
2141}
2142
2143static void
2144call_ll_exitfuncs(void)
2145{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002146 while (_PyRuntime.nexitfuncs > 0)
2147 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002148
2149 fflush(stdout);
2150 fflush(stderr);
2151}
2152
Victor Stinnercfc88312018-08-01 16:41:25 +02002153void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002154Py_Exit(int sts)
2155{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002156 if (Py_FinalizeEx() < 0) {
2157 sts = 120;
2158 }
Nick Coghland6009512014-11-20 21:39:37 +10002159
2160 exit(sts);
2161}
2162
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002163static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002164initsigs(void)
2165{
2166#ifdef SIGPIPE
2167 PyOS_setsig(SIGPIPE, SIG_IGN);
2168#endif
2169#ifdef SIGXFZ
2170 PyOS_setsig(SIGXFZ, SIG_IGN);
2171#endif
2172#ifdef SIGXFSZ
2173 PyOS_setsig(SIGXFSZ, SIG_IGN);
2174#endif
2175 PyOS_InitInterrupts(); /* May imply initsignal() */
2176 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002177 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002178 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002179 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002180}
2181
2182
2183/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2184 *
2185 * All of the code in this function must only use async-signal-safe functions,
2186 * listed at `man 7 signal` or
2187 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2188 */
2189void
2190_Py_RestoreSignals(void)
2191{
2192#ifdef SIGPIPE
2193 PyOS_setsig(SIGPIPE, SIG_DFL);
2194#endif
2195#ifdef SIGXFZ
2196 PyOS_setsig(SIGXFZ, SIG_DFL);
2197#endif
2198#ifdef SIGXFSZ
2199 PyOS_setsig(SIGXFSZ, SIG_DFL);
2200#endif
2201}
2202
2203
2204/*
2205 * The file descriptor fd is considered ``interactive'' if either
2206 * a) isatty(fd) is TRUE, or
2207 * b) the -i flag was given, and the filename associated with
2208 * the descriptor is NULL or "<stdin>" or "???".
2209 */
2210int
2211Py_FdIsInteractive(FILE *fp, const char *filename)
2212{
2213 if (isatty((int)fileno(fp)))
2214 return 1;
2215 if (!Py_InteractiveFlag)
2216 return 0;
2217 return (filename == NULL) ||
2218 (strcmp(filename, "<stdin>") == 0) ||
2219 (strcmp(filename, "???") == 0);
2220}
2221
2222
Nick Coghland6009512014-11-20 21:39:37 +10002223/* Wrappers around sigaction() or signal(). */
2224
2225PyOS_sighandler_t
2226PyOS_getsig(int sig)
2227{
2228#ifdef HAVE_SIGACTION
2229 struct sigaction context;
2230 if (sigaction(sig, NULL, &context) == -1)
2231 return SIG_ERR;
2232 return context.sa_handler;
2233#else
2234 PyOS_sighandler_t handler;
2235/* Special signal handling for the secure CRT in Visual Studio 2005 */
2236#if defined(_MSC_VER) && _MSC_VER >= 1400
2237 switch (sig) {
2238 /* Only these signals are valid */
2239 case SIGINT:
2240 case SIGILL:
2241 case SIGFPE:
2242 case SIGSEGV:
2243 case SIGTERM:
2244 case SIGBREAK:
2245 case SIGABRT:
2246 break;
2247 /* Don't call signal() with other values or it will assert */
2248 default:
2249 return SIG_ERR;
2250 }
2251#endif /* _MSC_VER && _MSC_VER >= 1400 */
2252 handler = signal(sig, SIG_IGN);
2253 if (handler != SIG_ERR)
2254 signal(sig, handler);
2255 return handler;
2256#endif
2257}
2258
2259/*
2260 * All of the code in this function must only use async-signal-safe functions,
2261 * listed at `man 7 signal` or
2262 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2263 */
2264PyOS_sighandler_t
2265PyOS_setsig(int sig, PyOS_sighandler_t handler)
2266{
2267#ifdef HAVE_SIGACTION
2268 /* Some code in Modules/signalmodule.c depends on sigaction() being
2269 * used here if HAVE_SIGACTION is defined. Fix that if this code
2270 * changes to invalidate that assumption.
2271 */
2272 struct sigaction context, ocontext;
2273 context.sa_handler = handler;
2274 sigemptyset(&context.sa_mask);
2275 context.sa_flags = 0;
2276 if (sigaction(sig, &context, &ocontext) == -1)
2277 return SIG_ERR;
2278 return ocontext.sa_handler;
2279#else
2280 PyOS_sighandler_t oldhandler;
2281 oldhandler = signal(sig, handler);
2282#ifdef HAVE_SIGINTERRUPT
2283 siginterrupt(sig, 1);
2284#endif
2285 return oldhandler;
2286#endif
2287}
2288
2289#ifdef __cplusplus
2290}
2291#endif