blob: af3d5ef055faec849dacfcef220ee5646e5f52fa [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"
8#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +01009#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010010#include "pycore_pylifecycle.h"
11#include "pycore_pymem.h"
12#include "pycore_pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100013#include "grammar.h"
14#include "node.h"
15#include "token.h"
16#include "parsetok.h"
17#include "errcode.h"
18#include "code.h"
19#include "symtable.h"
20#include "ast.h"
21#include "marshal.h"
22#include "osdefs.h"
23#include <locale.h>
24
25#ifdef HAVE_SIGNAL_H
26#include <signal.h>
27#endif
28
29#ifdef MS_WINDOWS
30#include "malloc.h" /* for alloca */
31#endif
32
33#ifdef HAVE_LANGINFO_H
34#include <langinfo.h>
35#endif
36
37#ifdef MS_WINDOWS
38#undef BYTE
39#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070040
41extern PyTypeObject PyWindowsConsoleIO_Type;
42#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100043#endif
44
45_Py_IDENTIFIER(flush);
46_Py_IDENTIFIER(name);
47_Py_IDENTIFIER(stdin);
48_Py_IDENTIFIER(stdout);
49_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060050_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100051
52#ifdef __cplusplus
53extern "C" {
54#endif
55
Nick Coghland6009512014-11-20 21:39:37 +100056extern grammar _PyParser_Grammar; /* From graminit.c */
57
58/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080059static _PyInitError add_main_module(PyInterpreterState *interp);
60static _PyInitError initfsencoding(PyInterpreterState *interp);
61static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010062static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080063static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010064static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100065static void wait_for_thread_shutdown(void);
66static void call_ll_exitfuncs(void);
Nick Coghland6009512014-11-20 21:39:37 +100067
Victor Stinnerf7e5b562017-11-15 15:48:08 -080068_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060069
Victor Stinnerf7e5b562017-11-15 15:48:08 -080070_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060071_PyRuntime_Initialize(void)
72{
73 /* XXX We only initialize once in the process, which aligns with
74 the static initialization of the former globals now found in
75 _PyRuntime. However, _PyRuntime *should* be initialized with
76 every Py_Initialize() call, but doing so breaks the runtime.
77 This is because the runtime state is not properly finalized
78 currently. */
79 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080 if (initialized) {
81 return _Py_INIT_OK();
82 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084
85 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086}
87
88void
89_PyRuntime_Finalize(void)
90{
91 _PyRuntimeState_Fini(&_PyRuntime);
92}
93
94int
95_Py_IsFinalizing(void)
96{
97 return _PyRuntime.finalizing != NULL;
98}
99
Nick Coghland6009512014-11-20 21:39:37 +1000100/* Hack to force loading of object files */
101int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
102 PyOS_mystrnicmp; /* Python/pystrcmp.o */
103
104/* PyModule_GetWarningsModule is no longer necessary as of 2.6
105since _warnings is builtin. This API should not be used. */
106PyObject *
107PyModule_GetWarningsModule(void)
108{
109 return PyImport_ImportModule("warnings");
110}
111
Eric Snowc7ec9982017-05-23 23:00:52 -0700112
Eric Snow1abcf672017-05-23 21:46:51 -0700113/* APIs to access the initialization flags
114 *
115 * Can be called prior to Py_Initialize.
116 */
Nick Coghland6009512014-11-20 21:39:37 +1000117
Eric Snow1abcf672017-05-23 21:46:51 -0700118int
119_Py_IsCoreInitialized(void)
120{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600121 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700122}
Nick Coghland6009512014-11-20 21:39:37 +1000123
124int
125Py_IsInitialized(void)
126{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600127 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000128}
129
Nick Coghlan6ea41862017-06-11 13:16:15 +1000130
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000131/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
132 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000133 initializations fail, a fatal error is issued and the function does
134 not return. On return, the first thread and interpreter state have
135 been created.
136
137 Locking: you must hold the interpreter lock while calling this.
138 (If the lock has not yet been initialized, that's equivalent to
139 having the lock, but you cannot use multiple threads.)
140
141*/
142
Nick Coghland6009512014-11-20 21:39:37 +1000143static char*
144get_codec_name(const char *encoding)
145{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200146 const char *name_utf8;
147 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000148 PyObject *codec, *name = NULL;
149
150 codec = _PyCodec_Lookup(encoding);
151 if (!codec)
152 goto error;
153
154 name = _PyObject_GetAttrId(codec, &PyId_name);
155 Py_CLEAR(codec);
156 if (!name)
157 goto error;
158
Serhiy Storchaka06515832016-11-20 09:13:07 +0200159 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000160 if (name_utf8 == NULL)
161 goto error;
162 name_str = _PyMem_RawStrdup(name_utf8);
163 Py_DECREF(name);
164 if (name_str == NULL) {
165 PyErr_NoMemory();
166 return NULL;
167 }
168 return name_str;
169
170error:
171 Py_XDECREF(codec);
172 Py_XDECREF(name);
173 return NULL;
174}
175
Nick Coghland6009512014-11-20 21:39:37 +1000176
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800177static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700178initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000179{
180 PyObject *importlib;
181 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000182 PyObject *value;
183
184 /* Import _importlib through its frozen version, _frozen_importlib. */
185 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800186 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000187 }
188 else if (Py_VerboseFlag) {
189 PySys_FormatStderr("import _frozen_importlib # frozen\n");
190 }
191 importlib = PyImport_AddModule("_frozen_importlib");
192 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800193 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000194 }
195 interp->importlib = importlib;
196 Py_INCREF(interp->importlib);
197
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300198 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
199 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800200 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300201 Py_INCREF(interp->import_func);
202
Victor Stinnercd6e6942015-09-18 09:11:57 +0200203 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800204 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000205 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800206 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000207 }
208 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200209 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000210 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600211 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800212 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000213 }
214
Victor Stinnercd6e6942015-09-18 09:11:57 +0200215 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000216 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
217 if (value == NULL) {
218 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800219 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000220 }
221 Py_DECREF(value);
222 Py_DECREF(impmod);
223
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800224 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000225}
226
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800227static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700228initexternalimport(PyInterpreterState *interp)
229{
230 PyObject *value;
231 value = PyObject_CallMethod(interp->importlib,
232 "_install_external_importers", "");
233 if (value == NULL) {
234 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800235 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700236 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200237 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300238 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700239}
Nick Coghland6009512014-11-20 21:39:37 +1000240
Nick Coghlan6ea41862017-06-11 13:16:15 +1000241/* Helper functions to better handle the legacy C locale
242 *
243 * The legacy C locale assumes ASCII as the default text encoding, which
244 * causes problems not only for the CPython runtime, but also other
245 * components like GNU readline.
246 *
247 * Accordingly, when the CLI detects it, it attempts to coerce it to a
248 * more capable UTF-8 based alternative as follows:
249 *
250 * if (_Py_LegacyLocaleDetected()) {
251 * _Py_CoerceLegacyLocale();
252 * }
253 *
254 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
255 *
256 * Locale coercion also impacts the default error handler for the standard
257 * streams: while the usual default is "strict", the default for the legacy
258 * C locale and for any of the coercion target locales is "surrogateescape".
259 */
260
261int
262_Py_LegacyLocaleDetected(void)
263{
264#ifndef MS_WINDOWS
265 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000266 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
267 * the POSIX locale as a simple alias for the C locale, so
268 * we may also want to check for that explicitly.
269 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000270 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
271 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
272#else
273 /* Windows uses code pages instead of locales, so no locale is legacy */
274 return 0;
275#endif
276}
277
Nick Coghlaneb817952017-06-18 12:29:42 +1000278static const char *_C_LOCALE_WARNING =
279 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
280 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
281 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
282 "locales is recommended.\n";
283
Nick Coghlaneb817952017-06-18 12:29:42 +1000284static void
Victor Stinner94540602017-12-16 04:54:22 +0100285_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000286{
Victor Stinner06e76082018-09-19 14:56:36 -0700287 if (core_config->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200288 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000289 }
290}
291
Nick Coghlan6ea41862017-06-11 13:16:15 +1000292typedef struct _CandidateLocale {
293 const char *locale_name; /* The locale to try as a coercion target */
294} _LocaleCoercionTarget;
295
296static _LocaleCoercionTarget _TARGET_LOCALES[] = {
297 {"C.UTF-8"},
298 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000299 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300 {NULL}
301};
302
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200303
304int
305_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000306{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200307 const _LocaleCoercionTarget *target = NULL;
308 for (target = _TARGET_LOCALES; target->locale_name; target++) {
309 if (strcmp(ctype_loc, target->locale_name) == 0) {
310 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000311 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200312 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200313 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000314}
315
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200316
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100318static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000319 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
320 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
321
322static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200323_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000324{
325 const char *newloc = target->locale_name;
326
327 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100328 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000329
330 /* Set the relevant locale environment variable */
331 if (setenv("LC_CTYPE", newloc, 1)) {
332 fprintf(stderr,
333 "Error setting LC_CTYPE, skipping C locale coercion\n");
334 return;
335 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200336 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100337 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000338 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000339
340 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100341 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000342}
343#endif
344
345void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200346_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000347{
348#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200349 char *oldloc = NULL;
350
351 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
352 if (oldloc == NULL) {
353 return;
354 }
355
Victor Stinner94540602017-12-16 04:54:22 +0100356 const char *locale_override = getenv("LC_ALL");
357 if (locale_override == NULL || *locale_override == '\0') {
358 /* LC_ALL is also not set (or is set to an empty string) */
359 const _LocaleCoercionTarget *target = NULL;
360 for (target = _TARGET_LOCALES; target->locale_name; target++) {
361 const char *new_locale = setlocale(LC_CTYPE,
362 target->locale_name);
363 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100364#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100365defined(HAVE_LANGINFO_H) && defined(CODESET)
366 /* Also ensure that nl_langinfo works in this locale */
367 char *codeset = nl_langinfo(CODESET);
368 if (!codeset || *codeset == '\0') {
369 /* CODESET is not set or empty, so skip coercion */
370 new_locale = NULL;
371 _Py_SetLocaleFromEnv(LC_CTYPE);
372 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000373 }
Victor Stinner94540602017-12-16 04:54:22 +0100374#endif
375 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200376 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200377 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000378 }
379 }
380 }
381 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200382
383 setlocale(LC_CTYPE, oldloc);
384
385done:
386 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000387#endif
388}
389
xdegaye1588be62017-11-12 12:45:59 +0100390/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
391 * isolate the idiosyncrasies of different libc implementations. It reads the
392 * appropriate environment variable and uses its value to select the locale for
393 * 'category'. */
394char *
395_Py_SetLocaleFromEnv(int category)
396{
397#ifdef __ANDROID__
398 const char *locale;
399 const char **pvar;
400#ifdef PY_COERCE_C_LOCALE
401 const char *coerce_c_locale;
402#endif
403 const char *utf8_locale = "C.UTF-8";
404 const char *env_var_set[] = {
405 "LC_ALL",
406 "LC_CTYPE",
407 "LANG",
408 NULL,
409 };
410
411 /* Android setlocale(category, "") doesn't check the environment variables
412 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
413 * check the environment variables listed in env_var_set. */
414 for (pvar=env_var_set; *pvar; pvar++) {
415 locale = getenv(*pvar);
416 if (locale != NULL && *locale != '\0') {
417 if (strcmp(locale, utf8_locale) == 0 ||
418 strcmp(locale, "en_US.UTF-8") == 0) {
419 return setlocale(category, utf8_locale);
420 }
421 return setlocale(category, "C");
422 }
423 }
424
425 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
426 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
427 * Quote from POSIX section "8.2 Internationalization Variables":
428 * "4. If the LANG environment variable is not set or is set to the empty
429 * string, the implementation-defined default locale shall be used." */
430
431#ifdef PY_COERCE_C_LOCALE
432 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
433 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
434 /* Some other ported code may check the environment variables (e.g. in
435 * extension modules), so we make sure that they match the locale
436 * configuration */
437 if (setenv("LC_CTYPE", utf8_locale, 1)) {
438 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
439 "environment variable to %s\n", utf8_locale);
440 }
441 }
442#endif
443 return setlocale(category, utf8_locale);
444#else /* __ANDROID__ */
445 return setlocale(category, "");
446#endif /* __ANDROID__ */
447}
448
Nick Coghlan6ea41862017-06-11 13:16:15 +1000449
Eric Snow1abcf672017-05-23 21:46:51 -0700450/* Global initializations. Can be undone by Py_Finalize(). Don't
451 call this twice without an intervening Py_Finalize() call.
452
Victor Stinner1dc6e392018-07-25 02:49:17 +0200453 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700454 must have a corresponding call to Py_Finalize.
455
456 Locking: you must hold the interpreter lock while calling these APIs.
457 (If the lock has not yet been initialized, that's equivalent to
458 having the lock, but you cannot use multiple threads.)
459
460*/
461
Victor Stinner1dc6e392018-07-25 02:49:17 +0200462static _PyInitError
463_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
464 const _PyCoreConfig *core_config)
465{
466 if (core_config->allocator != NULL) {
467 const char *allocator = _PyMem_GetAllocatorsName();
468 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
469 return _Py_INIT_USER_ERR("cannot modify memory allocator "
470 "after first Py_Initialize()");
471 }
472 }
473
474 _PyCoreConfig_SetGlobalConfig(core_config);
475
476 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
477 return _Py_INIT_ERR("failed to copy core config");
478 }
479 core_config = &interp->core_config;
480
481 if (core_config->_install_importlib) {
482 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
483 if (_Py_INIT_FAILED(err)) {
484 return err;
485 }
486 }
487 return _Py_INIT_OK();
488}
489
490
Eric Snow1abcf672017-05-23 21:46:51 -0700491/* Begin interpreter initialization
492 *
493 * On return, the first thread and interpreter state have been created,
494 * but the compiler, signal handling, multithreading and
495 * multiple interpreter support, and codec infrastructure are not yet
496 * available.
497 *
498 * The import system will support builtin and frozen modules only.
499 * The only supported io is writing to sys.stderr
500 *
501 * If any operation invoked by this function fails, a fatal error is
502 * issued and the function does not return.
503 *
504 * Any code invoked from this function should *not* assume it has access
505 * to the Python C API (unless the API is explicitly listed as being
506 * safe to call without calling Py_Initialize first)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200507 *
508 * The caller is responsible to call _PyCoreConfig_Read().
Eric Snow1abcf672017-05-23 21:46:51 -0700509 */
510
Victor Stinner1dc6e392018-07-25 02:49:17 +0200511static _PyInitError
512_Py_InitializeCore_impl(PyInterpreterState **interp_p,
513 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000514{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200515 PyInterpreterState *interp;
516 _PyInitError err;
517
518 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
519 Py_Initialize() ignores the new configuration. */
520 if (_PyRuntime.core_initialized) {
Victor Stinner50b48572018-11-01 01:51:40 +0100521 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200522 if (!tstate) {
523 return _Py_INIT_ERR("failed to read thread state");
524 }
525
526 interp = tstate->interp;
527 if (interp == NULL) {
528 return _Py_INIT_ERR("can't make main interpreter");
529 }
530 *interp_p = interp;
531
532 return _Py_Initialize_ReconfigureCore(interp, core_config);
533 }
534
535 if (_PyRuntime.initialized) {
536 return _Py_INIT_ERR("main interpreter already initialized");
537 }
Victor Stinnerda273412017-12-15 01:46:02 +0100538
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200539 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000540
Victor Stinner1dc6e392018-07-25 02:49:17 +0200541 err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800542 if (_Py_INIT_FAILED(err)) {
543 return err;
544 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600545
Victor Stinner31e99082017-12-20 23:41:38 +0100546 if (core_config->allocator != NULL) {
547 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
548 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
549 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800550 }
551
Eric Snow1abcf672017-05-23 21:46:51 -0700552 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
553 * threads behave a little more gracefully at interpreter shutdown.
554 * We clobber it here so the new interpreter can start with a clean
555 * slate.
556 *
557 * However, this may still lead to misbehaviour if there are daemon
558 * threads still hanging around from a previous Py_Initialize/Finalize
559 * pair :(
560 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600561 _PyRuntime.finalizing = NULL;
562
Victor Stinnerda273412017-12-15 01:46:02 +0100563 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800564 if (_Py_INIT_FAILED(err)) {
565 return err;
566 }
567
Victor Stinnera7368ac2017-11-15 18:11:45 -0800568 err = _PyInterpreterState_Enable(&_PyRuntime);
569 if (_Py_INIT_FAILED(err)) {
570 return err;
571 }
572
Victor Stinner1dc6e392018-07-25 02:49:17 +0200573 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100574 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800575 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100576 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200577 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100578
579 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
580 return _Py_INIT_ERR("failed to copy core config");
581 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200582 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000583
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200584 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000585 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800586 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000587 (void) PyThreadState_Swap(tstate);
588
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000589 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000590 destroying the GIL might fail when it is being referenced from
591 another running thread (see issue #9901).
592 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000593 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000594 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100595
Nick Coghland6009512014-11-20 21:39:37 +1000596 /* Auto-thread-state API */
597 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000598
Victor Stinner2914bb32018-01-29 11:57:45 +0100599 /* Create the GIL */
600 PyEval_InitThreads();
601
Nick Coghland6009512014-11-20 21:39:37 +1000602 _Py_ReadyTypes();
603
Nick Coghland6009512014-11-20 21:39:37 +1000604 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800605 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000606
607 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800608 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000609
610 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800611 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000612
Eric Snowd393c1b2017-09-14 12:18:12 -0600613 PyObject *modules = PyDict_New();
614 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800615 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600616 interp->modules = modules;
617
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200618 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800619 err = _PySys_BeginInit(&sysmod);
620 if (_Py_INIT_FAILED(err)) {
621 return err;
622 }
623
Eric Snowd393c1b2017-09-14 12:18:12 -0600624 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800625 if (interp->sysdict == NULL) {
626 return _Py_INIT_ERR("can't initialize sys dict");
627 }
628
Eric Snowd393c1b2017-09-14 12:18:12 -0600629 Py_INCREF(interp->sysdict);
630 PyDict_SetItemString(interp->sysdict, "modules", modules);
631 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000632
633 /* Init Unicode implementation; relies on the codec registry */
634 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800635 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700636
Nick Coghland6009512014-11-20 21:39:37 +1000637 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800638 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000639
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200640 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000641 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800642 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600643 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000644 interp->builtins = PyModule_GetDict(bimod);
645 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800646 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000647 Py_INCREF(interp->builtins);
648
649 /* initialize builtin exceptions */
650 _PyExc_Init(bimod);
651
Nick Coghland6009512014-11-20 21:39:37 +1000652 /* Set up a preliminary stderr printer until we have enough
653 infrastructure for the io module in place. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200654 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000655 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800656 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000657 _PySys_SetObjectId(&PyId_stderr, pstderr);
658 PySys_SetObject("__stderr__", pstderr);
659 Py_DECREF(pstderr);
660
Victor Stinner672b6ba2017-12-06 17:25:50 +0100661 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800662 if (_Py_INIT_FAILED(err)) {
663 return err;
664 }
Nick Coghland6009512014-11-20 21:39:37 +1000665
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800666 err = _PyImportHooks_Init();
667 if (_Py_INIT_FAILED(err)) {
668 return err;
669 }
Nick Coghland6009512014-11-20 21:39:37 +1000670
671 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100672 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100673 return _Py_INIT_ERR("can't initialize warnings");
674 }
Nick Coghland6009512014-11-20 21:39:37 +1000675
Yury Selivanovf23746a2018-01-22 19:11:18 -0500676 if (!_PyContext_Init())
677 return _Py_INIT_ERR("can't init context");
678
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200679 if (core_config->_install_importlib) {
Victor Stinnerb1147e42018-07-21 02:06:16 +0200680 err = _PyCoreConfig_SetPathConfig(core_config);
681 if (_Py_INIT_FAILED(err)) {
682 return err;
683 }
684 }
685
Eric Snow1abcf672017-05-23 21:46:51 -0700686 /* This call sets up builtin and frozen import support */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200687 if (core_config->_install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800688 err = initimport(interp, sysmod);
689 if (_Py_INIT_FAILED(err)) {
690 return err;
691 }
Eric Snow1abcf672017-05-23 21:46:51 -0700692 }
693
694 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600695 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800696 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700697}
698
Victor Stinner1dc6e392018-07-25 02:49:17 +0200699_PyInitError
700_Py_InitializeCore(PyInterpreterState **interp_p,
701 const _PyCoreConfig *src_config)
702{
703 assert(src_config != NULL);
704
Victor Stinner1dc6e392018-07-25 02:49:17 +0200705 PyMemAllocatorEx old_alloc;
706 _PyInitError err;
707
708 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
709 (and the input configuration is read only). */
710 _PyCoreConfig config = _PyCoreConfig_INIT;
711
Victor Stinner177d9212018-08-29 11:25:15 +0200712 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200713 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200714
Victor Stinner1dc6e392018-07-25 02:49:17 +0200715 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
716 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
717 err = _PyCoreConfig_Read(&config);
718 }
719 else {
720 err = _Py_INIT_ERR("failed to copy core config");
721 }
722 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
723
724 if (_Py_INIT_FAILED(err)) {
725 goto done;
726 }
727
728 err = _Py_InitializeCore_impl(interp_p, &config);
729
730done:
731 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
732 _PyCoreConfig_Clear(&config);
733 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
734
735 return err;
736}
737
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200738/* Py_Initialize() has already been called: update the main interpreter
739 configuration. Example of bpo-34008: Py_Main() called after
740 Py_Initialize(). */
741static _PyInitError
742_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
743 const _PyMainInterpreterConfig *config)
744{
745 if (config->argv != NULL) {
746 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
747 if (res < 0) {
748 return _Py_INIT_ERR("fail to set sys.argv");
749 }
750 }
751 return _Py_INIT_OK();
752}
753
Eric Snowc7ec9982017-05-23 23:00:52 -0700754/* Update interpreter state based on supplied configuration settings
755 *
756 * After calling this function, most of the restrictions on the interpreter
757 * are lifted. The only remaining incomplete settings are those related
758 * to the main module (sys.argv[0], __main__ metadata)
759 *
760 * Calling this when the interpreter is not initializing, is already
761 * initialized or without a valid current thread state is a fatal error.
762 * Other errors should be reported as normal Python exceptions with a
763 * non-zero return code.
764 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800765_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200766_Py_InitializeMainInterpreter(PyInterpreterState *interp,
767 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700768{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600769 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800770 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700771 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700772
Victor Stinner1dc6e392018-07-25 02:49:17 +0200773 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100774 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
775 return _Py_INIT_ERR("failed to copy main interpreter config");
776 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200777 config = &interp->config;
778 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700779
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200780 if (_PyRuntime.initialized) {
781 return _Py_ReconfigureMainInterpreter(interp, config);
782 }
783
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200784 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700785 /* Special mode for freeze_importlib: run with no import system
786 *
787 * This means anything which needs support from extension modules
788 * or pure Python code in the standard library won't work.
789 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600790 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800791 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700792 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100793
Victor Stinner33c377e2017-12-05 15:12:41 +0100794 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800795 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100796 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200797
Victor Stinnerfbca9082018-08-30 00:50:45 +0200798 if (_PySys_EndInit(interp->sysdict, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800799 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100800 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800801
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200802 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800803 if (_Py_INIT_FAILED(err)) {
804 return err;
805 }
Nick Coghland6009512014-11-20 21:39:37 +1000806
807 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200808 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800809 if (_Py_INIT_FAILED(err)) {
810 return err;
811 }
Nick Coghland6009512014-11-20 21:39:37 +1000812
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800813 err = initfsencoding(interp);
814 if (_Py_INIT_FAILED(err)) {
815 return err;
816 }
Nick Coghland6009512014-11-20 21:39:37 +1000817
Victor Stinner1f151112017-11-23 10:43:14 +0100818 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800819 err = initsigs(); /* Signal handling stuff, including initintr() */
820 if (_Py_INIT_FAILED(err)) {
821 return err;
822 }
823 }
Nick Coghland6009512014-11-20 21:39:37 +1000824
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200825 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800826 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200827 }
Nick Coghland6009512014-11-20 21:39:37 +1000828
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800829 err = add_main_module(interp);
830 if (_Py_INIT_FAILED(err)) {
831 return err;
832 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800833
Victor Stinner91106cd2017-12-13 12:29:09 +0100834 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800835 if (_Py_INIT_FAILED(err)) {
836 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800837 }
Nick Coghland6009512014-11-20 21:39:37 +1000838
839 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100840 PyObject *warnoptions = PySys_GetObject("warnoptions");
841 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100842 {
Nick Coghland6009512014-11-20 21:39:37 +1000843 PyObject *warnings_module = PyImport_ImportModule("warnings");
844 if (warnings_module == NULL) {
845 fprintf(stderr, "'import warnings' failed; traceback:\n");
846 PyErr_Print();
847 }
848 Py_XDECREF(warnings_module);
849 }
850
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600851 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700852
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200853 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800854 err = initsite(); /* Module site */
855 if (_Py_INIT_FAILED(err)) {
856 return err;
857 }
858 }
Victor Stinnercf215042018-08-29 22:56:06 +0200859
860#ifndef MS_WINDOWS
861 _emit_stderr_warning_for_legacy_locale(core_config);
862#endif
863
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800864 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000865}
866
Eric Snowc7ec9982017-05-23 23:00:52 -0700867#undef _INIT_DEBUG_PRINT
868
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800869_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200870_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700871{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700872 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800873 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200874 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800875 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200876 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800877 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200878 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100879
Victor Stinner9cfc0022017-12-20 19:36:46 +0100880 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200881 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100882 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200883 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800884 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100885 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800886 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200887 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800888 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200889 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700890}
891
892
893void
Nick Coghland6009512014-11-20 21:39:37 +1000894Py_InitializeEx(int install_sigs)
895{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200896 if (_PyRuntime.initialized) {
897 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
898 return;
899 }
900
901 _PyInitError err;
902 _PyCoreConfig config = _PyCoreConfig_INIT;
903 config.install_signal_handlers = install_sigs;
904
905 err = _Py_InitializeFromConfig(&config);
906 _PyCoreConfig_Clear(&config);
907
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800908 if (_Py_INIT_FAILED(err)) {
909 _Py_FatalInitError(err);
910 }
Nick Coghland6009512014-11-20 21:39:37 +1000911}
912
913void
914Py_Initialize(void)
915{
916 Py_InitializeEx(1);
917}
918
919
920#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000921extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000922#endif
923
924/* Flush stdout and stderr */
925
926static int
927file_is_closed(PyObject *fobj)
928{
929 int r;
930 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
931 if (tmp == NULL) {
932 PyErr_Clear();
933 return 0;
934 }
935 r = PyObject_IsTrue(tmp);
936 Py_DECREF(tmp);
937 if (r < 0)
938 PyErr_Clear();
939 return r > 0;
940}
941
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000942static int
Nick Coghland6009512014-11-20 21:39:37 +1000943flush_std_files(void)
944{
945 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
946 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
947 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000948 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000949
950 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700951 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000952 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000953 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000954 status = -1;
955 }
Nick Coghland6009512014-11-20 21:39:37 +1000956 else
957 Py_DECREF(tmp);
958 }
959
960 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700961 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000962 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000963 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000964 status = -1;
965 }
Nick Coghland6009512014-11-20 21:39:37 +1000966 else
967 Py_DECREF(tmp);
968 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000969
970 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000971}
972
973/* Undo the effect of Py_Initialize().
974
975 Beware: if multiple interpreter and/or thread states exist, these
976 are not wiped out; only the current thread and interpreter state
977 are deleted. But since everything else is deleted, those other
978 interpreter and thread states should no longer be used.
979
980 (XXX We should do better, e.g. wipe out all interpreters and
981 threads.)
982
983 Locking: as above.
984
985*/
986
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000987int
988Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000989{
990 PyInterpreterState *interp;
991 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000992 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000993
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600994 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000995 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000996
997 wait_for_thread_shutdown();
998
Marcel Plch776407f2017-12-20 11:17:58 +0100999 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001000 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001001 interp = tstate->interp;
1002
Nick Coghland6009512014-11-20 21:39:37 +10001003 /* The interpreter is still entirely intact at this point, and the
1004 * exit funcs may be relying on that. In particular, if some thread
1005 * or exit func is still waiting to do an import, the import machinery
1006 * expects Py_IsInitialized() to return true. So don't say the
1007 * interpreter is uninitialized until after the exit funcs have run.
1008 * Note that Threading.py uses an exit func to do a join on all the
1009 * threads created thru it, so this also protects pending imports in
1010 * the threads created via Threading.
1011 */
Nick Coghland6009512014-11-20 21:39:37 +10001012
Marcel Plch776407f2017-12-20 11:17:58 +01001013 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001014
Victor Stinnerda273412017-12-15 01:46:02 +01001015 /* Copy the core config, PyInterpreterState_Delete() free
1016 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001017#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001018 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001019#endif
1020#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001021 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001022#endif
1023#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001024 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001025#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001026
Nick Coghland6009512014-11-20 21:39:37 +10001027 /* Remaining threads (e.g. daemon threads) will automatically exit
1028 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001029 _PyRuntime.finalizing = tstate;
1030 _PyRuntime.initialized = 0;
1031 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001032
Victor Stinnere0deff32015-03-24 13:46:18 +01001033 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001034 if (flush_std_files() < 0) {
1035 status = -1;
1036 }
Nick Coghland6009512014-11-20 21:39:37 +10001037
1038 /* Disable signal handling */
1039 PyOS_FiniInterrupts();
1040
1041 /* Collect garbage. This may call finalizers; it's nice to call these
1042 * before all modules are destroyed.
1043 * XXX If a __del__ or weakref callback is triggered here, and tries to
1044 * XXX import a module, bad things can happen, because Python no
1045 * XXX longer believes it's initialized.
1046 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1047 * XXX is easy to provoke that way. I've also seen, e.g.,
1048 * XXX Exception exceptions.ImportError: 'No module named sha'
1049 * XXX in <function callback at 0x008F5718> ignored
1050 * XXX but I'm unclear on exactly how that one happens. In any case,
1051 * XXX I haven't seen a real-life report of either of these.
1052 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001053 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001054#ifdef COUNT_ALLOCS
1055 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1056 each collection might release some types from the type
1057 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001058 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001059 /* nothing */;
1060#endif
Eric Snowdae02762017-09-14 00:35:58 -07001061
Nick Coghland6009512014-11-20 21:39:37 +10001062 /* Destroy all modules */
1063 PyImport_Cleanup();
1064
Victor Stinnere0deff32015-03-24 13:46:18 +01001065 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001066 if (flush_std_files() < 0) {
1067 status = -1;
1068 }
Nick Coghland6009512014-11-20 21:39:37 +10001069
1070 /* Collect final garbage. This disposes of cycles created by
1071 * class definitions, for example.
1072 * XXX This is disabled because it caused too many problems. If
1073 * XXX a __del__ or weakref callback triggers here, Python code has
1074 * XXX a hard time running, because even the sys module has been
1075 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1076 * XXX One symptom is a sequence of information-free messages
1077 * XXX coming from threads (if a __del__ or callback is invoked,
1078 * XXX other threads can execute too, and any exception they encounter
1079 * XXX triggers a comedy of errors as subsystem after subsystem
1080 * XXX fails to find what it *expects* to find in sys to help report
1081 * XXX the exception and consequent unexpected failures). I've also
1082 * XXX seen segfaults then, after adding print statements to the
1083 * XXX Python code getting called.
1084 */
1085#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001086 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001087#endif
1088
1089 /* Disable tracemalloc after all Python objects have been destroyed,
1090 so it is possible to use tracemalloc in objects destructor. */
1091 _PyTraceMalloc_Fini();
1092
1093 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1094 _PyImport_Fini();
1095
1096 /* Cleanup typeobject.c's internal caches. */
1097 _PyType_Fini();
1098
1099 /* unload faulthandler module */
1100 _PyFaulthandler_Fini();
1101
1102 /* Debugging stuff */
1103#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001104 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001105#endif
1106 /* dump hash stats */
1107 _PyHash_Fini();
1108
Eric Snowdae02762017-09-14 00:35:58 -07001109#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001110 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001111 _PyDebug_PrintTotalRefs();
1112 }
Eric Snowdae02762017-09-14 00:35:58 -07001113#endif
Nick Coghland6009512014-11-20 21:39:37 +10001114
1115#ifdef Py_TRACE_REFS
1116 /* Display all objects still alive -- this can invoke arbitrary
1117 * __repr__ overrides, so requires a mostly-intact interpreter.
1118 * Alas, a lot of stuff may still be alive now that will be cleaned
1119 * up later.
1120 */
Victor Stinnerda273412017-12-15 01:46:02 +01001121 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001122 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001123 }
Nick Coghland6009512014-11-20 21:39:37 +10001124#endif /* Py_TRACE_REFS */
1125
1126 /* Clear interpreter state and all thread states. */
1127 PyInterpreterState_Clear(interp);
1128
1129 /* Now we decref the exception classes. After this point nothing
1130 can raise an exception. That's okay, because each Fini() method
1131 below has been checked to make sure no exceptions are ever
1132 raised.
1133 */
1134
1135 _PyExc_Fini();
1136
1137 /* Sundry finalizers */
1138 PyMethod_Fini();
1139 PyFrame_Fini();
1140 PyCFunction_Fini();
1141 PyTuple_Fini();
1142 PyList_Fini();
1143 PySet_Fini();
1144 PyBytes_Fini();
1145 PyByteArray_Fini();
1146 PyLong_Fini();
1147 PyFloat_Fini();
1148 PyDict_Fini();
1149 PySlice_Fini();
1150 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001151 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001152 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001153 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001154 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001155
1156 /* Cleanup Unicode implementation */
1157 _PyUnicode_Fini();
1158
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001159 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001160
1161 /* XXX Still allocated:
1162 - various static ad-hoc pointers to interned strings
1163 - int and float free list blocks
1164 - whatever various modules and libraries allocate
1165 */
1166
1167 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1168
1169 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001170 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001171
1172 /* Delete current thread. After this, many C API calls become crashy. */
1173 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001174
Nick Coghland6009512014-11-20 21:39:37 +10001175 PyInterpreterState_Delete(interp);
1176
1177#ifdef Py_TRACE_REFS
1178 /* Display addresses (& refcnts) of all objects still alive.
1179 * An address can be used to find the repr of the object, printed
1180 * above by _Py_PrintReferences.
1181 */
Victor Stinnerda273412017-12-15 01:46:02 +01001182 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001183 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001184 }
Nick Coghland6009512014-11-20 21:39:37 +10001185#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001186#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001187 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001188 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001189 }
Nick Coghland6009512014-11-20 21:39:37 +10001190#endif
1191
1192 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001193
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001194 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001195 return status;
1196}
1197
1198void
1199Py_Finalize(void)
1200{
1201 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001202}
1203
1204/* Create and initialize a new interpreter and thread, and return the
1205 new thread. This requires that Py_Initialize() has been called
1206 first.
1207
1208 Unsuccessful initialization yields a NULL pointer. Note that *no*
1209 exception information is available even in this case -- the
1210 exception information is held in the thread, and there is no
1211 thread.
1212
1213 Locking: as above.
1214
1215*/
1216
Victor Stinnera7368ac2017-11-15 18:11:45 -08001217static _PyInitError
1218new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001219{
1220 PyInterpreterState *interp;
1221 PyThreadState *tstate, *save_tstate;
1222 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001223 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001224
Victor Stinnera7368ac2017-11-15 18:11:45 -08001225 if (!_PyRuntime.initialized) {
1226 return _Py_INIT_ERR("Py_Initialize must be called first");
1227 }
Nick Coghland6009512014-11-20 21:39:37 +10001228
Victor Stinner8a1be612016-03-14 22:07:55 +01001229 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1230 interpreters: disable PyGILState_Check(). */
1231 _PyGILState_check_enabled = 0;
1232
Nick Coghland6009512014-11-20 21:39:37 +10001233 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001234 if (interp == NULL) {
1235 *tstate_p = NULL;
1236 return _Py_INIT_OK();
1237 }
Nick Coghland6009512014-11-20 21:39:37 +10001238
1239 tstate = PyThreadState_New(interp);
1240 if (tstate == NULL) {
1241 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001242 *tstate_p = NULL;
1243 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001244 }
1245
1246 save_tstate = PyThreadState_Swap(tstate);
1247
Eric Snow1abcf672017-05-23 21:46:51 -07001248 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001249 _PyCoreConfig *core_config;
1250 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001251 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001252 core_config = &save_tstate->interp->core_config;
1253 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001254 } else {
1255 /* No current thread state, copy from the main interpreter */
1256 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001257 core_config = &main_interp->core_config;
1258 config = &main_interp->config;
1259 }
1260
1261 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1262 return _Py_INIT_ERR("failed to copy core config");
1263 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001264 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001265 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1266 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001267 }
1268
Nick Coghland6009512014-11-20 21:39:37 +10001269 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001270 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001271 if (modules == NULL) {
1272 return _Py_INIT_ERR("can't make modules dictionary");
1273 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001274 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001275
Eric Snowd393c1b2017-09-14 12:18:12 -06001276 sysmod = _PyImport_FindBuiltin("sys", modules);
1277 if (sysmod != NULL) {
1278 interp->sysdict = PyModule_GetDict(sysmod);
1279 if (interp->sysdict == NULL)
1280 goto handle_error;
1281 Py_INCREF(interp->sysdict);
1282 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001283 _PySys_EndInit(interp->sysdict, interp);
Eric Snowd393c1b2017-09-14 12:18:12 -06001284 }
1285
1286 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001287 if (bimod != NULL) {
1288 interp->builtins = PyModule_GetDict(bimod);
1289 if (interp->builtins == NULL)
1290 goto handle_error;
1291 Py_INCREF(interp->builtins);
1292 }
1293
1294 /* initialize builtin exceptions */
1295 _PyExc_Init(bimod);
1296
Nick Coghland6009512014-11-20 21:39:37 +10001297 if (bimod != NULL && sysmod != NULL) {
1298 PyObject *pstderr;
1299
Nick Coghland6009512014-11-20 21:39:37 +10001300 /* Set up a preliminary stderr printer until we have enough
1301 infrastructure for the io module in place. */
1302 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001303 if (pstderr == NULL) {
1304 return _Py_INIT_ERR("can't set preliminary stderr");
1305 }
Nick Coghland6009512014-11-20 21:39:37 +10001306 _PySys_SetObjectId(&PyId_stderr, pstderr);
1307 PySys_SetObject("__stderr__", pstderr);
1308 Py_DECREF(pstderr);
1309
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001310 err = _PyImportHooks_Init();
1311 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001312 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001313 }
Nick Coghland6009512014-11-20 21:39:37 +10001314
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001315 err = initimport(interp, sysmod);
1316 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001317 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001318 }
Nick Coghland6009512014-11-20 21:39:37 +10001319
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001320 err = initexternalimport(interp);
1321 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001322 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001323 }
Nick Coghland6009512014-11-20 21:39:37 +10001324
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001325 err = initfsencoding(interp);
1326 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001327 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001328 }
1329
Victor Stinner91106cd2017-12-13 12:29:09 +01001330 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001331 if (_Py_INIT_FAILED(err)) {
1332 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001333 }
1334
1335 err = add_main_module(interp);
1336 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001337 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001338 }
1339
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001340 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001341 err = initsite();
1342 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001343 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001344 }
1345 }
Nick Coghland6009512014-11-20 21:39:37 +10001346 }
1347
Victor Stinnera7368ac2017-11-15 18:11:45 -08001348 if (PyErr_Occurred()) {
1349 goto handle_error;
1350 }
Nick Coghland6009512014-11-20 21:39:37 +10001351
Victor Stinnera7368ac2017-11-15 18:11:45 -08001352 *tstate_p = tstate;
1353 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001354
Nick Coghland6009512014-11-20 21:39:37 +10001355handle_error:
1356 /* Oops, it didn't work. Undo it all. */
1357
1358 PyErr_PrintEx(0);
1359 PyThreadState_Clear(tstate);
1360 PyThreadState_Swap(save_tstate);
1361 PyThreadState_Delete(tstate);
1362 PyInterpreterState_Delete(interp);
1363
Victor Stinnera7368ac2017-11-15 18:11:45 -08001364 *tstate_p = NULL;
1365 return _Py_INIT_OK();
1366}
1367
1368PyThreadState *
1369Py_NewInterpreter(void)
1370{
1371 PyThreadState *tstate;
1372 _PyInitError err = new_interpreter(&tstate);
1373 if (_Py_INIT_FAILED(err)) {
1374 _Py_FatalInitError(err);
1375 }
1376 return tstate;
1377
Nick Coghland6009512014-11-20 21:39:37 +10001378}
1379
1380/* Delete an interpreter and its last thread. This requires that the
1381 given thread state is current, that the thread has no remaining
1382 frames, and that it is its interpreter's only remaining thread.
1383 It is a fatal error to violate these constraints.
1384
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001385 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001386 everything, regardless.)
1387
1388 Locking: as above.
1389
1390*/
1391
1392void
1393Py_EndInterpreter(PyThreadState *tstate)
1394{
1395 PyInterpreterState *interp = tstate->interp;
1396
Victor Stinner50b48572018-11-01 01:51:40 +01001397 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001398 Py_FatalError("Py_EndInterpreter: thread is not current");
1399 if (tstate->frame != NULL)
1400 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1401
1402 wait_for_thread_shutdown();
1403
Marcel Plch776407f2017-12-20 11:17:58 +01001404 call_py_exitfuncs(interp);
1405
Nick Coghland6009512014-11-20 21:39:37 +10001406 if (tstate != interp->tstate_head || tstate->next != NULL)
1407 Py_FatalError("Py_EndInterpreter: not the last thread");
1408
1409 PyImport_Cleanup();
1410 PyInterpreterState_Clear(interp);
1411 PyThreadState_Swap(NULL);
1412 PyInterpreterState_Delete(interp);
1413}
1414
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001415/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001416
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001417static _PyInitError
1418add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001419{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001420 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001421 m = PyImport_AddModule("__main__");
1422 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001423 return _Py_INIT_ERR("can't create __main__ module");
1424
Nick Coghland6009512014-11-20 21:39:37 +10001425 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001426 ann_dict = PyDict_New();
1427 if ((ann_dict == NULL) ||
1428 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001429 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001430 }
1431 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001432
Nick Coghland6009512014-11-20 21:39:37 +10001433 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1434 PyObject *bimod = PyImport_ImportModule("builtins");
1435 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001436 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001437 }
1438 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001439 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001440 }
1441 Py_DECREF(bimod);
1442 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001443
Nick Coghland6009512014-11-20 21:39:37 +10001444 /* Main is a little special - imp.is_builtin("__main__") will return
1445 * False, but BuiltinImporter is still the most appropriate initial
1446 * setting for its __loader__ attribute. A more suitable value will
1447 * be set if __main__ gets further initialized later in the startup
1448 * process.
1449 */
1450 loader = PyDict_GetItemString(d, "__loader__");
1451 if (loader == NULL || loader == Py_None) {
1452 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1453 "BuiltinImporter");
1454 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001455 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001456 }
1457 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001458 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001459 }
1460 Py_DECREF(loader);
1461 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001462 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001463}
1464
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001465static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001466initfsencoding(PyInterpreterState *interp)
1467{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001468 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001469
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001470 char *encoding = get_codec_name(config->filesystem_encoding);
1471 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001472 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001473 memory, import a module of the standard library failed, etc. */
1474 return _Py_INIT_ERR("failed to get the Python codec "
1475 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001476 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001477
1478 /* Update the filesystem encoding to the normalized Python codec name.
1479 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1480 (Python codec name). */
1481 PyMem_RawFree(config->filesystem_encoding);
1482 config->filesystem_encoding = encoding;
1483
1484 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1485 global configuration variables. */
1486 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1487 config->filesystem_errors) < 0) {
1488 return _Py_INIT_NO_MEMORY();
1489 }
1490
1491 /* PyUnicode can now use the Python codec rather than C implementation
1492 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001493 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001494 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001495}
1496
1497/* Import the site module (not into __main__ though) */
1498
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001499static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001500initsite(void)
1501{
1502 PyObject *m;
1503 m = PyImport_ImportModule("site");
1504 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001505 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001506 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001507 Py_DECREF(m);
1508 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001509}
1510
Victor Stinner874dbe82015-09-04 17:29:57 +02001511/* Check if a file descriptor is valid or not.
1512 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1513static int
1514is_valid_fd(int fd)
1515{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001516#ifdef __APPLE__
1517 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1518 and the other side of the pipe is closed, dup(1) succeed, whereas
1519 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1520 such error. */
1521 struct stat st;
1522 return (fstat(fd, &st) == 0);
1523#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001524 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001525 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001526 return 0;
1527 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001528 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1529 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1530 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001531 fd2 = dup(fd);
1532 if (fd2 >= 0)
1533 close(fd2);
1534 _Py_END_SUPPRESS_IPH
1535 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001536#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001537}
1538
1539/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001540static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001541create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001542 int fd, int write_mode, const char* name,
1543 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001544{
1545 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1546 const char* mode;
1547 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001548 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001549 int buffering, isatty;
1550 _Py_IDENTIFIER(open);
1551 _Py_IDENTIFIER(isatty);
1552 _Py_IDENTIFIER(TextIOWrapper);
1553 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001554 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001555
Victor Stinner874dbe82015-09-04 17:29:57 +02001556 if (!is_valid_fd(fd))
1557 Py_RETURN_NONE;
1558
Nick Coghland6009512014-11-20 21:39:37 +10001559 /* stdin is always opened in buffered mode, first because it shouldn't
1560 make a difference in common use cases, second because TextIOWrapper
1561 depends on the presence of a read1() method which only exists on
1562 buffered streams.
1563 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001564 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001565 buffering = 0;
1566 else
1567 buffering = -1;
1568 if (write_mode)
1569 mode = "wb";
1570 else
1571 mode = "rb";
1572 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1573 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001574 Py_None, Py_None, /* encoding, errors */
1575 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001576 if (buf == NULL)
1577 goto error;
1578
1579 if (buffering) {
1580 _Py_IDENTIFIER(raw);
1581 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1582 if (raw == NULL)
1583 goto error;
1584 }
1585 else {
1586 raw = buf;
1587 Py_INCREF(raw);
1588 }
1589
Steve Dower39294992016-08-30 21:22:36 -07001590#ifdef MS_WINDOWS
1591 /* Windows console IO is always UTF-8 encoded */
1592 if (PyWindowsConsoleIO_Check(raw))
1593 encoding = "utf-8";
1594#endif
1595
Nick Coghland6009512014-11-20 21:39:37 +10001596 text = PyUnicode_FromString(name);
1597 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1598 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001599 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001600 if (res == NULL)
1601 goto error;
1602 isatty = PyObject_IsTrue(res);
1603 Py_DECREF(res);
1604 if (isatty == -1)
1605 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001606 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001607 write_through = Py_True;
1608 else
1609 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001610 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001611 line_buffering = Py_True;
1612 else
1613 line_buffering = Py_False;
1614
1615 Py_CLEAR(raw);
1616 Py_CLEAR(text);
1617
1618#ifdef MS_WINDOWS
1619 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1620 newlines to "\n".
1621 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1622 newline = NULL;
1623#else
1624 /* sys.stdin: split lines at "\n".
1625 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1626 newline = "\n";
1627#endif
1628
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001629 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001630 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001631 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001632 Py_CLEAR(buf);
1633 if (stream == NULL)
1634 goto error;
1635
1636 if (write_mode)
1637 mode = "w";
1638 else
1639 mode = "r";
1640 text = PyUnicode_FromString(mode);
1641 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1642 goto error;
1643 Py_CLEAR(text);
1644 return stream;
1645
1646error:
1647 Py_XDECREF(buf);
1648 Py_XDECREF(stream);
1649 Py_XDECREF(text);
1650 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001651
Victor Stinner874dbe82015-09-04 17:29:57 +02001652 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1653 /* Issue #24891: the file descriptor was closed after the first
1654 is_valid_fd() check was called. Ignore the OSError and set the
1655 stream to None. */
1656 PyErr_Clear();
1657 Py_RETURN_NONE;
1658 }
1659 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001660}
1661
1662/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001663static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001664init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001665{
1666 PyObject *iomod = NULL, *wrapper;
1667 PyObject *bimod = NULL;
1668 PyObject *m;
1669 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001670 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001671 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001672 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001673 _PyCoreConfig *config = &interp->core_config;
1674
1675 char *codec_name = get_codec_name(config->stdio_encoding);
1676 if (codec_name == NULL) {
1677 return _Py_INIT_ERR("failed to get the Python codec name "
1678 "of the stdio encoding");
1679 }
1680 PyMem_RawFree(config->stdio_encoding);
1681 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001682
1683 /* Hack to avoid a nasty recursion issue when Python is invoked
1684 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1685 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1686 goto error;
1687 }
1688 Py_DECREF(m);
1689
1690 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1691 goto error;
1692 }
1693 Py_DECREF(m);
1694
1695 if (!(bimod = PyImport_ImportModule("builtins"))) {
1696 goto error;
1697 }
1698
1699 if (!(iomod = PyImport_ImportModule("io"))) {
1700 goto error;
1701 }
1702 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1703 goto error;
1704 }
1705
1706 /* Set builtins.open */
1707 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1708 Py_DECREF(wrapper);
1709 goto error;
1710 }
1711 Py_DECREF(wrapper);
1712
Nick Coghland6009512014-11-20 21:39:37 +10001713 /* Set sys.stdin */
1714 fd = fileno(stdin);
1715 /* Under some conditions stdin, stdout and stderr may not be connected
1716 * and fileno() may point to an invalid file descriptor. For example
1717 * GUI apps don't have valid standard streams by default.
1718 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001719 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001720 config->stdio_encoding,
1721 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001722 if (std == NULL)
1723 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001724 PySys_SetObject("__stdin__", std);
1725 _PySys_SetObjectId(&PyId_stdin, std);
1726 Py_DECREF(std);
1727
1728 /* Set sys.stdout */
1729 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001730 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001731 config->stdio_encoding,
1732 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001733 if (std == NULL)
1734 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001735 PySys_SetObject("__stdout__", std);
1736 _PySys_SetObjectId(&PyId_stdout, std);
1737 Py_DECREF(std);
1738
1739#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1740 /* Set sys.stderr, replaces the preliminary stderr */
1741 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001742 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001743 config->stdio_encoding,
1744 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001745 if (std == NULL)
1746 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001747
1748 /* Same as hack above, pre-import stderr's codec to avoid recursion
1749 when import.c tries to write to stderr in verbose mode. */
1750 encoding_attr = PyObject_GetAttrString(std, "encoding");
1751 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001752 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001753 if (std_encoding != NULL) {
1754 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1755 Py_XDECREF(codec_info);
1756 }
1757 Py_DECREF(encoding_attr);
1758 }
1759 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1760
1761 if (PySys_SetObject("__stderr__", std) < 0) {
1762 Py_DECREF(std);
1763 goto error;
1764 }
1765 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1766 Py_DECREF(std);
1767 goto error;
1768 }
1769 Py_DECREF(std);
1770#endif
1771
Victor Stinnera7368ac2017-11-15 18:11:45 -08001772 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001773
Victor Stinnera7368ac2017-11-15 18:11:45 -08001774error:
1775 res = _Py_INIT_ERR("can't initialize sys standard streams");
1776
1777done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001778 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001779
Nick Coghland6009512014-11-20 21:39:37 +10001780 Py_XDECREF(bimod);
1781 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001782 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001783}
1784
1785
Victor Stinner10dc4842015-03-24 12:01:30 +01001786static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001787_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001788{
Victor Stinner10dc4842015-03-24 12:01:30 +01001789 fputc('\n', stderr);
1790 fflush(stderr);
1791
1792 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001793 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001794}
Victor Stinner791da1c2016-03-14 16:53:12 +01001795
1796/* Print the current exception (if an exception is set) with its traceback,
1797 or display the current Python stack.
1798
1799 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1800 called on catastrophic cases.
1801
1802 Return 1 if the traceback was displayed, 0 otherwise. */
1803
1804static int
1805_Py_FatalError_PrintExc(int fd)
1806{
1807 PyObject *ferr, *res;
1808 PyObject *exception, *v, *tb;
1809 int has_tb;
1810
Victor Stinner791da1c2016-03-14 16:53:12 +01001811 PyErr_Fetch(&exception, &v, &tb);
1812 if (exception == NULL) {
1813 /* No current exception */
1814 return 0;
1815 }
1816
1817 ferr = _PySys_GetObjectId(&PyId_stderr);
1818 if (ferr == NULL || ferr == Py_None) {
1819 /* sys.stderr is not set yet or set to None,
1820 no need to try to display the exception */
1821 return 0;
1822 }
1823
1824 PyErr_NormalizeException(&exception, &v, &tb);
1825 if (tb == NULL) {
1826 tb = Py_None;
1827 Py_INCREF(tb);
1828 }
1829 PyException_SetTraceback(v, tb);
1830 if (exception == NULL) {
1831 /* PyErr_NormalizeException() failed */
1832 return 0;
1833 }
1834
1835 has_tb = (tb != Py_None);
1836 PyErr_Display(exception, v, tb);
1837 Py_XDECREF(exception);
1838 Py_XDECREF(v);
1839 Py_XDECREF(tb);
1840
1841 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001842 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001843 if (res == NULL)
1844 PyErr_Clear();
1845 else
1846 Py_DECREF(res);
1847
1848 return has_tb;
1849}
1850
Nick Coghland6009512014-11-20 21:39:37 +10001851/* Print fatal error message and abort */
1852
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001853#ifdef MS_WINDOWS
1854static void
1855fatal_output_debug(const char *msg)
1856{
1857 /* buffer of 256 bytes allocated on the stack */
1858 WCHAR buffer[256 / sizeof(WCHAR)];
1859 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1860 size_t msglen;
1861
1862 OutputDebugStringW(L"Fatal Python error: ");
1863
1864 msglen = strlen(msg);
1865 while (msglen) {
1866 size_t i;
1867
1868 if (buflen > msglen) {
1869 buflen = msglen;
1870 }
1871
1872 /* Convert the message to wchar_t. This uses a simple one-to-one
1873 conversion, assuming that the this error message actually uses
1874 ASCII only. If this ceases to be true, we will have to convert. */
1875 for (i=0; i < buflen; ++i) {
1876 buffer[i] = msg[i];
1877 }
1878 buffer[i] = L'\0';
1879 OutputDebugStringW(buffer);
1880
1881 msg += buflen;
1882 msglen -= buflen;
1883 }
1884 OutputDebugStringW(L"\n");
1885}
1886#endif
1887
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001888static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001889fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001890{
1891 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001892 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001893
1894 if (reentrant) {
1895 /* Py_FatalError() caused a second fatal error.
1896 Example: flush_std_files() raises a recursion error. */
1897 goto exit;
1898 }
1899 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001900
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001901 fprintf(stderr, "Fatal Python error: ");
1902 if (prefix) {
1903 fputs(prefix, stderr);
1904 fputs(": ", stderr);
1905 }
1906 if (msg) {
1907 fputs(msg, stderr);
1908 }
1909 else {
1910 fprintf(stderr, "<message not set>");
1911 }
1912 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001913 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001914
Victor Stinner3a228ab2018-11-01 00:26:41 +01001915 /* Check if the current thread has a Python thread state
1916 and holds the GIL */
1917 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
1918 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01001919 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01001920 if (tss_tstate != tstate) {
1921 /* The Python thread does not hold the GIL */
1922 tss_tstate = NULL;
1923 }
1924 }
1925 else {
1926 /* Py_FatalError() has been called from a C thread
1927 which has no Python thread state. */
1928 }
1929 int has_tstate_and_gil = (tss_tstate != NULL);
1930
1931 if (has_tstate_and_gil) {
1932 /* If an exception is set, print the exception with its traceback */
1933 if (!_Py_FatalError_PrintExc(fd)) {
1934 /* No exception is set, or an exception is set without traceback */
1935 _Py_FatalError_DumpTracebacks(fd);
1936 }
1937 }
1938 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01001939 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001940 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001941
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001942 /* The main purpose of faulthandler is to display the traceback.
1943 This function already did its best to display a traceback.
1944 Disable faulthandler to prevent writing a second traceback
1945 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001946 _PyFaulthandler_Fini();
1947
Victor Stinner791da1c2016-03-14 16:53:12 +01001948 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01001949 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001950 /* Flush sys.stdout and sys.stderr */
1951 flush_std_files();
1952 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001953
Nick Coghland6009512014-11-20 21:39:37 +10001954#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001955 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001956#endif /* MS_WINDOWS */
1957
1958exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001959 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01001960#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001961 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10001962#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001963 abort();
1964 }
1965 else {
1966 exit(status);
1967 }
1968}
1969
Victor Stinner19760862017-12-20 01:41:59 +01001970void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001971Py_FatalError(const char *msg)
1972{
1973 fatal_error(NULL, msg, -1);
1974}
1975
Victor Stinner19760862017-12-20 01:41:59 +01001976void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001977_Py_FatalInitError(_PyInitError err)
1978{
1979 /* On "user" error: exit with status 1.
1980 For all other errors, call abort(). */
1981 int status = err.user_err ? 1 : -1;
1982 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10001983}
1984
1985/* Clean up and exit */
1986
Victor Stinnerd7292b52016-06-17 12:29:00 +02001987# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001988
Nick Coghland6009512014-11-20 21:39:37 +10001989/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01001990void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10001991{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001992 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01001993
Antoine Pitroufc5db952017-12-13 02:29:07 +01001994 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01001995 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
1996
1997 is->pyexitfunc = func;
1998 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10001999}
2000
2001static void
Marcel Plch776407f2017-12-20 11:17:58 +01002002call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002003{
Marcel Plch776407f2017-12-20 11:17:58 +01002004 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002005 return;
2006
Marcel Plch776407f2017-12-20 11:17:58 +01002007 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002008 PyErr_Clear();
2009}
2010
2011/* Wait until threading._shutdown completes, provided
2012 the threading module was imported in the first place.
2013 The shutdown routine will wait until all non-daemon
2014 "threading" threads have completed. */
2015static void
2016wait_for_thread_shutdown(void)
2017{
Nick Coghland6009512014-11-20 21:39:37 +10002018 _Py_IDENTIFIER(_shutdown);
2019 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002020 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002021 if (threading == NULL) {
2022 /* threading not imported */
2023 PyErr_Clear();
2024 return;
2025 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002026 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002027 if (result == NULL) {
2028 PyErr_WriteUnraisable(threading);
2029 }
2030 else {
2031 Py_DECREF(result);
2032 }
2033 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002034}
2035
2036#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002037int Py_AtExit(void (*func)(void))
2038{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002039 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002040 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002041 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002042 return 0;
2043}
2044
2045static void
2046call_ll_exitfuncs(void)
2047{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002048 while (_PyRuntime.nexitfuncs > 0)
2049 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002050
2051 fflush(stdout);
2052 fflush(stderr);
2053}
2054
Victor Stinnercfc88312018-08-01 16:41:25 +02002055void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002056Py_Exit(int sts)
2057{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002058 if (Py_FinalizeEx() < 0) {
2059 sts = 120;
2060 }
Nick Coghland6009512014-11-20 21:39:37 +10002061
2062 exit(sts);
2063}
2064
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002065static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002066initsigs(void)
2067{
2068#ifdef SIGPIPE
2069 PyOS_setsig(SIGPIPE, SIG_IGN);
2070#endif
2071#ifdef SIGXFZ
2072 PyOS_setsig(SIGXFZ, SIG_IGN);
2073#endif
2074#ifdef SIGXFSZ
2075 PyOS_setsig(SIGXFSZ, SIG_IGN);
2076#endif
2077 PyOS_InitInterrupts(); /* May imply initsignal() */
2078 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002079 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002080 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002081 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002082}
2083
2084
2085/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2086 *
2087 * All of the code in this function must only use async-signal-safe functions,
2088 * listed at `man 7 signal` or
2089 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2090 */
2091void
2092_Py_RestoreSignals(void)
2093{
2094#ifdef SIGPIPE
2095 PyOS_setsig(SIGPIPE, SIG_DFL);
2096#endif
2097#ifdef SIGXFZ
2098 PyOS_setsig(SIGXFZ, SIG_DFL);
2099#endif
2100#ifdef SIGXFSZ
2101 PyOS_setsig(SIGXFSZ, SIG_DFL);
2102#endif
2103}
2104
2105
2106/*
2107 * The file descriptor fd is considered ``interactive'' if either
2108 * a) isatty(fd) is TRUE, or
2109 * b) the -i flag was given, and the filename associated with
2110 * the descriptor is NULL or "<stdin>" or "???".
2111 */
2112int
2113Py_FdIsInteractive(FILE *fp, const char *filename)
2114{
2115 if (isatty((int)fileno(fp)))
2116 return 1;
2117 if (!Py_InteractiveFlag)
2118 return 0;
2119 return (filename == NULL) ||
2120 (strcmp(filename, "<stdin>") == 0) ||
2121 (strcmp(filename, "???") == 0);
2122}
2123
2124
Nick Coghland6009512014-11-20 21:39:37 +10002125/* Wrappers around sigaction() or signal(). */
2126
2127PyOS_sighandler_t
2128PyOS_getsig(int sig)
2129{
2130#ifdef HAVE_SIGACTION
2131 struct sigaction context;
2132 if (sigaction(sig, NULL, &context) == -1)
2133 return SIG_ERR;
2134 return context.sa_handler;
2135#else
2136 PyOS_sighandler_t handler;
2137/* Special signal handling for the secure CRT in Visual Studio 2005 */
2138#if defined(_MSC_VER) && _MSC_VER >= 1400
2139 switch (sig) {
2140 /* Only these signals are valid */
2141 case SIGINT:
2142 case SIGILL:
2143 case SIGFPE:
2144 case SIGSEGV:
2145 case SIGTERM:
2146 case SIGBREAK:
2147 case SIGABRT:
2148 break;
2149 /* Don't call signal() with other values or it will assert */
2150 default:
2151 return SIG_ERR;
2152 }
2153#endif /* _MSC_VER && _MSC_VER >= 1400 */
2154 handler = signal(sig, SIG_IGN);
2155 if (handler != SIG_ERR)
2156 signal(sig, handler);
2157 return handler;
2158#endif
2159}
2160
2161/*
2162 * All of the code in this function must only use async-signal-safe functions,
2163 * listed at `man 7 signal` or
2164 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2165 */
2166PyOS_sighandler_t
2167PyOS_setsig(int sig, PyOS_sighandler_t handler)
2168{
2169#ifdef HAVE_SIGACTION
2170 /* Some code in Modules/signalmodule.c depends on sigaction() being
2171 * used here if HAVE_SIGACTION is defined. Fix that if this code
2172 * changes to invalidate that assumption.
2173 */
2174 struct sigaction context, ocontext;
2175 context.sa_handler = handler;
2176 sigemptyset(&context.sa_mask);
2177 context.sa_flags = 0;
2178 if (sigaction(sig, &context, &ocontext) == -1)
2179 return SIG_ERR;
2180 return ocontext.sa_handler;
2181#else
2182 PyOS_sighandler_t oldhandler;
2183 oldhandler = signal(sig, handler);
2184#ifdef HAVE_SIGINTERRUPT
2185 siginterrupt(sig, 1);
2186#endif
2187 return oldhandler;
2188#endif
2189}
2190
2191#ifdef __cplusplus
2192}
2193#endif