blob: df9570b2e4877581f3265b166a7c26e938a92e21 [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 Stinnerf684d832019-03-01 03:44:13 +01007#include "pycore_coreconfig.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01008#include "pycore_context.h"
Victor Stinner353933e2018-11-23 13:08:26 +01009#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010010#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010011#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010012#include "pycore_pylifecycle.h"
13#include "pycore_pymem.h"
14#include "pycore_pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100015#include "grammar.h"
16#include "node.h"
17#include "token.h"
18#include "parsetok.h"
19#include "errcode.h"
20#include "code.h"
21#include "symtable.h"
22#include "ast.h"
23#include "marshal.h"
24#include "osdefs.h"
25#include <locale.h>
26
27#ifdef HAVE_SIGNAL_H
28#include <signal.h>
29#endif
30
31#ifdef MS_WINDOWS
32#include "malloc.h" /* for alloca */
33#endif
34
35#ifdef HAVE_LANGINFO_H
36#include <langinfo.h>
37#endif
38
39#ifdef MS_WINDOWS
40#undef BYTE
41#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070042
43extern PyTypeObject PyWindowsConsoleIO_Type;
44#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100045#endif
46
47_Py_IDENTIFIER(flush);
48_Py_IDENTIFIER(name);
49_Py_IDENTIFIER(stdin);
50_Py_IDENTIFIER(stdout);
51_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060052_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100053
54#ifdef __cplusplus
55extern "C" {
56#endif
57
Nick Coghland6009512014-11-20 21:39:37 +100058extern grammar _PyParser_Grammar; /* From graminit.c */
59
60/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080061static _PyInitError add_main_module(PyInterpreterState *interp);
62static _PyInitError initfsencoding(PyInterpreterState *interp);
63static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010064static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080065static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010066static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100067static void wait_for_thread_shutdown(void);
68static void call_ll_exitfuncs(void);
Nick Coghland6009512014-11-20 21:39:37 +100069
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080070int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010072static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075_PyRuntime_Initialize(void)
76{
77 /* XXX We only initialize once in the process, which aligns with
78 the static initialization of the former globals now found in
79 _PyRuntime. However, _PyRuntime *should* be initialized with
80 every Py_Initialize() call, but doing so breaks the runtime.
81 This is because the runtime state is not properly finalized
82 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010083 if (runtime_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084 return _Py_INIT_OK();
85 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010086 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087
88 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
90
91void
92_PyRuntime_Finalize(void)
93{
94 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010095 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
97
98int
99_Py_IsFinalizing(void)
100{
101 return _PyRuntime.finalizing != NULL;
102}
103
Nick Coghland6009512014-11-20 21:39:37 +1000104/* Hack to force loading of object files */
105int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
106 PyOS_mystrnicmp; /* Python/pystrcmp.o */
107
108/* PyModule_GetWarningsModule is no longer necessary as of 2.6
109since _warnings is builtin. This API should not be used. */
110PyObject *
111PyModule_GetWarningsModule(void)
112{
113 return PyImport_ImportModule("warnings");
114}
115
Eric Snowc7ec9982017-05-23 23:00:52 -0700116
Eric Snow1abcf672017-05-23 21:46:51 -0700117/* APIs to access the initialization flags
118 *
119 * Can be called prior to Py_Initialize.
120 */
Nick Coghland6009512014-11-20 21:39:37 +1000121
Eric Snow1abcf672017-05-23 21:46:51 -0700122int
123_Py_IsCoreInitialized(void)
124{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600125 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700126}
Nick Coghland6009512014-11-20 21:39:37 +1000127
128int
129Py_IsInitialized(void)
130{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600131 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000132}
133
Nick Coghlan6ea41862017-06-11 13:16:15 +1000134
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000135/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
136 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000137 initializations fail, a fatal error is issued and the function does
138 not return. On return, the first thread and interpreter state have
139 been created.
140
141 Locking: you must hold the interpreter lock while calling this.
142 (If the lock has not yet been initialized, that's equivalent to
143 having the lock, but you cannot use multiple threads.)
144
145*/
146
Nick Coghland6009512014-11-20 21:39:37 +1000147static char*
148get_codec_name(const char *encoding)
149{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200150 const char *name_utf8;
151 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000152 PyObject *codec, *name = NULL;
153
154 codec = _PyCodec_Lookup(encoding);
155 if (!codec)
156 goto error;
157
158 name = _PyObject_GetAttrId(codec, &PyId_name);
159 Py_CLEAR(codec);
160 if (!name)
161 goto error;
162
Serhiy Storchaka06515832016-11-20 09:13:07 +0200163 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000164 if (name_utf8 == NULL)
165 goto error;
166 name_str = _PyMem_RawStrdup(name_utf8);
167 Py_DECREF(name);
168 if (name_str == NULL) {
169 PyErr_NoMemory();
170 return NULL;
171 }
172 return name_str;
173
174error:
175 Py_XDECREF(codec);
176 Py_XDECREF(name);
177 return NULL;
178}
179
Nick Coghland6009512014-11-20 21:39:37 +1000180
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800181static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700182initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000183{
184 PyObject *importlib;
185 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000186 PyObject *value;
187
188 /* Import _importlib through its frozen version, _frozen_importlib. */
189 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800190 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000191 }
192 else if (Py_VerboseFlag) {
193 PySys_FormatStderr("import _frozen_importlib # frozen\n");
194 }
195 importlib = PyImport_AddModule("_frozen_importlib");
196 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800197 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000198 }
199 interp->importlib = importlib;
200 Py_INCREF(interp->importlib);
201
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300202 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
203 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800204 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300205 Py_INCREF(interp->import_func);
206
Victor Stinnercd6e6942015-09-18 09:11:57 +0200207 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800208 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000209 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800210 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000211 }
212 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200213 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000214 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600215 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800216 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000217 }
218
Victor Stinnercd6e6942015-09-18 09:11:57 +0200219 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000220 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
221 if (value == NULL) {
222 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800223 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000224 }
225 Py_DECREF(value);
226 Py_DECREF(impmod);
227
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800228 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000229}
230
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800231static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700232initexternalimport(PyInterpreterState *interp)
233{
234 PyObject *value;
235 value = PyObject_CallMethod(interp->importlib,
236 "_install_external_importers", "");
237 if (value == NULL) {
238 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800239 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700240 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200241 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300242 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700243}
Nick Coghland6009512014-11-20 21:39:37 +1000244
Nick Coghlan6ea41862017-06-11 13:16:15 +1000245/* Helper functions to better handle the legacy C locale
246 *
247 * The legacy C locale assumes ASCII as the default text encoding, which
248 * causes problems not only for the CPython runtime, but also other
249 * components like GNU readline.
250 *
251 * Accordingly, when the CLI detects it, it attempts to coerce it to a
252 * more capable UTF-8 based alternative as follows:
253 *
254 * if (_Py_LegacyLocaleDetected()) {
255 * _Py_CoerceLegacyLocale();
256 * }
257 *
258 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
259 *
260 * Locale coercion also impacts the default error handler for the standard
261 * streams: while the usual default is "strict", the default for the legacy
262 * C locale and for any of the coercion target locales is "surrogateescape".
263 */
264
265int
266_Py_LegacyLocaleDetected(void)
267{
268#ifndef MS_WINDOWS
269 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000270 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
271 * the POSIX locale as a simple alias for the C locale, so
272 * we may also want to check for that explicitly.
273 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000274 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
275 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
276#else
277 /* Windows uses code pages instead of locales, so no locale is legacy */
278 return 0;
279#endif
280}
281
Nick Coghlaneb817952017-06-18 12:29:42 +1000282static const char *_C_LOCALE_WARNING =
283 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
284 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
285 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
286 "locales is recommended.\n";
287
Nick Coghlaneb817952017-06-18 12:29:42 +1000288static void
Victor Stinner94540602017-12-16 04:54:22 +0100289_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000290{
Victor Stinner5a02e0d2019-03-05 12:32:09 +0100291 if (core_config->preconfig.coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200292 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000293 }
294}
295
Nick Coghlan6ea41862017-06-11 13:16:15 +1000296typedef struct _CandidateLocale {
297 const char *locale_name; /* The locale to try as a coercion target */
298} _LocaleCoercionTarget;
299
300static _LocaleCoercionTarget _TARGET_LOCALES[] = {
301 {"C.UTF-8"},
302 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000303 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000304 {NULL}
305};
306
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200307
308int
309_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000310{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200311 const _LocaleCoercionTarget *target = NULL;
312 for (target = _TARGET_LOCALES; target->locale_name; target++) {
313 if (strcmp(ctype_loc, target->locale_name) == 0) {
314 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200316 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200317 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318}
319
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200320
Nick Coghlan6ea41862017-06-11 13:16:15 +1000321#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100322static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000323 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
324 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
325
326static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200327_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328{
329 const char *newloc = target->locale_name;
330
331 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100332 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000333
334 /* Set the relevant locale environment variable */
335 if (setenv("LC_CTYPE", newloc, 1)) {
336 fprintf(stderr,
337 "Error setting LC_CTYPE, skipping C locale coercion\n");
338 return;
339 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200340 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100341 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000342 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000343
344 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100345 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000346}
347#endif
348
349void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200350_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000351{
352#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200353 char *oldloc = NULL;
354
355 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
356 if (oldloc == NULL) {
357 return;
358 }
359
Victor Stinner94540602017-12-16 04:54:22 +0100360 const char *locale_override = getenv("LC_ALL");
361 if (locale_override == NULL || *locale_override == '\0') {
362 /* LC_ALL is also not set (or is set to an empty string) */
363 const _LocaleCoercionTarget *target = NULL;
364 for (target = _TARGET_LOCALES; target->locale_name; target++) {
365 const char *new_locale = setlocale(LC_CTYPE,
366 target->locale_name);
367 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100368#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100369defined(HAVE_LANGINFO_H) && defined(CODESET)
370 /* Also ensure that nl_langinfo works in this locale */
371 char *codeset = nl_langinfo(CODESET);
372 if (!codeset || *codeset == '\0') {
373 /* CODESET is not set or empty, so skip coercion */
374 new_locale = NULL;
375 _Py_SetLocaleFromEnv(LC_CTYPE);
376 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000377 }
Victor Stinner94540602017-12-16 04:54:22 +0100378#endif
379 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200380 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200381 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000382 }
383 }
384 }
385 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200386
387 setlocale(LC_CTYPE, oldloc);
388
389done:
390 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000391#endif
392}
393
xdegaye1588be62017-11-12 12:45:59 +0100394/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
395 * isolate the idiosyncrasies of different libc implementations. It reads the
396 * appropriate environment variable and uses its value to select the locale for
397 * 'category'. */
398char *
399_Py_SetLocaleFromEnv(int category)
400{
Victor Stinner353933e2018-11-23 13:08:26 +0100401 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100402#ifdef __ANDROID__
403 const char *locale;
404 const char **pvar;
405#ifdef PY_COERCE_C_LOCALE
406 const char *coerce_c_locale;
407#endif
408 const char *utf8_locale = "C.UTF-8";
409 const char *env_var_set[] = {
410 "LC_ALL",
411 "LC_CTYPE",
412 "LANG",
413 NULL,
414 };
415
416 /* Android setlocale(category, "") doesn't check the environment variables
417 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
418 * check the environment variables listed in env_var_set. */
419 for (pvar=env_var_set; *pvar; pvar++) {
420 locale = getenv(*pvar);
421 if (locale != NULL && *locale != '\0') {
422 if (strcmp(locale, utf8_locale) == 0 ||
423 strcmp(locale, "en_US.UTF-8") == 0) {
424 return setlocale(category, utf8_locale);
425 }
426 return setlocale(category, "C");
427 }
428 }
429
430 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
431 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
432 * Quote from POSIX section "8.2 Internationalization Variables":
433 * "4. If the LANG environment variable is not set or is set to the empty
434 * string, the implementation-defined default locale shall be used." */
435
436#ifdef PY_COERCE_C_LOCALE
437 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
438 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
439 /* Some other ported code may check the environment variables (e.g. in
440 * extension modules), so we make sure that they match the locale
441 * configuration */
442 if (setenv("LC_CTYPE", utf8_locale, 1)) {
443 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
444 "environment variable to %s\n", utf8_locale);
445 }
446 }
447#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100448 res = setlocale(category, utf8_locale);
449#else /* !defined(__ANDROID__) */
450 res = setlocale(category, "");
451#endif
452 _Py_ResetForceASCII();
453 return res;
xdegaye1588be62017-11-12 12:45:59 +0100454}
455
Nick Coghlan6ea41862017-06-11 13:16:15 +1000456
Eric Snow1abcf672017-05-23 21:46:51 -0700457/* Global initializations. Can be undone by Py_Finalize(). Don't
458 call this twice without an intervening Py_Finalize() call.
459
Victor Stinner1dc6e392018-07-25 02:49:17 +0200460 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700461 must have a corresponding call to Py_Finalize.
462
463 Locking: you must hold the interpreter lock while calling these APIs.
464 (If the lock has not yet been initialized, that's equivalent to
465 having the lock, but you cannot use multiple threads.)
466
467*/
468
Victor Stinner1dc6e392018-07-25 02:49:17 +0200469static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100470_Py_Initialize_ReconfigureCore(PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200471 const _PyCoreConfig *core_config)
472{
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100473 PyThreadState *tstate = _PyThreadState_GET();
474 if (!tstate) {
475 return _Py_INIT_ERR("failed to read thread state");
476 }
477
478 PyInterpreterState *interp = tstate->interp;
479 if (interp == NULL) {
480 return _Py_INIT_ERR("can't make main interpreter");
481 }
482 *interp_p = interp;
483
Victor Stinner1dc6e392018-07-25 02:49:17 +0200484 _PyCoreConfig_SetGlobalConfig(core_config);
485
486 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
487 return _Py_INIT_ERR("failed to copy core config");
488 }
489 core_config = &interp->core_config;
490
491 if (core_config->_install_importlib) {
492 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
493 if (_Py_INIT_FAILED(err)) {
494 return err;
495 }
496 }
497 return _Py_INIT_OK();
498}
499
500
Victor Stinner1dc6e392018-07-25 02:49:17 +0200501static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100502pycore_init_runtime(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000503{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200504 if (_PyRuntime.initialized) {
505 return _Py_INIT_ERR("main interpreter already initialized");
506 }
Victor Stinnerda273412017-12-15 01:46:02 +0100507
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200508 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000509
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100510 _PyInitError err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800511 if (_Py_INIT_FAILED(err)) {
512 return err;
513 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600514
Eric Snow1abcf672017-05-23 21:46:51 -0700515 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
516 * threads behave a little more gracefully at interpreter shutdown.
517 * We clobber it here so the new interpreter can start with a clean
518 * slate.
519 *
520 * However, this may still lead to misbehaviour if there are daemon
521 * threads still hanging around from a previous Py_Initialize/Finalize
522 * pair :(
523 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600524 _PyRuntime.finalizing = NULL;
525
Victor Stinnerda273412017-12-15 01:46:02 +0100526 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800527 if (_Py_INIT_FAILED(err)) {
528 return err;
529 }
530
Victor Stinnera7368ac2017-11-15 18:11:45 -0800531 err = _PyInterpreterState_Enable(&_PyRuntime);
532 if (_Py_INIT_FAILED(err)) {
533 return err;
534 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100535 return _Py_INIT_OK();
536}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800537
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100538
539static _PyInitError
540pycore_create_interpreter(const _PyCoreConfig *core_config,
541 PyInterpreterState **interp_p)
542{
543 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100544 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800545 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100546 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200547 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100548
549 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
550 return _Py_INIT_ERR("failed to copy core config");
551 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200552 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000553
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200554 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000555 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800556 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000557 (void) PyThreadState_Swap(tstate);
558
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000559 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000560 destroying the GIL might fail when it is being referenced from
561 another running thread (see issue #9901).
562 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000563 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000564 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100565
Nick Coghland6009512014-11-20 21:39:37 +1000566 /* Auto-thread-state API */
567 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000568
Victor Stinner2914bb32018-01-29 11:57:45 +0100569 /* Create the GIL */
570 PyEval_InitThreads();
571
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100572 return _Py_INIT_OK();
573}
Nick Coghland6009512014-11-20 21:39:37 +1000574
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100575
576static _PyInitError
577pycore_init_types(void)
578{
Victor Stinnerab672812019-01-23 15:04:40 +0100579 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100580 if (_Py_INIT_FAILED(err)) {
581 return err;
582 }
583
584 err = _PyUnicode_Init();
585 if (_Py_INIT_FAILED(err)) {
586 return err;
587 }
588
589 if (_PyStructSequence_Init() < 0) {
590 return _Py_INIT_ERR("can't initialize structseq");
591 }
592
593 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800594 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100595 }
Nick Coghland6009512014-11-20 21:39:37 +1000596
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100597 err = _PyExc_Init();
598 if (_Py_INIT_FAILED(err)) {
599 return err;
600 }
601
602 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800603 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100604 }
Nick Coghland6009512014-11-20 21:39:37 +1000605
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100606 if (!_PyContext_Init()) {
607 return _Py_INIT_ERR("can't init context");
608 }
609 return _Py_INIT_OK();
610}
611
612
613static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100614pycore_init_builtins(PyInterpreterState *interp)
615{
616 PyObject *bimod = _PyBuiltin_Init();
617 if (bimod == NULL) {
618 return _Py_INIT_ERR("can't initialize builtins modules");
619 }
620 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
621
622 interp->builtins = PyModule_GetDict(bimod);
623 if (interp->builtins == NULL) {
624 return _Py_INIT_ERR("can't initialize builtins dict");
625 }
626 Py_INCREF(interp->builtins);
627
628 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
629 if (_Py_INIT_FAILED(err)) {
630 return err;
631 }
632 return _Py_INIT_OK();
633}
634
635
636static _PyInitError
637pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
638{
639 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800640 if (_Py_INIT_FAILED(err)) {
641 return err;
642 }
Nick Coghland6009512014-11-20 21:39:37 +1000643
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800644 err = _PyImportHooks_Init();
645 if (_Py_INIT_FAILED(err)) {
646 return err;
647 }
Nick Coghland6009512014-11-20 21:39:37 +1000648
649 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100650 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100651 return _Py_INIT_ERR("can't initialize warnings");
652 }
Nick Coghland6009512014-11-20 21:39:37 +1000653
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100654 if (interp->core_config._install_importlib) {
655 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200656 if (_Py_INIT_FAILED(err)) {
657 return err;
658 }
659 }
660
Eric Snow1abcf672017-05-23 21:46:51 -0700661 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100662 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800663 err = initimport(interp, sysmod);
664 if (_Py_INIT_FAILED(err)) {
665 return err;
666 }
Eric Snow1abcf672017-05-23 21:46:51 -0700667 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100668 return _Py_INIT_OK();
669}
670
671
672static _PyInitError
673_Py_InitializeCore_impl(PyInterpreterState **interp_p,
674 const _PyCoreConfig *core_config)
675{
676 PyInterpreterState *interp;
677
678 _PyInitError err = pycore_init_runtime(core_config);
679 if (_Py_INIT_FAILED(err)) {
680 return err;
681 }
682
683 err = pycore_create_interpreter(core_config, &interp);
684 if (_Py_INIT_FAILED(err)) {
685 return err;
686 }
687 core_config = &interp->core_config;
688 *interp_p = interp;
689
690 err = pycore_init_types();
691 if (_Py_INIT_FAILED(err)) {
692 return err;
693 }
694
695 PyObject *sysmod;
Victor Stinnerab672812019-01-23 15:04:40 +0100696 err = _PySys_Create(interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100697 if (_Py_INIT_FAILED(err)) {
698 return err;
699 }
700
701 err = pycore_init_builtins(interp);
702 if (_Py_INIT_FAILED(err)) {
703 return err;
704 }
705
706 err = pycore_init_import_warnings(interp, sysmod);
707 if (_Py_INIT_FAILED(err)) {
708 return err;
709 }
Eric Snow1abcf672017-05-23 21:46:51 -0700710
711 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600712 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800713 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700714}
715
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100716
717static _PyInitError
718pyinit_preconfig(_PyPreConfig *preconfig, const _PyPreConfig *src_preconfig)
719{
Victor Stinnerc656e252019-03-06 01:13:43 +0100720 if (_PyPreConfig_Copy(preconfig, src_preconfig) < 0) {
721 return _Py_INIT_ERR("failed to copy pre config");
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100722 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100723
Victor Stinnerc656e252019-03-06 01:13:43 +0100724 _PyInitError err = _PyPreConfig_Read(preconfig);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100725 if (_Py_INIT_FAILED(err)) {
726 return err;
727 }
728
729 return _PyPreConfig_Write(preconfig);
730}
731
732
733static _PyInitError
734pyinit_coreconfig(_PyCoreConfig *config, const _PyCoreConfig *src_config,
735 PyInterpreterState **interp_p)
736{
Victor Stinnerc656e252019-03-06 01:13:43 +0100737 if (_PyCoreConfig_Copy(config, src_config) < 0) {
738 return _Py_INIT_ERR("failed to copy core config");
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100739 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100740
Victor Stinnerc656e252019-03-06 01:13:43 +0100741 _PyInitError err = _PyCoreConfig_Read(config, NULL);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100742 if (_Py_INIT_FAILED(err)) {
743 return err;
744 }
745
746 if (!_PyRuntime.core_initialized) {
747 return _Py_InitializeCore_impl(interp_p, config);
748 }
749 else {
750 return _Py_Initialize_ReconfigureCore(interp_p, config);
751 }
752}
753
754
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100755/* Begin interpreter initialization
756 *
757 * On return, the first thread and interpreter state have been created,
758 * but the compiler, signal handling, multithreading and
759 * multiple interpreter support, and codec infrastructure are not yet
760 * available.
761 *
762 * The import system will support builtin and frozen modules only.
763 * The only supported io is writing to sys.stderr
764 *
765 * If any operation invoked by this function fails, a fatal error is
766 * issued and the function does not return.
767 *
768 * Any code invoked from this function should *not* assume it has access
769 * to the Python C API (unless the API is explicitly listed as being
770 * safe to call without calling Py_Initialize first)
771 */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200772_PyInitError
773_Py_InitializeCore(PyInterpreterState **interp_p,
774 const _PyCoreConfig *src_config)
775{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200776 _PyInitError err;
777
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100778 assert(src_config != NULL);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200779
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100780 _PyCoreConfig local_config = _PyCoreConfig_INIT;
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200781
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100782 err = pyinit_preconfig(&local_config.preconfig, &src_config->preconfig);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200783 if (_Py_INIT_FAILED(err)) {
784 goto done;
785 }
786
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100787 err = pyinit_coreconfig(&local_config, src_config, interp_p);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200788
789done:
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100790 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200791 return err;
792}
793
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200794/* Py_Initialize() has already been called: update the main interpreter
795 configuration. Example of bpo-34008: Py_Main() called after
796 Py_Initialize(). */
797static _PyInitError
798_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
799 const _PyMainInterpreterConfig *config)
800{
801 if (config->argv != NULL) {
802 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
803 if (res < 0) {
804 return _Py_INIT_ERR("fail to set sys.argv");
805 }
806 }
807 return _Py_INIT_OK();
808}
809
Eric Snowc7ec9982017-05-23 23:00:52 -0700810/* Update interpreter state based on supplied configuration settings
811 *
812 * After calling this function, most of the restrictions on the interpreter
813 * are lifted. The only remaining incomplete settings are those related
814 * to the main module (sys.argv[0], __main__ metadata)
815 *
816 * Calling this when the interpreter is not initializing, is already
817 * initialized or without a valid current thread state is a fatal error.
818 * Other errors should be reported as normal Python exceptions with a
819 * non-zero return code.
820 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800821_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200822_Py_InitializeMainInterpreter(PyInterpreterState *interp,
823 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700824{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600825 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800826 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700827 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700828
Victor Stinner1dc6e392018-07-25 02:49:17 +0200829 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100830 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
831 return _Py_INIT_ERR("failed to copy main interpreter config");
832 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200833 config = &interp->config;
834 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700835
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200836 if (_PyRuntime.initialized) {
837 return _Py_ReconfigureMainInterpreter(interp, config);
838 }
839
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200840 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700841 /* Special mode for freeze_importlib: run with no import system
842 *
843 * This means anything which needs support from extension modules
844 * or pure Python code in the standard library won't work.
845 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600846 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800847 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700848 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100849
Victor Stinner33c377e2017-12-05 15:12:41 +0100850 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800851 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100852 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200853
Victor Stinnerab672812019-01-23 15:04:40 +0100854 if (_PySys_InitMain(interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800855 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100856 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800857
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200858 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800859 if (_Py_INIT_FAILED(err)) {
860 return err;
861 }
Nick Coghland6009512014-11-20 21:39:37 +1000862
863 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200864 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800865 if (_Py_INIT_FAILED(err)) {
866 return err;
867 }
Nick Coghland6009512014-11-20 21:39:37 +1000868
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800869 err = initfsencoding(interp);
870 if (_Py_INIT_FAILED(err)) {
871 return err;
872 }
Nick Coghland6009512014-11-20 21:39:37 +1000873
Victor Stinner1f151112017-11-23 10:43:14 +0100874 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800875 err = initsigs(); /* Signal handling stuff, including initintr() */
876 if (_Py_INIT_FAILED(err)) {
877 return err;
878 }
879 }
Nick Coghland6009512014-11-20 21:39:37 +1000880
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200881 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800882 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200883 }
Nick Coghland6009512014-11-20 21:39:37 +1000884
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800885 err = add_main_module(interp);
886 if (_Py_INIT_FAILED(err)) {
887 return err;
888 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800889
Victor Stinner91106cd2017-12-13 12:29:09 +0100890 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800891 if (_Py_INIT_FAILED(err)) {
892 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800893 }
Nick Coghland6009512014-11-20 21:39:37 +1000894
895 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100896 PyObject *warnoptions = PySys_GetObject("warnoptions");
897 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100898 {
Nick Coghland6009512014-11-20 21:39:37 +1000899 PyObject *warnings_module = PyImport_ImportModule("warnings");
900 if (warnings_module == NULL) {
901 fprintf(stderr, "'import warnings' failed; traceback:\n");
902 PyErr_Print();
903 }
904 Py_XDECREF(warnings_module);
905 }
906
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600907 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700908
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200909 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800910 err = initsite(); /* Module site */
911 if (_Py_INIT_FAILED(err)) {
912 return err;
913 }
914 }
Victor Stinnercf215042018-08-29 22:56:06 +0200915
916#ifndef MS_WINDOWS
917 _emit_stderr_warning_for_legacy_locale(core_config);
918#endif
919
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800920 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000921}
922
Eric Snowc7ec9982017-05-23 23:00:52 -0700923#undef _INIT_DEBUG_PRINT
924
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800925_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200926_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700927{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700928 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800929 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200930 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200932 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800933 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200934 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100935
Victor Stinner9cfc0022017-12-20 19:36:46 +0100936 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200937 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100938 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200939 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800940 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100941 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800942 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200943 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800944 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200945 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700946}
947
948
949void
Nick Coghland6009512014-11-20 21:39:37 +1000950Py_InitializeEx(int install_sigs)
951{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200952 if (_PyRuntime.initialized) {
953 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
954 return;
955 }
956
957 _PyInitError err;
958 _PyCoreConfig config = _PyCoreConfig_INIT;
959 config.install_signal_handlers = install_sigs;
960
961 err = _Py_InitializeFromConfig(&config);
962 _PyCoreConfig_Clear(&config);
963
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800964 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +0100965 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800966 }
Nick Coghland6009512014-11-20 21:39:37 +1000967}
968
969void
970Py_Initialize(void)
971{
972 Py_InitializeEx(1);
973}
974
975
976#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000977extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000978#endif
979
980/* Flush stdout and stderr */
981
982static int
983file_is_closed(PyObject *fobj)
984{
985 int r;
986 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
987 if (tmp == NULL) {
988 PyErr_Clear();
989 return 0;
990 }
991 r = PyObject_IsTrue(tmp);
992 Py_DECREF(tmp);
993 if (r < 0)
994 PyErr_Clear();
995 return r > 0;
996}
997
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000998static int
Nick Coghland6009512014-11-20 21:39:37 +1000999flush_std_files(void)
1000{
1001 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1002 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1003 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001004 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001005
1006 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001007 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001008 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001009 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001010 status = -1;
1011 }
Nick Coghland6009512014-11-20 21:39:37 +10001012 else
1013 Py_DECREF(tmp);
1014 }
1015
1016 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001017 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001018 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001019 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001020 status = -1;
1021 }
Nick Coghland6009512014-11-20 21:39:37 +10001022 else
1023 Py_DECREF(tmp);
1024 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001025
1026 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001027}
1028
1029/* Undo the effect of Py_Initialize().
1030
1031 Beware: if multiple interpreter and/or thread states exist, these
1032 are not wiped out; only the current thread and interpreter state
1033 are deleted. But since everything else is deleted, those other
1034 interpreter and thread states should no longer be used.
1035
1036 (XXX We should do better, e.g. wipe out all interpreters and
1037 threads.)
1038
1039 Locking: as above.
1040
1041*/
1042
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001043int
1044Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001045{
1046 PyInterpreterState *interp;
1047 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001048 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001049
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001050 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001051 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001052
Eric Snow842a2f02019-03-15 15:47:51 -06001053 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001054 wait_for_thread_shutdown();
1055
Marcel Plch776407f2017-12-20 11:17:58 +01001056 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001057 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001058 interp = tstate->interp;
1059
Eric Snow842a2f02019-03-15 15:47:51 -06001060 // Make any remaining pending calls.
1061 _Py_FinishPendingCalls();
1062
Nick Coghland6009512014-11-20 21:39:37 +10001063 /* The interpreter is still entirely intact at this point, and the
1064 * exit funcs may be relying on that. In particular, if some thread
1065 * or exit func is still waiting to do an import, the import machinery
1066 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001067 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001068 * Note that Threading.py uses an exit func to do a join on all the
1069 * threads created thru it, so this also protects pending imports in
1070 * the threads created via Threading.
1071 */
Nick Coghland6009512014-11-20 21:39:37 +10001072
Marcel Plch776407f2017-12-20 11:17:58 +01001073 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001074
Victor Stinnerda273412017-12-15 01:46:02 +01001075 /* Copy the core config, PyInterpreterState_Delete() free
1076 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001077#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001078 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001079#endif
1080#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001081 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001082#endif
1083#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001084 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001085#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001086
Nick Coghland6009512014-11-20 21:39:37 +10001087 /* Remaining threads (e.g. daemon threads) will automatically exit
1088 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001089 _PyRuntime.finalizing = tstate;
1090 _PyRuntime.initialized = 0;
1091 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001092
Victor Stinnere0deff32015-03-24 13:46:18 +01001093 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001094 if (flush_std_files() < 0) {
1095 status = -1;
1096 }
Nick Coghland6009512014-11-20 21:39:37 +10001097
1098 /* Disable signal handling */
1099 PyOS_FiniInterrupts();
1100
1101 /* Collect garbage. This may call finalizers; it's nice to call these
1102 * before all modules are destroyed.
1103 * XXX If a __del__ or weakref callback is triggered here, and tries to
1104 * XXX import a module, bad things can happen, because Python no
1105 * XXX longer believes it's initialized.
1106 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1107 * XXX is easy to provoke that way. I've also seen, e.g.,
1108 * XXX Exception exceptions.ImportError: 'No module named sha'
1109 * XXX in <function callback at 0x008F5718> ignored
1110 * XXX but I'm unclear on exactly how that one happens. In any case,
1111 * XXX I haven't seen a real-life report of either of these.
1112 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001113 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001114#ifdef COUNT_ALLOCS
1115 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1116 each collection might release some types from the type
1117 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001118 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001119 /* nothing */;
1120#endif
Eric Snowdae02762017-09-14 00:35:58 -07001121
Nick Coghland6009512014-11-20 21:39:37 +10001122 /* Destroy all modules */
1123 PyImport_Cleanup();
1124
Victor Stinnere0deff32015-03-24 13:46:18 +01001125 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001126 if (flush_std_files() < 0) {
1127 status = -1;
1128 }
Nick Coghland6009512014-11-20 21:39:37 +10001129
1130 /* Collect final garbage. This disposes of cycles created by
1131 * class definitions, for example.
1132 * XXX This is disabled because it caused too many problems. If
1133 * XXX a __del__ or weakref callback triggers here, Python code has
1134 * XXX a hard time running, because even the sys module has been
1135 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1136 * XXX One symptom is a sequence of information-free messages
1137 * XXX coming from threads (if a __del__ or callback is invoked,
1138 * XXX other threads can execute too, and any exception they encounter
1139 * XXX triggers a comedy of errors as subsystem after subsystem
1140 * XXX fails to find what it *expects* to find in sys to help report
1141 * XXX the exception and consequent unexpected failures). I've also
1142 * XXX seen segfaults then, after adding print statements to the
1143 * XXX Python code getting called.
1144 */
1145#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001146 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001147#endif
1148
1149 /* Disable tracemalloc after all Python objects have been destroyed,
1150 so it is possible to use tracemalloc in objects destructor. */
1151 _PyTraceMalloc_Fini();
1152
1153 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1154 _PyImport_Fini();
1155
1156 /* Cleanup typeobject.c's internal caches. */
1157 _PyType_Fini();
1158
1159 /* unload faulthandler module */
1160 _PyFaulthandler_Fini();
1161
1162 /* Debugging stuff */
1163#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001164 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001165#endif
1166 /* dump hash stats */
1167 _PyHash_Fini();
1168
Eric Snowdae02762017-09-14 00:35:58 -07001169#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001170 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001171 _PyDebug_PrintTotalRefs();
1172 }
Eric Snowdae02762017-09-14 00:35:58 -07001173#endif
Nick Coghland6009512014-11-20 21:39:37 +10001174
1175#ifdef Py_TRACE_REFS
1176 /* Display all objects still alive -- this can invoke arbitrary
1177 * __repr__ overrides, so requires a mostly-intact interpreter.
1178 * Alas, a lot of stuff may still be alive now that will be cleaned
1179 * up later.
1180 */
Victor Stinnerda273412017-12-15 01:46:02 +01001181 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001182 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001183 }
Nick Coghland6009512014-11-20 21:39:37 +10001184#endif /* Py_TRACE_REFS */
1185
1186 /* Clear interpreter state and all thread states. */
1187 PyInterpreterState_Clear(interp);
1188
1189 /* Now we decref the exception classes. After this point nothing
1190 can raise an exception. That's okay, because each Fini() method
1191 below has been checked to make sure no exceptions are ever
1192 raised.
1193 */
1194
1195 _PyExc_Fini();
1196
1197 /* Sundry finalizers */
1198 PyMethod_Fini();
1199 PyFrame_Fini();
1200 PyCFunction_Fini();
1201 PyTuple_Fini();
1202 PyList_Fini();
1203 PySet_Fini();
1204 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001205 PyLong_Fini();
1206 PyFloat_Fini();
1207 PyDict_Fini();
1208 PySlice_Fini();
1209 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001210 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001211 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001212 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001213 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001214
1215 /* Cleanup Unicode implementation */
1216 _PyUnicode_Fini();
1217
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001218 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001219
1220 /* XXX Still allocated:
1221 - various static ad-hoc pointers to interned strings
1222 - int and float free list blocks
1223 - whatever various modules and libraries allocate
1224 */
1225
1226 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1227
1228 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001229 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001230
1231 /* Delete current thread. After this, many C API calls become crashy. */
1232 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001233
Nick Coghland6009512014-11-20 21:39:37 +10001234 PyInterpreterState_Delete(interp);
1235
1236#ifdef Py_TRACE_REFS
1237 /* Display addresses (& refcnts) of all objects still alive.
1238 * An address can be used to find the repr of the object, printed
1239 * above by _Py_PrintReferences.
1240 */
Victor Stinnerda273412017-12-15 01:46:02 +01001241 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001242 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001243 }
Nick Coghland6009512014-11-20 21:39:37 +10001244#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001245#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001246 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001247 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001248 }
Nick Coghland6009512014-11-20 21:39:37 +10001249#endif
1250
1251 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001252
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001253 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001254 return status;
1255}
1256
1257void
1258Py_Finalize(void)
1259{
1260 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001261}
1262
1263/* Create and initialize a new interpreter and thread, and return the
1264 new thread. This requires that Py_Initialize() has been called
1265 first.
1266
1267 Unsuccessful initialization yields a NULL pointer. Note that *no*
1268 exception information is available even in this case -- the
1269 exception information is held in the thread, and there is no
1270 thread.
1271
1272 Locking: as above.
1273
1274*/
1275
Victor Stinnera7368ac2017-11-15 18:11:45 -08001276static _PyInitError
1277new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001278{
1279 PyInterpreterState *interp;
1280 PyThreadState *tstate, *save_tstate;
1281 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001282 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001283
Victor Stinnera7368ac2017-11-15 18:11:45 -08001284 if (!_PyRuntime.initialized) {
1285 return _Py_INIT_ERR("Py_Initialize must be called first");
1286 }
Nick Coghland6009512014-11-20 21:39:37 +10001287
Victor Stinner8a1be612016-03-14 22:07:55 +01001288 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1289 interpreters: disable PyGILState_Check(). */
1290 _PyGILState_check_enabled = 0;
1291
Nick Coghland6009512014-11-20 21:39:37 +10001292 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001293 if (interp == NULL) {
1294 *tstate_p = NULL;
1295 return _Py_INIT_OK();
1296 }
Nick Coghland6009512014-11-20 21:39:37 +10001297
1298 tstate = PyThreadState_New(interp);
1299 if (tstate == NULL) {
1300 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001301 *tstate_p = NULL;
1302 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001303 }
1304
1305 save_tstate = PyThreadState_Swap(tstate);
1306
Eric Snow1abcf672017-05-23 21:46:51 -07001307 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001308 _PyCoreConfig *core_config;
1309 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001310 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001311 core_config = &save_tstate->interp->core_config;
1312 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001313 } else {
1314 /* No current thread state, copy from the main interpreter */
1315 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001316 core_config = &main_interp->core_config;
1317 config = &main_interp->config;
1318 }
1319
1320 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1321 return _Py_INIT_ERR("failed to copy core config");
1322 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001323 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001324 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1325 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001326 }
1327
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001328 err = _PyExc_Init();
1329 if (_Py_INIT_FAILED(err)) {
1330 return err;
1331 }
1332
Nick Coghland6009512014-11-20 21:39:37 +10001333 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001334 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001335 if (modules == NULL) {
1336 return _Py_INIT_ERR("can't make modules dictionary");
1337 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001338 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001339
Eric Snowd393c1b2017-09-14 12:18:12 -06001340 sysmod = _PyImport_FindBuiltin("sys", modules);
1341 if (sysmod != NULL) {
1342 interp->sysdict = PyModule_GetDict(sysmod);
1343 if (interp->sysdict == NULL)
1344 goto handle_error;
1345 Py_INCREF(interp->sysdict);
1346 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerab672812019-01-23 15:04:40 +01001347 if (_PySys_InitMain(interp) < 0) {
1348 return _Py_INIT_ERR("can't finish initializing sys");
1349 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001350 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001351 else if (PyErr_Occurred()) {
1352 goto handle_error;
1353 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001354
1355 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001356 if (bimod != NULL) {
1357 interp->builtins = PyModule_GetDict(bimod);
1358 if (interp->builtins == NULL)
1359 goto handle_error;
1360 Py_INCREF(interp->builtins);
1361 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001362 else if (PyErr_Occurred()) {
1363 goto handle_error;
1364 }
Nick Coghland6009512014-11-20 21:39:37 +10001365
Nick Coghland6009512014-11-20 21:39:37 +10001366 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001367 err = _PyBuiltins_AddExceptions(bimod);
1368 if (_Py_INIT_FAILED(err)) {
1369 return err;
1370 }
Nick Coghland6009512014-11-20 21:39:37 +10001371
Victor Stinnerab672812019-01-23 15:04:40 +01001372 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1373 if (_Py_INIT_FAILED(err)) {
1374 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001375 }
Nick Coghland6009512014-11-20 21:39:37 +10001376
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001377 err = _PyImportHooks_Init();
1378 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001379 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001380 }
Nick Coghland6009512014-11-20 21:39:37 +10001381
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001382 err = initimport(interp, sysmod);
1383 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001384 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001385 }
Nick Coghland6009512014-11-20 21:39:37 +10001386
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001387 err = initexternalimport(interp);
1388 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001389 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001390 }
Nick Coghland6009512014-11-20 21:39:37 +10001391
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001392 err = initfsencoding(interp);
1393 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001394 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001395 }
1396
Victor Stinner91106cd2017-12-13 12:29:09 +01001397 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001398 if (_Py_INIT_FAILED(err)) {
1399 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001400 }
1401
1402 err = add_main_module(interp);
1403 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001404 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001405 }
1406
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001407 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001408 err = initsite();
1409 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001410 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001411 }
1412 }
Nick Coghland6009512014-11-20 21:39:37 +10001413 }
1414
Victor Stinnera7368ac2017-11-15 18:11:45 -08001415 if (PyErr_Occurred()) {
1416 goto handle_error;
1417 }
Nick Coghland6009512014-11-20 21:39:37 +10001418
Victor Stinnera7368ac2017-11-15 18:11:45 -08001419 *tstate_p = tstate;
1420 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001421
Nick Coghland6009512014-11-20 21:39:37 +10001422handle_error:
1423 /* Oops, it didn't work. Undo it all. */
1424
1425 PyErr_PrintEx(0);
1426 PyThreadState_Clear(tstate);
1427 PyThreadState_Swap(save_tstate);
1428 PyThreadState_Delete(tstate);
1429 PyInterpreterState_Delete(interp);
1430
Victor Stinnera7368ac2017-11-15 18:11:45 -08001431 *tstate_p = NULL;
1432 return _Py_INIT_OK();
1433}
1434
1435PyThreadState *
1436Py_NewInterpreter(void)
1437{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001438 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001439 _PyInitError err = new_interpreter(&tstate);
1440 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001441 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001442 }
1443 return tstate;
1444
Nick Coghland6009512014-11-20 21:39:37 +10001445}
1446
1447/* Delete an interpreter and its last thread. This requires that the
1448 given thread state is current, that the thread has no remaining
1449 frames, and that it is its interpreter's only remaining thread.
1450 It is a fatal error to violate these constraints.
1451
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001452 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001453 everything, regardless.)
1454
1455 Locking: as above.
1456
1457*/
1458
1459void
1460Py_EndInterpreter(PyThreadState *tstate)
1461{
1462 PyInterpreterState *interp = tstate->interp;
1463
Victor Stinner50b48572018-11-01 01:51:40 +01001464 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001465 Py_FatalError("Py_EndInterpreter: thread is not current");
1466 if (tstate->frame != NULL)
1467 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001468 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001469
Eric Snow842a2f02019-03-15 15:47:51 -06001470 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001471 wait_for_thread_shutdown();
1472
Marcel Plch776407f2017-12-20 11:17:58 +01001473 call_py_exitfuncs(interp);
1474
Nick Coghland6009512014-11-20 21:39:37 +10001475 if (tstate != interp->tstate_head || tstate->next != NULL)
1476 Py_FatalError("Py_EndInterpreter: not the last thread");
1477
1478 PyImport_Cleanup();
1479 PyInterpreterState_Clear(interp);
1480 PyThreadState_Swap(NULL);
1481 PyInterpreterState_Delete(interp);
1482}
1483
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001484/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001485
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001486static _PyInitError
1487add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001488{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001489 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001490 m = PyImport_AddModule("__main__");
1491 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001492 return _Py_INIT_ERR("can't create __main__ module");
1493
Nick Coghland6009512014-11-20 21:39:37 +10001494 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001495 ann_dict = PyDict_New();
1496 if ((ann_dict == NULL) ||
1497 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001499 }
1500 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001501
Nick Coghland6009512014-11-20 21:39:37 +10001502 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1503 PyObject *bimod = PyImport_ImportModule("builtins");
1504 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001505 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001506 }
1507 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001508 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001509 }
1510 Py_DECREF(bimod);
1511 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001512
Nick Coghland6009512014-11-20 21:39:37 +10001513 /* Main is a little special - imp.is_builtin("__main__") will return
1514 * False, but BuiltinImporter is still the most appropriate initial
1515 * setting for its __loader__ attribute. A more suitable value will
1516 * be set if __main__ gets further initialized later in the startup
1517 * process.
1518 */
1519 loader = PyDict_GetItemString(d, "__loader__");
1520 if (loader == NULL || loader == Py_None) {
1521 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1522 "BuiltinImporter");
1523 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001525 }
1526 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001527 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001528 }
1529 Py_DECREF(loader);
1530 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001531 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001532}
1533
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001534static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001535initfsencoding(PyInterpreterState *interp)
1536{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001537 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001538
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001539 char *encoding = get_codec_name(config->filesystem_encoding);
1540 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001541 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001542 memory, import a module of the standard library failed, etc. */
1543 return _Py_INIT_ERR("failed to get the Python codec "
1544 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001545 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001546
1547 /* Update the filesystem encoding to the normalized Python codec name.
1548 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1549 (Python codec name). */
1550 PyMem_RawFree(config->filesystem_encoding);
1551 config->filesystem_encoding = encoding;
1552
1553 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1554 global configuration variables. */
1555 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1556 config->filesystem_errors) < 0) {
1557 return _Py_INIT_NO_MEMORY();
1558 }
1559
1560 /* PyUnicode can now use the Python codec rather than C implementation
1561 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001562 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001563 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001564}
1565
1566/* Import the site module (not into __main__ though) */
1567
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001568static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001569initsite(void)
1570{
1571 PyObject *m;
1572 m = PyImport_ImportModule("site");
1573 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001574 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001575 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001576 Py_DECREF(m);
1577 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001578}
1579
Victor Stinner874dbe82015-09-04 17:29:57 +02001580/* Check if a file descriptor is valid or not.
1581 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1582static int
1583is_valid_fd(int fd)
1584{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001585#ifdef __APPLE__
1586 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1587 and the other side of the pipe is closed, dup(1) succeed, whereas
1588 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1589 such error. */
1590 struct stat st;
1591 return (fstat(fd, &st) == 0);
1592#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001593 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001594 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001595 return 0;
1596 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001597 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1598 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1599 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001600 fd2 = dup(fd);
1601 if (fd2 >= 0)
1602 close(fd2);
1603 _Py_END_SUPPRESS_IPH
1604 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001605#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001606}
1607
1608/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001609static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001610create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001611 int fd, int write_mode, const char* name,
1612 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001613{
1614 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1615 const char* mode;
1616 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001617 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001618 int buffering, isatty;
1619 _Py_IDENTIFIER(open);
1620 _Py_IDENTIFIER(isatty);
1621 _Py_IDENTIFIER(TextIOWrapper);
1622 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001623 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001624
Victor Stinner874dbe82015-09-04 17:29:57 +02001625 if (!is_valid_fd(fd))
1626 Py_RETURN_NONE;
1627
Nick Coghland6009512014-11-20 21:39:37 +10001628 /* stdin is always opened in buffered mode, first because it shouldn't
1629 make a difference in common use cases, second because TextIOWrapper
1630 depends on the presence of a read1() method which only exists on
1631 buffered streams.
1632 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001633 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001634 buffering = 0;
1635 else
1636 buffering = -1;
1637 if (write_mode)
1638 mode = "wb";
1639 else
1640 mode = "rb";
1641 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1642 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001643 Py_None, Py_None, /* encoding, errors */
1644 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001645 if (buf == NULL)
1646 goto error;
1647
1648 if (buffering) {
1649 _Py_IDENTIFIER(raw);
1650 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1651 if (raw == NULL)
1652 goto error;
1653 }
1654 else {
1655 raw = buf;
1656 Py_INCREF(raw);
1657 }
1658
Steve Dower39294992016-08-30 21:22:36 -07001659#ifdef MS_WINDOWS
1660 /* Windows console IO is always UTF-8 encoded */
1661 if (PyWindowsConsoleIO_Check(raw))
1662 encoding = "utf-8";
1663#endif
1664
Nick Coghland6009512014-11-20 21:39:37 +10001665 text = PyUnicode_FromString(name);
1666 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1667 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001668 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001669 if (res == NULL)
1670 goto error;
1671 isatty = PyObject_IsTrue(res);
1672 Py_DECREF(res);
1673 if (isatty == -1)
1674 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001675 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001676 write_through = Py_True;
1677 else
1678 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001679 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001680 line_buffering = Py_True;
1681 else
1682 line_buffering = Py_False;
1683
1684 Py_CLEAR(raw);
1685 Py_CLEAR(text);
1686
1687#ifdef MS_WINDOWS
1688 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1689 newlines to "\n".
1690 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1691 newline = NULL;
1692#else
1693 /* sys.stdin: split lines at "\n".
1694 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1695 newline = "\n";
1696#endif
1697
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001698 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001699 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001700 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001701 Py_CLEAR(buf);
1702 if (stream == NULL)
1703 goto error;
1704
1705 if (write_mode)
1706 mode = "w";
1707 else
1708 mode = "r";
1709 text = PyUnicode_FromString(mode);
1710 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1711 goto error;
1712 Py_CLEAR(text);
1713 return stream;
1714
1715error:
1716 Py_XDECREF(buf);
1717 Py_XDECREF(stream);
1718 Py_XDECREF(text);
1719 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001720
Victor Stinner874dbe82015-09-04 17:29:57 +02001721 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1722 /* Issue #24891: the file descriptor was closed after the first
1723 is_valid_fd() check was called. Ignore the OSError and set the
1724 stream to None. */
1725 PyErr_Clear();
1726 Py_RETURN_NONE;
1727 }
1728 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001729}
1730
1731/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001732static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001733init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001734{
1735 PyObject *iomod = NULL, *wrapper;
1736 PyObject *bimod = NULL;
1737 PyObject *m;
1738 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001739 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001740 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001741 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001742 _PyCoreConfig *config = &interp->core_config;
1743
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001744 /* Check that stdin is not a directory
1745 Using shell redirection, you can redirect stdin to a directory,
1746 crashing the Python interpreter. Catch this common mistake here
1747 and output a useful error message. Note that under MS Windows,
1748 the shell already prevents that. */
1749#ifndef MS_WINDOWS
1750 struct _Py_stat_struct sb;
1751 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1752 S_ISDIR(sb.st_mode)) {
1753 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1754 "cannot continue");
1755 }
1756#endif
1757
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001758 char *codec_name = get_codec_name(config->stdio_encoding);
1759 if (codec_name == NULL) {
1760 return _Py_INIT_ERR("failed to get the Python codec name "
1761 "of the stdio encoding");
1762 }
1763 PyMem_RawFree(config->stdio_encoding);
1764 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001765
1766 /* Hack to avoid a nasty recursion issue when Python is invoked
1767 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1768 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1769 goto error;
1770 }
1771 Py_DECREF(m);
1772
1773 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1774 goto error;
1775 }
1776 Py_DECREF(m);
1777
1778 if (!(bimod = PyImport_ImportModule("builtins"))) {
1779 goto error;
1780 }
1781
1782 if (!(iomod = PyImport_ImportModule("io"))) {
1783 goto error;
1784 }
1785 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1786 goto error;
1787 }
1788
1789 /* Set builtins.open */
1790 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1791 Py_DECREF(wrapper);
1792 goto error;
1793 }
1794 Py_DECREF(wrapper);
1795
Nick Coghland6009512014-11-20 21:39:37 +10001796 /* Set sys.stdin */
1797 fd = fileno(stdin);
1798 /* Under some conditions stdin, stdout and stderr may not be connected
1799 * and fileno() may point to an invalid file descriptor. For example
1800 * GUI apps don't have valid standard streams by default.
1801 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001802 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001803 config->stdio_encoding,
1804 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001805 if (std == NULL)
1806 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001807 PySys_SetObject("__stdin__", std);
1808 _PySys_SetObjectId(&PyId_stdin, std);
1809 Py_DECREF(std);
1810
1811 /* Set sys.stdout */
1812 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001813 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001814 config->stdio_encoding,
1815 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001816 if (std == NULL)
1817 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001818 PySys_SetObject("__stdout__", std);
1819 _PySys_SetObjectId(&PyId_stdout, std);
1820 Py_DECREF(std);
1821
1822#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1823 /* Set sys.stderr, replaces the preliminary stderr */
1824 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001825 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001826 config->stdio_encoding,
1827 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001828 if (std == NULL)
1829 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001830
1831 /* Same as hack above, pre-import stderr's codec to avoid recursion
1832 when import.c tries to write to stderr in verbose mode. */
1833 encoding_attr = PyObject_GetAttrString(std, "encoding");
1834 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001835 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001836 if (std_encoding != NULL) {
1837 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1838 Py_XDECREF(codec_info);
1839 }
1840 Py_DECREF(encoding_attr);
1841 }
1842 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1843
1844 if (PySys_SetObject("__stderr__", std) < 0) {
1845 Py_DECREF(std);
1846 goto error;
1847 }
1848 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1849 Py_DECREF(std);
1850 goto error;
1851 }
1852 Py_DECREF(std);
1853#endif
1854
Victor Stinnera7368ac2017-11-15 18:11:45 -08001855 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001856
Victor Stinnera7368ac2017-11-15 18:11:45 -08001857error:
1858 res = _Py_INIT_ERR("can't initialize sys standard streams");
1859
1860done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001861 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001862
Nick Coghland6009512014-11-20 21:39:37 +10001863 Py_XDECREF(bimod);
1864 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001865 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001866}
1867
1868
Victor Stinner10dc4842015-03-24 12:01:30 +01001869static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001870_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001871{
Victor Stinner10dc4842015-03-24 12:01:30 +01001872 fputc('\n', stderr);
1873 fflush(stderr);
1874
1875 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001876 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001877}
Victor Stinner791da1c2016-03-14 16:53:12 +01001878
1879/* Print the current exception (if an exception is set) with its traceback,
1880 or display the current Python stack.
1881
1882 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1883 called on catastrophic cases.
1884
1885 Return 1 if the traceback was displayed, 0 otherwise. */
1886
1887static int
1888_Py_FatalError_PrintExc(int fd)
1889{
1890 PyObject *ferr, *res;
1891 PyObject *exception, *v, *tb;
1892 int has_tb;
1893
Victor Stinner791da1c2016-03-14 16:53:12 +01001894 PyErr_Fetch(&exception, &v, &tb);
1895 if (exception == NULL) {
1896 /* No current exception */
1897 return 0;
1898 }
1899
1900 ferr = _PySys_GetObjectId(&PyId_stderr);
1901 if (ferr == NULL || ferr == Py_None) {
1902 /* sys.stderr is not set yet or set to None,
1903 no need to try to display the exception */
1904 return 0;
1905 }
1906
1907 PyErr_NormalizeException(&exception, &v, &tb);
1908 if (tb == NULL) {
1909 tb = Py_None;
1910 Py_INCREF(tb);
1911 }
1912 PyException_SetTraceback(v, tb);
1913 if (exception == NULL) {
1914 /* PyErr_NormalizeException() failed */
1915 return 0;
1916 }
1917
1918 has_tb = (tb != Py_None);
1919 PyErr_Display(exception, v, tb);
1920 Py_XDECREF(exception);
1921 Py_XDECREF(v);
1922 Py_XDECREF(tb);
1923
1924 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001925 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001926 if (res == NULL)
1927 PyErr_Clear();
1928 else
1929 Py_DECREF(res);
1930
1931 return has_tb;
1932}
1933
Nick Coghland6009512014-11-20 21:39:37 +10001934/* Print fatal error message and abort */
1935
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001936#ifdef MS_WINDOWS
1937static void
1938fatal_output_debug(const char *msg)
1939{
1940 /* buffer of 256 bytes allocated on the stack */
1941 WCHAR buffer[256 / sizeof(WCHAR)];
1942 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1943 size_t msglen;
1944
1945 OutputDebugStringW(L"Fatal Python error: ");
1946
1947 msglen = strlen(msg);
1948 while (msglen) {
1949 size_t i;
1950
1951 if (buflen > msglen) {
1952 buflen = msglen;
1953 }
1954
1955 /* Convert the message to wchar_t. This uses a simple one-to-one
1956 conversion, assuming that the this error message actually uses
1957 ASCII only. If this ceases to be true, we will have to convert. */
1958 for (i=0; i < buflen; ++i) {
1959 buffer[i] = msg[i];
1960 }
1961 buffer[i] = L'\0';
1962 OutputDebugStringW(buffer);
1963
1964 msg += buflen;
1965 msglen -= buflen;
1966 }
1967 OutputDebugStringW(L"\n");
1968}
1969#endif
1970
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001971static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001972fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001973{
1974 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001975 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001976
1977 if (reentrant) {
1978 /* Py_FatalError() caused a second fatal error.
1979 Example: flush_std_files() raises a recursion error. */
1980 goto exit;
1981 }
1982 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001983
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001984 fprintf(stderr, "Fatal Python error: ");
1985 if (prefix) {
1986 fputs(prefix, stderr);
1987 fputs(": ", stderr);
1988 }
1989 if (msg) {
1990 fputs(msg, stderr);
1991 }
1992 else {
1993 fprintf(stderr, "<message not set>");
1994 }
1995 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001996 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001997
Victor Stinner3a228ab2018-11-01 00:26:41 +01001998 /* Check if the current thread has a Python thread state
1999 and holds the GIL */
2000 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2001 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002002 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002003 if (tss_tstate != tstate) {
2004 /* The Python thread does not hold the GIL */
2005 tss_tstate = NULL;
2006 }
2007 }
2008 else {
2009 /* Py_FatalError() has been called from a C thread
2010 which has no Python thread state. */
2011 }
2012 int has_tstate_and_gil = (tss_tstate != NULL);
2013
2014 if (has_tstate_and_gil) {
2015 /* If an exception is set, print the exception with its traceback */
2016 if (!_Py_FatalError_PrintExc(fd)) {
2017 /* No exception is set, or an exception is set without traceback */
2018 _Py_FatalError_DumpTracebacks(fd);
2019 }
2020 }
2021 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002022 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002023 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002024
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002025 /* The main purpose of faulthandler is to display the traceback.
2026 This function already did its best to display a traceback.
2027 Disable faulthandler to prevent writing a second traceback
2028 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002029 _PyFaulthandler_Fini();
2030
Victor Stinner791da1c2016-03-14 16:53:12 +01002031 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002032 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002033 /* Flush sys.stdout and sys.stderr */
2034 flush_std_files();
2035 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002036
Nick Coghland6009512014-11-20 21:39:37 +10002037#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002038 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002039#endif /* MS_WINDOWS */
2040
2041exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002042 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002043#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002044 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002045#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002046 abort();
2047 }
2048 else {
2049 exit(status);
2050 }
2051}
2052
Victor Stinner19760862017-12-20 01:41:59 +01002053void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002054Py_FatalError(const char *msg)
2055{
2056 fatal_error(NULL, msg, -1);
2057}
2058
Victor Stinner19760862017-12-20 01:41:59 +01002059void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002060_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002061{
Victor Stinnerdfe88472019-03-01 12:14:41 +01002062 if (err.exitcode >= 0) {
2063 exit(err.exitcode);
2064 }
2065 else {
2066 /* On "user" error: exit with status 1.
2067 For all other errors, call abort(). */
2068 int status = err.user_err ? 1 : -1;
2069 fatal_error(err.prefix, err.msg, status);
2070 }
Nick Coghland6009512014-11-20 21:39:37 +10002071}
2072
2073/* Clean up and exit */
2074
Victor Stinnerd7292b52016-06-17 12:29:00 +02002075# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002076
Nick Coghland6009512014-11-20 21:39:37 +10002077/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002078void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002079{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002080 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002081
Antoine Pitroufc5db952017-12-13 02:29:07 +01002082 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002083 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2084
2085 is->pyexitfunc = func;
2086 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002087}
2088
2089static void
Marcel Plch776407f2017-12-20 11:17:58 +01002090call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002091{
Marcel Plch776407f2017-12-20 11:17:58 +01002092 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002093 return;
2094
Marcel Plch776407f2017-12-20 11:17:58 +01002095 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002096 PyErr_Clear();
2097}
2098
2099/* Wait until threading._shutdown completes, provided
2100 the threading module was imported in the first place.
2101 The shutdown routine will wait until all non-daemon
2102 "threading" threads have completed. */
2103static void
2104wait_for_thread_shutdown(void)
2105{
Nick Coghland6009512014-11-20 21:39:37 +10002106 _Py_IDENTIFIER(_shutdown);
2107 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002108 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002109 if (threading == NULL) {
2110 /* threading not imported */
2111 PyErr_Clear();
2112 return;
2113 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002114 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002115 if (result == NULL) {
2116 PyErr_WriteUnraisable(threading);
2117 }
2118 else {
2119 Py_DECREF(result);
2120 }
2121 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002122}
2123
2124#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002125int Py_AtExit(void (*func)(void))
2126{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002127 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002128 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002129 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002130 return 0;
2131}
2132
2133static void
2134call_ll_exitfuncs(void)
2135{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002136 while (_PyRuntime.nexitfuncs > 0)
2137 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002138
2139 fflush(stdout);
2140 fflush(stderr);
2141}
2142
Victor Stinnercfc88312018-08-01 16:41:25 +02002143void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002144Py_Exit(int sts)
2145{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002146 if (Py_FinalizeEx() < 0) {
2147 sts = 120;
2148 }
Nick Coghland6009512014-11-20 21:39:37 +10002149
2150 exit(sts);
2151}
2152
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002153static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002154initsigs(void)
2155{
2156#ifdef SIGPIPE
2157 PyOS_setsig(SIGPIPE, SIG_IGN);
2158#endif
2159#ifdef SIGXFZ
2160 PyOS_setsig(SIGXFZ, SIG_IGN);
2161#endif
2162#ifdef SIGXFSZ
2163 PyOS_setsig(SIGXFSZ, SIG_IGN);
2164#endif
2165 PyOS_InitInterrupts(); /* May imply initsignal() */
2166 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002167 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002168 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002169 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002170}
2171
2172
2173/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2174 *
2175 * All of the code in this function must only use async-signal-safe functions,
2176 * listed at `man 7 signal` or
2177 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2178 */
2179void
2180_Py_RestoreSignals(void)
2181{
2182#ifdef SIGPIPE
2183 PyOS_setsig(SIGPIPE, SIG_DFL);
2184#endif
2185#ifdef SIGXFZ
2186 PyOS_setsig(SIGXFZ, SIG_DFL);
2187#endif
2188#ifdef SIGXFSZ
2189 PyOS_setsig(SIGXFSZ, SIG_DFL);
2190#endif
2191}
2192
2193
2194/*
2195 * The file descriptor fd is considered ``interactive'' if either
2196 * a) isatty(fd) is TRUE, or
2197 * b) the -i flag was given, and the filename associated with
2198 * the descriptor is NULL or "<stdin>" or "???".
2199 */
2200int
2201Py_FdIsInteractive(FILE *fp, const char *filename)
2202{
2203 if (isatty((int)fileno(fp)))
2204 return 1;
2205 if (!Py_InteractiveFlag)
2206 return 0;
2207 return (filename == NULL) ||
2208 (strcmp(filename, "<stdin>") == 0) ||
2209 (strcmp(filename, "???") == 0);
2210}
2211
2212
Nick Coghland6009512014-11-20 21:39:37 +10002213/* Wrappers around sigaction() or signal(). */
2214
2215PyOS_sighandler_t
2216PyOS_getsig(int sig)
2217{
2218#ifdef HAVE_SIGACTION
2219 struct sigaction context;
2220 if (sigaction(sig, NULL, &context) == -1)
2221 return SIG_ERR;
2222 return context.sa_handler;
2223#else
2224 PyOS_sighandler_t handler;
2225/* Special signal handling for the secure CRT in Visual Studio 2005 */
2226#if defined(_MSC_VER) && _MSC_VER >= 1400
2227 switch (sig) {
2228 /* Only these signals are valid */
2229 case SIGINT:
2230 case SIGILL:
2231 case SIGFPE:
2232 case SIGSEGV:
2233 case SIGTERM:
2234 case SIGBREAK:
2235 case SIGABRT:
2236 break;
2237 /* Don't call signal() with other values or it will assert */
2238 default:
2239 return SIG_ERR;
2240 }
2241#endif /* _MSC_VER && _MSC_VER >= 1400 */
2242 handler = signal(sig, SIG_IGN);
2243 if (handler != SIG_ERR)
2244 signal(sig, handler);
2245 return handler;
2246#endif
2247}
2248
2249/*
2250 * All of the code in this function must only use async-signal-safe functions,
2251 * listed at `man 7 signal` or
2252 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2253 */
2254PyOS_sighandler_t
2255PyOS_setsig(int sig, PyOS_sighandler_t handler)
2256{
2257#ifdef HAVE_SIGACTION
2258 /* Some code in Modules/signalmodule.c depends on sigaction() being
2259 * used here if HAVE_SIGACTION is defined. Fix that if this code
2260 * changes to invalidate that assumption.
2261 */
2262 struct sigaction context, ocontext;
2263 context.sa_handler = handler;
2264 sigemptyset(&context.sa_mask);
2265 context.sa_flags = 0;
2266 if (sigaction(sig, &context, &ocontext) == -1)
2267 return SIG_ERR;
2268 return ocontext.sa_handler;
2269#else
2270 PyOS_sighandler_t oldhandler;
2271 oldhandler = signal(sig, handler);
2272#ifdef HAVE_SIGINTERRUPT
2273 siginterrupt(sig, 1);
2274#endif
2275 return oldhandler;
2276#endif
2277}
2278
2279#ifdef __cplusplus
2280}
2281#endif