blob: 08107296be0658cd13821401d41751142c1ff06f [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;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060072
Victor Stinnerf7e5b562017-11-15 15:48:08 -080073_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060074_PyRuntime_Initialize(void)
75{
76 /* XXX We only initialize once in the process, which aligns with
77 the static initialization of the former globals now found in
78 _PyRuntime. However, _PyRuntime *should* be initialized with
79 every Py_Initialize() call, but doing so breaks the runtime.
80 This is because the runtime state is not properly finalized
81 currently. */
82 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080083 if (initialized) {
84 return _Py_INIT_OK();
85 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086 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);
95}
96
97int
98_Py_IsFinalizing(void)
99{
100 return _PyRuntime.finalizing != NULL;
101}
102
Nick Coghland6009512014-11-20 21:39:37 +1000103/* Hack to force loading of object files */
104int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
105 PyOS_mystrnicmp; /* Python/pystrcmp.o */
106
107/* PyModule_GetWarningsModule is no longer necessary as of 2.6
108since _warnings is builtin. This API should not be used. */
109PyObject *
110PyModule_GetWarningsModule(void)
111{
112 return PyImport_ImportModule("warnings");
113}
114
Eric Snowc7ec9982017-05-23 23:00:52 -0700115
Eric Snow1abcf672017-05-23 21:46:51 -0700116/* APIs to access the initialization flags
117 *
118 * Can be called prior to Py_Initialize.
119 */
Nick Coghland6009512014-11-20 21:39:37 +1000120
Eric Snow1abcf672017-05-23 21:46:51 -0700121int
122_Py_IsCoreInitialized(void)
123{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600124 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700125}
Nick Coghland6009512014-11-20 21:39:37 +1000126
127int
128Py_IsInitialized(void)
129{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600130 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000131}
132
Nick Coghlan6ea41862017-06-11 13:16:15 +1000133
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000134/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
135 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000136 initializations fail, a fatal error is issued and the function does
137 not return. On return, the first thread and interpreter state have
138 been created.
139
140 Locking: you must hold the interpreter lock while calling this.
141 (If the lock has not yet been initialized, that's equivalent to
142 having the lock, but you cannot use multiple threads.)
143
144*/
145
Nick Coghland6009512014-11-20 21:39:37 +1000146static char*
147get_codec_name(const char *encoding)
148{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200149 const char *name_utf8;
150 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000151 PyObject *codec, *name = NULL;
152
153 codec = _PyCodec_Lookup(encoding);
154 if (!codec)
155 goto error;
156
157 name = _PyObject_GetAttrId(codec, &PyId_name);
158 Py_CLEAR(codec);
159 if (!name)
160 goto error;
161
Serhiy Storchaka06515832016-11-20 09:13:07 +0200162 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000163 if (name_utf8 == NULL)
164 goto error;
165 name_str = _PyMem_RawStrdup(name_utf8);
166 Py_DECREF(name);
167 if (name_str == NULL) {
168 PyErr_NoMemory();
169 return NULL;
170 }
171 return name_str;
172
173error:
174 Py_XDECREF(codec);
175 Py_XDECREF(name);
176 return NULL;
177}
178
Nick Coghland6009512014-11-20 21:39:37 +1000179
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800180static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700181initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000182{
183 PyObject *importlib;
184 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000185 PyObject *value;
186
187 /* Import _importlib through its frozen version, _frozen_importlib. */
188 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800189 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000190 }
191 else if (Py_VerboseFlag) {
192 PySys_FormatStderr("import _frozen_importlib # frozen\n");
193 }
194 importlib = PyImport_AddModule("_frozen_importlib");
195 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800196 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000197 }
198 interp->importlib = importlib;
199 Py_INCREF(interp->importlib);
200
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300201 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
202 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800203 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300204 Py_INCREF(interp->import_func);
205
Victor Stinnercd6e6942015-09-18 09:11:57 +0200206 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800207 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000208 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800209 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000210 }
211 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200212 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000213 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600214 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800215 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000216 }
217
Victor Stinnercd6e6942015-09-18 09:11:57 +0200218 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000219 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
220 if (value == NULL) {
221 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800222 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000223 }
224 Py_DECREF(value);
225 Py_DECREF(impmod);
226
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800227 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000228}
229
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800230static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700231initexternalimport(PyInterpreterState *interp)
232{
233 PyObject *value;
234 value = PyObject_CallMethod(interp->importlib,
235 "_install_external_importers", "");
236 if (value == NULL) {
237 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800238 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700239 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200240 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300241 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700242}
Nick Coghland6009512014-11-20 21:39:37 +1000243
Nick Coghlan6ea41862017-06-11 13:16:15 +1000244/* Helper functions to better handle the legacy C locale
245 *
246 * The legacy C locale assumes ASCII as the default text encoding, which
247 * causes problems not only for the CPython runtime, but also other
248 * components like GNU readline.
249 *
250 * Accordingly, when the CLI detects it, it attempts to coerce it to a
251 * more capable UTF-8 based alternative as follows:
252 *
253 * if (_Py_LegacyLocaleDetected()) {
254 * _Py_CoerceLegacyLocale();
255 * }
256 *
257 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
258 *
259 * Locale coercion also impacts the default error handler for the standard
260 * streams: while the usual default is "strict", the default for the legacy
261 * C locale and for any of the coercion target locales is "surrogateescape".
262 */
263
264int
265_Py_LegacyLocaleDetected(void)
266{
267#ifndef MS_WINDOWS
268 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000269 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
270 * the POSIX locale as a simple alias for the C locale, so
271 * we may also want to check for that explicitly.
272 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000273 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
274 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
275#else
276 /* Windows uses code pages instead of locales, so no locale is legacy */
277 return 0;
278#endif
279}
280
Nick Coghlaneb817952017-06-18 12:29:42 +1000281static const char *_C_LOCALE_WARNING =
282 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
283 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
284 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
285 "locales is recommended.\n";
286
Nick Coghlaneb817952017-06-18 12:29:42 +1000287static void
Victor Stinner94540602017-12-16 04:54:22 +0100288_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000289{
Victor Stinner5a02e0d2019-03-05 12:32:09 +0100290 if (core_config->preconfig.coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200291 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000292 }
293}
294
Nick Coghlan6ea41862017-06-11 13:16:15 +1000295typedef struct _CandidateLocale {
296 const char *locale_name; /* The locale to try as a coercion target */
297} _LocaleCoercionTarget;
298
299static _LocaleCoercionTarget _TARGET_LOCALES[] = {
300 {"C.UTF-8"},
301 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000302 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000303 {NULL}
304};
305
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200306
307int
308_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000309{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200310 const _LocaleCoercionTarget *target = NULL;
311 for (target = _TARGET_LOCALES; target->locale_name; target++) {
312 if (strcmp(ctype_loc, target->locale_name) == 0) {
313 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000314 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200315 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200316 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317}
318
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200319
Nick Coghlan6ea41862017-06-11 13:16:15 +1000320#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100321static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000322 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
323 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
324
325static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200326_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000327{
328 const char *newloc = target->locale_name;
329
330 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100331 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000332
333 /* Set the relevant locale environment variable */
334 if (setenv("LC_CTYPE", newloc, 1)) {
335 fprintf(stderr,
336 "Error setting LC_CTYPE, skipping C locale coercion\n");
337 return;
338 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200339 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100340 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000341 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000342
343 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100344 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000345}
346#endif
347
348void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200349_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350{
351#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200352 char *oldloc = NULL;
353
354 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
355 if (oldloc == NULL) {
356 return;
357 }
358
Victor Stinner94540602017-12-16 04:54:22 +0100359 const char *locale_override = getenv("LC_ALL");
360 if (locale_override == NULL || *locale_override == '\0') {
361 /* LC_ALL is also not set (or is set to an empty string) */
362 const _LocaleCoercionTarget *target = NULL;
363 for (target = _TARGET_LOCALES; target->locale_name; target++) {
364 const char *new_locale = setlocale(LC_CTYPE,
365 target->locale_name);
366 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100367#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100368defined(HAVE_LANGINFO_H) && defined(CODESET)
369 /* Also ensure that nl_langinfo works in this locale */
370 char *codeset = nl_langinfo(CODESET);
371 if (!codeset || *codeset == '\0') {
372 /* CODESET is not set or empty, so skip coercion */
373 new_locale = NULL;
374 _Py_SetLocaleFromEnv(LC_CTYPE);
375 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000376 }
Victor Stinner94540602017-12-16 04:54:22 +0100377#endif
378 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200379 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200380 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000381 }
382 }
383 }
384 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200385
386 setlocale(LC_CTYPE, oldloc);
387
388done:
389 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000390#endif
391}
392
xdegaye1588be62017-11-12 12:45:59 +0100393/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
394 * isolate the idiosyncrasies of different libc implementations. It reads the
395 * appropriate environment variable and uses its value to select the locale for
396 * 'category'. */
397char *
398_Py_SetLocaleFromEnv(int category)
399{
Victor Stinner353933e2018-11-23 13:08:26 +0100400 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100401#ifdef __ANDROID__
402 const char *locale;
403 const char **pvar;
404#ifdef PY_COERCE_C_LOCALE
405 const char *coerce_c_locale;
406#endif
407 const char *utf8_locale = "C.UTF-8";
408 const char *env_var_set[] = {
409 "LC_ALL",
410 "LC_CTYPE",
411 "LANG",
412 NULL,
413 };
414
415 /* Android setlocale(category, "") doesn't check the environment variables
416 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
417 * check the environment variables listed in env_var_set. */
418 for (pvar=env_var_set; *pvar; pvar++) {
419 locale = getenv(*pvar);
420 if (locale != NULL && *locale != '\0') {
421 if (strcmp(locale, utf8_locale) == 0 ||
422 strcmp(locale, "en_US.UTF-8") == 0) {
423 return setlocale(category, utf8_locale);
424 }
425 return setlocale(category, "C");
426 }
427 }
428
429 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
430 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
431 * Quote from POSIX section "8.2 Internationalization Variables":
432 * "4. If the LANG environment variable is not set or is set to the empty
433 * string, the implementation-defined default locale shall be used." */
434
435#ifdef PY_COERCE_C_LOCALE
436 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
437 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
438 /* Some other ported code may check the environment variables (e.g. in
439 * extension modules), so we make sure that they match the locale
440 * configuration */
441 if (setenv("LC_CTYPE", utf8_locale, 1)) {
442 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
443 "environment variable to %s\n", utf8_locale);
444 }
445 }
446#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100447 res = setlocale(category, utf8_locale);
448#else /* !defined(__ANDROID__) */
449 res = setlocale(category, "");
450#endif
451 _Py_ResetForceASCII();
452 return res;
xdegaye1588be62017-11-12 12:45:59 +0100453}
454
Nick Coghlan6ea41862017-06-11 13:16:15 +1000455
Eric Snow1abcf672017-05-23 21:46:51 -0700456/* Global initializations. Can be undone by Py_Finalize(). Don't
457 call this twice without an intervening Py_Finalize() call.
458
Victor Stinner1dc6e392018-07-25 02:49:17 +0200459 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700460 must have a corresponding call to Py_Finalize.
461
462 Locking: you must hold the interpreter lock while calling these APIs.
463 (If the lock has not yet been initialized, that's equivalent to
464 having the lock, but you cannot use multiple threads.)
465
466*/
467
Victor Stinner1dc6e392018-07-25 02:49:17 +0200468static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100469_Py_Initialize_ReconfigureCore(PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200470 const _PyCoreConfig *core_config)
471{
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100472 PyThreadState *tstate = _PyThreadState_GET();
473 if (!tstate) {
474 return _Py_INIT_ERR("failed to read thread state");
475 }
476
477 PyInterpreterState *interp = tstate->interp;
478 if (interp == NULL) {
479 return _Py_INIT_ERR("can't make main interpreter");
480 }
481 *interp_p = interp;
482
Victor Stinner1dc6e392018-07-25 02:49:17 +0200483 _PyCoreConfig_SetGlobalConfig(core_config);
484
485 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
486 return _Py_INIT_ERR("failed to copy core config");
487 }
488 core_config = &interp->core_config;
489
490 if (core_config->_install_importlib) {
491 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
492 if (_Py_INIT_FAILED(err)) {
493 return err;
494 }
495 }
496 return _Py_INIT_OK();
497}
498
499
Victor Stinner1dc6e392018-07-25 02:49:17 +0200500static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100501pycore_init_runtime(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000502{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200503 if (_PyRuntime.initialized) {
504 return _Py_INIT_ERR("main interpreter already initialized");
505 }
Victor Stinnerda273412017-12-15 01:46:02 +0100506
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200507 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000508
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100509 _PyInitError err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800510 if (_Py_INIT_FAILED(err)) {
511 return err;
512 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600513
Eric Snow1abcf672017-05-23 21:46:51 -0700514 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
515 * threads behave a little more gracefully at interpreter shutdown.
516 * We clobber it here so the new interpreter can start with a clean
517 * slate.
518 *
519 * However, this may still lead to misbehaviour if there are daemon
520 * threads still hanging around from a previous Py_Initialize/Finalize
521 * pair :(
522 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600523 _PyRuntime.finalizing = NULL;
524
Victor Stinnerda273412017-12-15 01:46:02 +0100525 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800526 if (_Py_INIT_FAILED(err)) {
527 return err;
528 }
529
Victor Stinnera7368ac2017-11-15 18:11:45 -0800530 err = _PyInterpreterState_Enable(&_PyRuntime);
531 if (_Py_INIT_FAILED(err)) {
532 return err;
533 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100534 return _Py_INIT_OK();
535}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800536
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100537
538static _PyInitError
539pycore_create_interpreter(const _PyCoreConfig *core_config,
540 PyInterpreterState **interp_p)
541{
542 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100543 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800544 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100545 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200546 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100547
548 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
549 return _Py_INIT_ERR("failed to copy core config");
550 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200551 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000552
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200553 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000554 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800555 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000556 (void) PyThreadState_Swap(tstate);
557
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000558 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000559 destroying the GIL might fail when it is being referenced from
560 another running thread (see issue #9901).
561 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000562 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000563 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100564
Nick Coghland6009512014-11-20 21:39:37 +1000565 /* Auto-thread-state API */
566 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000567
Victor Stinner2914bb32018-01-29 11:57:45 +0100568 /* Create the GIL */
569 PyEval_InitThreads();
570
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100571 return _Py_INIT_OK();
572}
Nick Coghland6009512014-11-20 21:39:37 +1000573
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100574
575static _PyInitError
576pycore_init_types(void)
577{
Victor Stinnerab672812019-01-23 15:04:40 +0100578 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100579 if (_Py_INIT_FAILED(err)) {
580 return err;
581 }
582
583 err = _PyUnicode_Init();
584 if (_Py_INIT_FAILED(err)) {
585 return err;
586 }
587
588 if (_PyStructSequence_Init() < 0) {
589 return _Py_INIT_ERR("can't initialize structseq");
590 }
591
592 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800593 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100594 }
Nick Coghland6009512014-11-20 21:39:37 +1000595
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100596 err = _PyExc_Init();
597 if (_Py_INIT_FAILED(err)) {
598 return err;
599 }
600
601 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800602 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100603 }
Nick Coghland6009512014-11-20 21:39:37 +1000604
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100605 if (!_PyContext_Init()) {
606 return _Py_INIT_ERR("can't init context");
607 }
608 return _Py_INIT_OK();
609}
610
611
612static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100613pycore_init_builtins(PyInterpreterState *interp)
614{
615 PyObject *bimod = _PyBuiltin_Init();
616 if (bimod == NULL) {
617 return _Py_INIT_ERR("can't initialize builtins modules");
618 }
619 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
620
621 interp->builtins = PyModule_GetDict(bimod);
622 if (interp->builtins == NULL) {
623 return _Py_INIT_ERR("can't initialize builtins dict");
624 }
625 Py_INCREF(interp->builtins);
626
627 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
628 if (_Py_INIT_FAILED(err)) {
629 return err;
630 }
631 return _Py_INIT_OK();
632}
633
634
635static _PyInitError
636pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
637{
638 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800639 if (_Py_INIT_FAILED(err)) {
640 return err;
641 }
Nick Coghland6009512014-11-20 21:39:37 +1000642
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800643 err = _PyImportHooks_Init();
644 if (_Py_INIT_FAILED(err)) {
645 return err;
646 }
Nick Coghland6009512014-11-20 21:39:37 +1000647
648 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100649 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100650 return _Py_INIT_ERR("can't initialize warnings");
651 }
Nick Coghland6009512014-11-20 21:39:37 +1000652
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100653 if (interp->core_config._install_importlib) {
654 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200655 if (_Py_INIT_FAILED(err)) {
656 return err;
657 }
658 }
659
Eric Snow1abcf672017-05-23 21:46:51 -0700660 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100661 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800662 err = initimport(interp, sysmod);
663 if (_Py_INIT_FAILED(err)) {
664 return err;
665 }
Eric Snow1abcf672017-05-23 21:46:51 -0700666 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100667 return _Py_INIT_OK();
668}
669
670
671static _PyInitError
672_Py_InitializeCore_impl(PyInterpreterState **interp_p,
673 const _PyCoreConfig *core_config)
674{
675 PyInterpreterState *interp;
676
677 _PyInitError err = pycore_init_runtime(core_config);
678 if (_Py_INIT_FAILED(err)) {
679 return err;
680 }
681
682 err = pycore_create_interpreter(core_config, &interp);
683 if (_Py_INIT_FAILED(err)) {
684 return err;
685 }
686 core_config = &interp->core_config;
687 *interp_p = interp;
688
689 err = pycore_init_types();
690 if (_Py_INIT_FAILED(err)) {
691 return err;
692 }
693
694 PyObject *sysmod;
Victor Stinnerab672812019-01-23 15:04:40 +0100695 err = _PySys_Create(interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100696 if (_Py_INIT_FAILED(err)) {
697 return err;
698 }
699
700 err = pycore_init_builtins(interp);
701 if (_Py_INIT_FAILED(err)) {
702 return err;
703 }
704
705 err = pycore_init_import_warnings(interp, sysmod);
706 if (_Py_INIT_FAILED(err)) {
707 return err;
708 }
Eric Snow1abcf672017-05-23 21:46:51 -0700709
710 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600711 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800712 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700713}
714
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100715
716static _PyInitError
717pyinit_preconfig(_PyPreConfig *preconfig, const _PyPreConfig *src_preconfig)
718{
Victor Stinnerc656e252019-03-06 01:13:43 +0100719 if (_PyPreConfig_Copy(preconfig, src_preconfig) < 0) {
720 return _Py_INIT_ERR("failed to copy pre config");
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100721 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100722
Victor Stinnerc656e252019-03-06 01:13:43 +0100723 _PyInitError err = _PyPreConfig_Read(preconfig);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100724 if (_Py_INIT_FAILED(err)) {
725 return err;
726 }
727
728 return _PyPreConfig_Write(preconfig);
729}
730
731
732static _PyInitError
733pyinit_coreconfig(_PyCoreConfig *config, const _PyCoreConfig *src_config,
734 PyInterpreterState **interp_p)
735{
Victor Stinnerc656e252019-03-06 01:13:43 +0100736 if (_PyCoreConfig_Copy(config, src_config) < 0) {
737 return _Py_INIT_ERR("failed to copy core config");
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100738 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100739
Victor Stinnerc656e252019-03-06 01:13:43 +0100740 _PyInitError err = _PyCoreConfig_Read(config, NULL);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100741 if (_Py_INIT_FAILED(err)) {
742 return err;
743 }
744
745 if (!_PyRuntime.core_initialized) {
746 return _Py_InitializeCore_impl(interp_p, config);
747 }
748 else {
749 return _Py_Initialize_ReconfigureCore(interp_p, config);
750 }
751}
752
753
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100754/* Begin interpreter initialization
755 *
756 * On return, the first thread and interpreter state have been created,
757 * but the compiler, signal handling, multithreading and
758 * multiple interpreter support, and codec infrastructure are not yet
759 * available.
760 *
761 * The import system will support builtin and frozen modules only.
762 * The only supported io is writing to sys.stderr
763 *
764 * If any operation invoked by this function fails, a fatal error is
765 * issued and the function does not return.
766 *
767 * Any code invoked from this function should *not* assume it has access
768 * to the Python C API (unless the API is explicitly listed as being
769 * safe to call without calling Py_Initialize first)
770 */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200771_PyInitError
772_Py_InitializeCore(PyInterpreterState **interp_p,
773 const _PyCoreConfig *src_config)
774{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200775 _PyInitError err;
776
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100777 assert(src_config != NULL);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200778
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100779 _PyCoreConfig local_config = _PyCoreConfig_INIT;
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200780
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100781 err = pyinit_preconfig(&local_config.preconfig, &src_config->preconfig);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200782 if (_Py_INIT_FAILED(err)) {
783 goto done;
784 }
785
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100786 err = pyinit_coreconfig(&local_config, src_config, interp_p);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200787
788done:
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100789 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200790 return err;
791}
792
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200793/* Py_Initialize() has already been called: update the main interpreter
794 configuration. Example of bpo-34008: Py_Main() called after
795 Py_Initialize(). */
796static _PyInitError
797_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
798 const _PyMainInterpreterConfig *config)
799{
800 if (config->argv != NULL) {
801 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
802 if (res < 0) {
803 return _Py_INIT_ERR("fail to set sys.argv");
804 }
805 }
806 return _Py_INIT_OK();
807}
808
Eric Snowc7ec9982017-05-23 23:00:52 -0700809/* Update interpreter state based on supplied configuration settings
810 *
811 * After calling this function, most of the restrictions on the interpreter
812 * are lifted. The only remaining incomplete settings are those related
813 * to the main module (sys.argv[0], __main__ metadata)
814 *
815 * Calling this when the interpreter is not initializing, is already
816 * initialized or without a valid current thread state is a fatal error.
817 * Other errors should be reported as normal Python exceptions with a
818 * non-zero return code.
819 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800820_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200821_Py_InitializeMainInterpreter(PyInterpreterState *interp,
822 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700823{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600824 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800825 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700826 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700827
Victor Stinner1dc6e392018-07-25 02:49:17 +0200828 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100829 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
830 return _Py_INIT_ERR("failed to copy main interpreter config");
831 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200832 config = &interp->config;
833 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700834
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200835 if (_PyRuntime.initialized) {
836 return _Py_ReconfigureMainInterpreter(interp, config);
837 }
838
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200839 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700840 /* Special mode for freeze_importlib: run with no import system
841 *
842 * This means anything which needs support from extension modules
843 * or pure Python code in the standard library won't work.
844 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600845 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800846 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700847 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100848
Victor Stinner33c377e2017-12-05 15:12:41 +0100849 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800850 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100851 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200852
Victor Stinnerab672812019-01-23 15:04:40 +0100853 if (_PySys_InitMain(interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800854 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100855 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800856
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200857 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800858 if (_Py_INIT_FAILED(err)) {
859 return err;
860 }
Nick Coghland6009512014-11-20 21:39:37 +1000861
862 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200863 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800864 if (_Py_INIT_FAILED(err)) {
865 return err;
866 }
Nick Coghland6009512014-11-20 21:39:37 +1000867
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800868 err = initfsencoding(interp);
869 if (_Py_INIT_FAILED(err)) {
870 return err;
871 }
Nick Coghland6009512014-11-20 21:39:37 +1000872
Victor Stinner1f151112017-11-23 10:43:14 +0100873 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800874 err = initsigs(); /* Signal handling stuff, including initintr() */
875 if (_Py_INIT_FAILED(err)) {
876 return err;
877 }
878 }
Nick Coghland6009512014-11-20 21:39:37 +1000879
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200880 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800881 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200882 }
Nick Coghland6009512014-11-20 21:39:37 +1000883
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800884 err = add_main_module(interp);
885 if (_Py_INIT_FAILED(err)) {
886 return err;
887 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800888
Victor Stinner91106cd2017-12-13 12:29:09 +0100889 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800890 if (_Py_INIT_FAILED(err)) {
891 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800892 }
Nick Coghland6009512014-11-20 21:39:37 +1000893
894 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100895 PyObject *warnoptions = PySys_GetObject("warnoptions");
896 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100897 {
Nick Coghland6009512014-11-20 21:39:37 +1000898 PyObject *warnings_module = PyImport_ImportModule("warnings");
899 if (warnings_module == NULL) {
900 fprintf(stderr, "'import warnings' failed; traceback:\n");
901 PyErr_Print();
902 }
903 Py_XDECREF(warnings_module);
904 }
905
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600906 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700907
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200908 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800909 err = initsite(); /* Module site */
910 if (_Py_INIT_FAILED(err)) {
911 return err;
912 }
913 }
Victor Stinnercf215042018-08-29 22:56:06 +0200914
915#ifndef MS_WINDOWS
916 _emit_stderr_warning_for_legacy_locale(core_config);
917#endif
918
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800919 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000920}
921
Eric Snowc7ec9982017-05-23 23:00:52 -0700922#undef _INIT_DEBUG_PRINT
923
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800924_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200925_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700926{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700927 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800928 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200929 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800930 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200931 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800932 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200933 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100934
Victor Stinner9cfc0022017-12-20 19:36:46 +0100935 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200936 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100937 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200938 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800939 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100940 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800941 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200942 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800943 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200944 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700945}
946
947
948void
Nick Coghland6009512014-11-20 21:39:37 +1000949Py_InitializeEx(int install_sigs)
950{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200951 if (_PyRuntime.initialized) {
952 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
953 return;
954 }
955
956 _PyInitError err;
957 _PyCoreConfig config = _PyCoreConfig_INIT;
958 config.install_signal_handlers = install_sigs;
959
960 err = _Py_InitializeFromConfig(&config);
961 _PyCoreConfig_Clear(&config);
962
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800963 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +0100964 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800965 }
Nick Coghland6009512014-11-20 21:39:37 +1000966}
967
968void
969Py_Initialize(void)
970{
971 Py_InitializeEx(1);
972}
973
974
975#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000976extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000977#endif
978
979/* Flush stdout and stderr */
980
981static int
982file_is_closed(PyObject *fobj)
983{
984 int r;
985 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
986 if (tmp == NULL) {
987 PyErr_Clear();
988 return 0;
989 }
990 r = PyObject_IsTrue(tmp);
991 Py_DECREF(tmp);
992 if (r < 0)
993 PyErr_Clear();
994 return r > 0;
995}
996
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000997static int
Nick Coghland6009512014-11-20 21:39:37 +1000998flush_std_files(void)
999{
1000 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1001 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1002 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001003 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001004
1005 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001006 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001007 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001008 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001009 status = -1;
1010 }
Nick Coghland6009512014-11-20 21:39:37 +10001011 else
1012 Py_DECREF(tmp);
1013 }
1014
1015 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001016 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001017 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001018 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001019 status = -1;
1020 }
Nick Coghland6009512014-11-20 21:39:37 +10001021 else
1022 Py_DECREF(tmp);
1023 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001024
1025 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001026}
1027
1028/* Undo the effect of Py_Initialize().
1029
1030 Beware: if multiple interpreter and/or thread states exist, these
1031 are not wiped out; only the current thread and interpreter state
1032 are deleted. But since everything else is deleted, those other
1033 interpreter and thread states should no longer be used.
1034
1035 (XXX We should do better, e.g. wipe out all interpreters and
1036 threads.)
1037
1038 Locking: as above.
1039
1040*/
1041
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001042int
1043Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001044{
1045 PyInterpreterState *interp;
1046 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001047 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001048
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001049 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001050 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001051
1052 wait_for_thread_shutdown();
1053
Marcel Plch776407f2017-12-20 11:17:58 +01001054 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001055 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001056 interp = tstate->interp;
1057
Nick Coghland6009512014-11-20 21:39:37 +10001058 /* The interpreter is still entirely intact at this point, and the
1059 * exit funcs may be relying on that. In particular, if some thread
1060 * or exit func is still waiting to do an import, the import machinery
1061 * expects Py_IsInitialized() to return true. So don't say the
1062 * interpreter is uninitialized until after the exit funcs have run.
1063 * Note that Threading.py uses an exit func to do a join on all the
1064 * threads created thru it, so this also protects pending imports in
1065 * the threads created via Threading.
1066 */
Nick Coghland6009512014-11-20 21:39:37 +10001067
Marcel Plch776407f2017-12-20 11:17:58 +01001068 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001069
Victor Stinnerda273412017-12-15 01:46:02 +01001070 /* Copy the core config, PyInterpreterState_Delete() free
1071 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001072#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001073 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001074#endif
1075#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001076 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001077#endif
1078#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001079 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001080#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001081
Nick Coghland6009512014-11-20 21:39:37 +10001082 /* Remaining threads (e.g. daemon threads) will automatically exit
1083 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001084 _PyRuntime.finalizing = tstate;
1085 _PyRuntime.initialized = 0;
1086 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001087
Victor Stinnere0deff32015-03-24 13:46:18 +01001088 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001089 if (flush_std_files() < 0) {
1090 status = -1;
1091 }
Nick Coghland6009512014-11-20 21:39:37 +10001092
1093 /* Disable signal handling */
1094 PyOS_FiniInterrupts();
1095
1096 /* Collect garbage. This may call finalizers; it's nice to call these
1097 * before all modules are destroyed.
1098 * XXX If a __del__ or weakref callback is triggered here, and tries to
1099 * XXX import a module, bad things can happen, because Python no
1100 * XXX longer believes it's initialized.
1101 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1102 * XXX is easy to provoke that way. I've also seen, e.g.,
1103 * XXX Exception exceptions.ImportError: 'No module named sha'
1104 * XXX in <function callback at 0x008F5718> ignored
1105 * XXX but I'm unclear on exactly how that one happens. In any case,
1106 * XXX I haven't seen a real-life report of either of these.
1107 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001108 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001109#ifdef COUNT_ALLOCS
1110 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1111 each collection might release some types from the type
1112 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001113 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001114 /* nothing */;
1115#endif
Eric Snowdae02762017-09-14 00:35:58 -07001116
Nick Coghland6009512014-11-20 21:39:37 +10001117 /* Destroy all modules */
1118 PyImport_Cleanup();
1119
Victor Stinnere0deff32015-03-24 13:46:18 +01001120 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001121 if (flush_std_files() < 0) {
1122 status = -1;
1123 }
Nick Coghland6009512014-11-20 21:39:37 +10001124
1125 /* Collect final garbage. This disposes of cycles created by
1126 * class definitions, for example.
1127 * XXX This is disabled because it caused too many problems. If
1128 * XXX a __del__ or weakref callback triggers here, Python code has
1129 * XXX a hard time running, because even the sys module has been
1130 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1131 * XXX One symptom is a sequence of information-free messages
1132 * XXX coming from threads (if a __del__ or callback is invoked,
1133 * XXX other threads can execute too, and any exception they encounter
1134 * XXX triggers a comedy of errors as subsystem after subsystem
1135 * XXX fails to find what it *expects* to find in sys to help report
1136 * XXX the exception and consequent unexpected failures). I've also
1137 * XXX seen segfaults then, after adding print statements to the
1138 * XXX Python code getting called.
1139 */
1140#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001141 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001142#endif
1143
1144 /* Disable tracemalloc after all Python objects have been destroyed,
1145 so it is possible to use tracemalloc in objects destructor. */
1146 _PyTraceMalloc_Fini();
1147
1148 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1149 _PyImport_Fini();
1150
1151 /* Cleanup typeobject.c's internal caches. */
1152 _PyType_Fini();
1153
1154 /* unload faulthandler module */
1155 _PyFaulthandler_Fini();
1156
1157 /* Debugging stuff */
1158#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001159 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001160#endif
1161 /* dump hash stats */
1162 _PyHash_Fini();
1163
Eric Snowdae02762017-09-14 00:35:58 -07001164#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001165 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001166 _PyDebug_PrintTotalRefs();
1167 }
Eric Snowdae02762017-09-14 00:35:58 -07001168#endif
Nick Coghland6009512014-11-20 21:39:37 +10001169
1170#ifdef Py_TRACE_REFS
1171 /* Display all objects still alive -- this can invoke arbitrary
1172 * __repr__ overrides, so requires a mostly-intact interpreter.
1173 * Alas, a lot of stuff may still be alive now that will be cleaned
1174 * up later.
1175 */
Victor Stinnerda273412017-12-15 01:46:02 +01001176 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001177 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001178 }
Nick Coghland6009512014-11-20 21:39:37 +10001179#endif /* Py_TRACE_REFS */
1180
1181 /* Clear interpreter state and all thread states. */
1182 PyInterpreterState_Clear(interp);
1183
1184 /* Now we decref the exception classes. After this point nothing
1185 can raise an exception. That's okay, because each Fini() method
1186 below has been checked to make sure no exceptions are ever
1187 raised.
1188 */
1189
1190 _PyExc_Fini();
1191
1192 /* Sundry finalizers */
1193 PyMethod_Fini();
1194 PyFrame_Fini();
1195 PyCFunction_Fini();
1196 PyTuple_Fini();
1197 PyList_Fini();
1198 PySet_Fini();
1199 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001200 PyLong_Fini();
1201 PyFloat_Fini();
1202 PyDict_Fini();
1203 PySlice_Fini();
1204 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001205 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001206 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001207 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001208 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001209
1210 /* Cleanup Unicode implementation */
1211 _PyUnicode_Fini();
1212
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001213 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001214
1215 /* XXX Still allocated:
1216 - various static ad-hoc pointers to interned strings
1217 - int and float free list blocks
1218 - whatever various modules and libraries allocate
1219 */
1220
1221 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1222
1223 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001224 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001225
1226 /* Delete current thread. After this, many C API calls become crashy. */
1227 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001228
Nick Coghland6009512014-11-20 21:39:37 +10001229 PyInterpreterState_Delete(interp);
1230
1231#ifdef Py_TRACE_REFS
1232 /* Display addresses (& refcnts) of all objects still alive.
1233 * An address can be used to find the repr of the object, printed
1234 * above by _Py_PrintReferences.
1235 */
Victor Stinnerda273412017-12-15 01:46:02 +01001236 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001237 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001238 }
Nick Coghland6009512014-11-20 21:39:37 +10001239#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001240#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001241 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001242 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001243 }
Nick Coghland6009512014-11-20 21:39:37 +10001244#endif
1245
1246 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001247
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001248 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001249 return status;
1250}
1251
1252void
1253Py_Finalize(void)
1254{
1255 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001256}
1257
1258/* Create and initialize a new interpreter and thread, and return the
1259 new thread. This requires that Py_Initialize() has been called
1260 first.
1261
1262 Unsuccessful initialization yields a NULL pointer. Note that *no*
1263 exception information is available even in this case -- the
1264 exception information is held in the thread, and there is no
1265 thread.
1266
1267 Locking: as above.
1268
1269*/
1270
Victor Stinnera7368ac2017-11-15 18:11:45 -08001271static _PyInitError
1272new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001273{
1274 PyInterpreterState *interp;
1275 PyThreadState *tstate, *save_tstate;
1276 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001277 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001278
Victor Stinnera7368ac2017-11-15 18:11:45 -08001279 if (!_PyRuntime.initialized) {
1280 return _Py_INIT_ERR("Py_Initialize must be called first");
1281 }
Nick Coghland6009512014-11-20 21:39:37 +10001282
Victor Stinner8a1be612016-03-14 22:07:55 +01001283 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1284 interpreters: disable PyGILState_Check(). */
1285 _PyGILState_check_enabled = 0;
1286
Nick Coghland6009512014-11-20 21:39:37 +10001287 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001288 if (interp == NULL) {
1289 *tstate_p = NULL;
1290 return _Py_INIT_OK();
1291 }
Nick Coghland6009512014-11-20 21:39:37 +10001292
1293 tstate = PyThreadState_New(interp);
1294 if (tstate == NULL) {
1295 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001296 *tstate_p = NULL;
1297 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001298 }
1299
1300 save_tstate = PyThreadState_Swap(tstate);
1301
Eric Snow1abcf672017-05-23 21:46:51 -07001302 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001303 _PyCoreConfig *core_config;
1304 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001305 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001306 core_config = &save_tstate->interp->core_config;
1307 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001308 } else {
1309 /* No current thread state, copy from the main interpreter */
1310 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001311 core_config = &main_interp->core_config;
1312 config = &main_interp->config;
1313 }
1314
1315 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1316 return _Py_INIT_ERR("failed to copy core config");
1317 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001318 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001319 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1320 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001321 }
1322
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001323 err = _PyExc_Init();
1324 if (_Py_INIT_FAILED(err)) {
1325 return err;
1326 }
1327
Nick Coghland6009512014-11-20 21:39:37 +10001328 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001329 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001330 if (modules == NULL) {
1331 return _Py_INIT_ERR("can't make modules dictionary");
1332 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001333 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001334
Eric Snowd393c1b2017-09-14 12:18:12 -06001335 sysmod = _PyImport_FindBuiltin("sys", modules);
1336 if (sysmod != NULL) {
1337 interp->sysdict = PyModule_GetDict(sysmod);
1338 if (interp->sysdict == NULL)
1339 goto handle_error;
1340 Py_INCREF(interp->sysdict);
1341 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerab672812019-01-23 15:04:40 +01001342 if (_PySys_InitMain(interp) < 0) {
1343 return _Py_INIT_ERR("can't finish initializing sys");
1344 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001345 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001346 else if (PyErr_Occurred()) {
1347 goto handle_error;
1348 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001349
1350 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001351 if (bimod != NULL) {
1352 interp->builtins = PyModule_GetDict(bimod);
1353 if (interp->builtins == NULL)
1354 goto handle_error;
1355 Py_INCREF(interp->builtins);
1356 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001357 else if (PyErr_Occurred()) {
1358 goto handle_error;
1359 }
Nick Coghland6009512014-11-20 21:39:37 +10001360
Nick Coghland6009512014-11-20 21:39:37 +10001361 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001362 err = _PyBuiltins_AddExceptions(bimod);
1363 if (_Py_INIT_FAILED(err)) {
1364 return err;
1365 }
Nick Coghland6009512014-11-20 21:39:37 +10001366
Victor Stinnerab672812019-01-23 15:04:40 +01001367 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1368 if (_Py_INIT_FAILED(err)) {
1369 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001370 }
Nick Coghland6009512014-11-20 21:39:37 +10001371
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001372 err = _PyImportHooks_Init();
1373 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001374 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001375 }
Nick Coghland6009512014-11-20 21:39:37 +10001376
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001377 err = initimport(interp, sysmod);
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 = initexternalimport(interp);
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 = initfsencoding(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 }
1391
Victor Stinner91106cd2017-12-13 12:29:09 +01001392 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001393 if (_Py_INIT_FAILED(err)) {
1394 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001395 }
1396
1397 err = add_main_module(interp);
1398 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001399 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001400 }
1401
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001402 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001403 err = initsite();
1404 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001405 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001406 }
1407 }
Nick Coghland6009512014-11-20 21:39:37 +10001408 }
1409
Victor Stinnera7368ac2017-11-15 18:11:45 -08001410 if (PyErr_Occurred()) {
1411 goto handle_error;
1412 }
Nick Coghland6009512014-11-20 21:39:37 +10001413
Victor Stinnera7368ac2017-11-15 18:11:45 -08001414 *tstate_p = tstate;
1415 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001416
Nick Coghland6009512014-11-20 21:39:37 +10001417handle_error:
1418 /* Oops, it didn't work. Undo it all. */
1419
1420 PyErr_PrintEx(0);
1421 PyThreadState_Clear(tstate);
1422 PyThreadState_Swap(save_tstate);
1423 PyThreadState_Delete(tstate);
1424 PyInterpreterState_Delete(interp);
1425
Victor Stinnera7368ac2017-11-15 18:11:45 -08001426 *tstate_p = NULL;
1427 return _Py_INIT_OK();
1428}
1429
1430PyThreadState *
1431Py_NewInterpreter(void)
1432{
1433 PyThreadState *tstate;
1434 _PyInitError err = new_interpreter(&tstate);
1435 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001436 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001437 }
1438 return tstate;
1439
Nick Coghland6009512014-11-20 21:39:37 +10001440}
1441
1442/* Delete an interpreter and its last thread. This requires that the
1443 given thread state is current, that the thread has no remaining
1444 frames, and that it is its interpreter's only remaining thread.
1445 It is a fatal error to violate these constraints.
1446
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001447 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001448 everything, regardless.)
1449
1450 Locking: as above.
1451
1452*/
1453
1454void
1455Py_EndInterpreter(PyThreadState *tstate)
1456{
1457 PyInterpreterState *interp = tstate->interp;
1458
Victor Stinner50b48572018-11-01 01:51:40 +01001459 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001460 Py_FatalError("Py_EndInterpreter: thread is not current");
1461 if (tstate->frame != NULL)
1462 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1463
1464 wait_for_thread_shutdown();
1465
Marcel Plch776407f2017-12-20 11:17:58 +01001466 call_py_exitfuncs(interp);
1467
Nick Coghland6009512014-11-20 21:39:37 +10001468 if (tstate != interp->tstate_head || tstate->next != NULL)
1469 Py_FatalError("Py_EndInterpreter: not the last thread");
1470
1471 PyImport_Cleanup();
1472 PyInterpreterState_Clear(interp);
1473 PyThreadState_Swap(NULL);
1474 PyInterpreterState_Delete(interp);
1475}
1476
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001477/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001478
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001479static _PyInitError
1480add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001481{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001482 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001483 m = PyImport_AddModule("__main__");
1484 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001485 return _Py_INIT_ERR("can't create __main__ module");
1486
Nick Coghland6009512014-11-20 21:39:37 +10001487 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001488 ann_dict = PyDict_New();
1489 if ((ann_dict == NULL) ||
1490 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001491 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001492 }
1493 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001494
Nick Coghland6009512014-11-20 21:39:37 +10001495 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1496 PyObject *bimod = PyImport_ImportModule("builtins");
1497 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001499 }
1500 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001501 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001502 }
1503 Py_DECREF(bimod);
1504 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001505
Nick Coghland6009512014-11-20 21:39:37 +10001506 /* Main is a little special - imp.is_builtin("__main__") will return
1507 * False, but BuiltinImporter is still the most appropriate initial
1508 * setting for its __loader__ attribute. A more suitable value will
1509 * be set if __main__ gets further initialized later in the startup
1510 * process.
1511 */
1512 loader = PyDict_GetItemString(d, "__loader__");
1513 if (loader == NULL || loader == Py_None) {
1514 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1515 "BuiltinImporter");
1516 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001518 }
1519 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001520 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001521 }
1522 Py_DECREF(loader);
1523 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001525}
1526
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001527static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001528initfsencoding(PyInterpreterState *interp)
1529{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001530 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001531
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001532 char *encoding = get_codec_name(config->filesystem_encoding);
1533 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001534 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001535 memory, import a module of the standard library failed, etc. */
1536 return _Py_INIT_ERR("failed to get the Python codec "
1537 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001538 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001539
1540 /* Update the filesystem encoding to the normalized Python codec name.
1541 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1542 (Python codec name). */
1543 PyMem_RawFree(config->filesystem_encoding);
1544 config->filesystem_encoding = encoding;
1545
1546 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1547 global configuration variables. */
1548 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1549 config->filesystem_errors) < 0) {
1550 return _Py_INIT_NO_MEMORY();
1551 }
1552
1553 /* PyUnicode can now use the Python codec rather than C implementation
1554 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001555 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001556 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001557}
1558
1559/* Import the site module (not into __main__ though) */
1560
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001561static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001562initsite(void)
1563{
1564 PyObject *m;
1565 m = PyImport_ImportModule("site");
1566 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001567 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001568 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001569 Py_DECREF(m);
1570 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001571}
1572
Victor Stinner874dbe82015-09-04 17:29:57 +02001573/* Check if a file descriptor is valid or not.
1574 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1575static int
1576is_valid_fd(int fd)
1577{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001578#ifdef __APPLE__
1579 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1580 and the other side of the pipe is closed, dup(1) succeed, whereas
1581 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1582 such error. */
1583 struct stat st;
1584 return (fstat(fd, &st) == 0);
1585#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001586 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001587 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001588 return 0;
1589 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001590 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1591 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1592 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001593 fd2 = dup(fd);
1594 if (fd2 >= 0)
1595 close(fd2);
1596 _Py_END_SUPPRESS_IPH
1597 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001598#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001599}
1600
1601/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001602static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001603create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001604 int fd, int write_mode, const char* name,
1605 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001606{
1607 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1608 const char* mode;
1609 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001610 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001611 int buffering, isatty;
1612 _Py_IDENTIFIER(open);
1613 _Py_IDENTIFIER(isatty);
1614 _Py_IDENTIFIER(TextIOWrapper);
1615 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001616 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001617
Victor Stinner874dbe82015-09-04 17:29:57 +02001618 if (!is_valid_fd(fd))
1619 Py_RETURN_NONE;
1620
Nick Coghland6009512014-11-20 21:39:37 +10001621 /* stdin is always opened in buffered mode, first because it shouldn't
1622 make a difference in common use cases, second because TextIOWrapper
1623 depends on the presence of a read1() method which only exists on
1624 buffered streams.
1625 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001626 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001627 buffering = 0;
1628 else
1629 buffering = -1;
1630 if (write_mode)
1631 mode = "wb";
1632 else
1633 mode = "rb";
1634 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1635 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001636 Py_None, Py_None, /* encoding, errors */
1637 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001638 if (buf == NULL)
1639 goto error;
1640
1641 if (buffering) {
1642 _Py_IDENTIFIER(raw);
1643 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1644 if (raw == NULL)
1645 goto error;
1646 }
1647 else {
1648 raw = buf;
1649 Py_INCREF(raw);
1650 }
1651
Steve Dower39294992016-08-30 21:22:36 -07001652#ifdef MS_WINDOWS
1653 /* Windows console IO is always UTF-8 encoded */
1654 if (PyWindowsConsoleIO_Check(raw))
1655 encoding = "utf-8";
1656#endif
1657
Nick Coghland6009512014-11-20 21:39:37 +10001658 text = PyUnicode_FromString(name);
1659 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1660 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001661 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001662 if (res == NULL)
1663 goto error;
1664 isatty = PyObject_IsTrue(res);
1665 Py_DECREF(res);
1666 if (isatty == -1)
1667 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001668 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001669 write_through = Py_True;
1670 else
1671 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001672 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001673 line_buffering = Py_True;
1674 else
1675 line_buffering = Py_False;
1676
1677 Py_CLEAR(raw);
1678 Py_CLEAR(text);
1679
1680#ifdef MS_WINDOWS
1681 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1682 newlines to "\n".
1683 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1684 newline = NULL;
1685#else
1686 /* sys.stdin: split lines at "\n".
1687 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1688 newline = "\n";
1689#endif
1690
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001691 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001692 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001693 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001694 Py_CLEAR(buf);
1695 if (stream == NULL)
1696 goto error;
1697
1698 if (write_mode)
1699 mode = "w";
1700 else
1701 mode = "r";
1702 text = PyUnicode_FromString(mode);
1703 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1704 goto error;
1705 Py_CLEAR(text);
1706 return stream;
1707
1708error:
1709 Py_XDECREF(buf);
1710 Py_XDECREF(stream);
1711 Py_XDECREF(text);
1712 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001713
Victor Stinner874dbe82015-09-04 17:29:57 +02001714 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1715 /* Issue #24891: the file descriptor was closed after the first
1716 is_valid_fd() check was called. Ignore the OSError and set the
1717 stream to None. */
1718 PyErr_Clear();
1719 Py_RETURN_NONE;
1720 }
1721 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001722}
1723
1724/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001725static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001726init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001727{
1728 PyObject *iomod = NULL, *wrapper;
1729 PyObject *bimod = NULL;
1730 PyObject *m;
1731 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001732 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001733 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001734 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001735 _PyCoreConfig *config = &interp->core_config;
1736
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001737 /* Check that stdin is not a directory
1738 Using shell redirection, you can redirect stdin to a directory,
1739 crashing the Python interpreter. Catch this common mistake here
1740 and output a useful error message. Note that under MS Windows,
1741 the shell already prevents that. */
1742#ifndef MS_WINDOWS
1743 struct _Py_stat_struct sb;
1744 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1745 S_ISDIR(sb.st_mode)) {
1746 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1747 "cannot continue");
1748 }
1749#endif
1750
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001751 char *codec_name = get_codec_name(config->stdio_encoding);
1752 if (codec_name == NULL) {
1753 return _Py_INIT_ERR("failed to get the Python codec name "
1754 "of the stdio encoding");
1755 }
1756 PyMem_RawFree(config->stdio_encoding);
1757 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001758
1759 /* Hack to avoid a nasty recursion issue when Python is invoked
1760 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1761 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1762 goto error;
1763 }
1764 Py_DECREF(m);
1765
1766 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1767 goto error;
1768 }
1769 Py_DECREF(m);
1770
1771 if (!(bimod = PyImport_ImportModule("builtins"))) {
1772 goto error;
1773 }
1774
1775 if (!(iomod = PyImport_ImportModule("io"))) {
1776 goto error;
1777 }
1778 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1779 goto error;
1780 }
1781
1782 /* Set builtins.open */
1783 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1784 Py_DECREF(wrapper);
1785 goto error;
1786 }
1787 Py_DECREF(wrapper);
1788
Nick Coghland6009512014-11-20 21:39:37 +10001789 /* Set sys.stdin */
1790 fd = fileno(stdin);
1791 /* Under some conditions stdin, stdout and stderr may not be connected
1792 * and fileno() may point to an invalid file descriptor. For example
1793 * GUI apps don't have valid standard streams by default.
1794 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001795 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001796 config->stdio_encoding,
1797 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001798 if (std == NULL)
1799 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001800 PySys_SetObject("__stdin__", std);
1801 _PySys_SetObjectId(&PyId_stdin, std);
1802 Py_DECREF(std);
1803
1804 /* Set sys.stdout */
1805 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001806 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001807 config->stdio_encoding,
1808 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001809 if (std == NULL)
1810 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001811 PySys_SetObject("__stdout__", std);
1812 _PySys_SetObjectId(&PyId_stdout, std);
1813 Py_DECREF(std);
1814
1815#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1816 /* Set sys.stderr, replaces the preliminary stderr */
1817 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001818 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001819 config->stdio_encoding,
1820 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001821 if (std == NULL)
1822 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001823
1824 /* Same as hack above, pre-import stderr's codec to avoid recursion
1825 when import.c tries to write to stderr in verbose mode. */
1826 encoding_attr = PyObject_GetAttrString(std, "encoding");
1827 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001828 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001829 if (std_encoding != NULL) {
1830 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1831 Py_XDECREF(codec_info);
1832 }
1833 Py_DECREF(encoding_attr);
1834 }
1835 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1836
1837 if (PySys_SetObject("__stderr__", std) < 0) {
1838 Py_DECREF(std);
1839 goto error;
1840 }
1841 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1842 Py_DECREF(std);
1843 goto error;
1844 }
1845 Py_DECREF(std);
1846#endif
1847
Victor Stinnera7368ac2017-11-15 18:11:45 -08001848 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001849
Victor Stinnera7368ac2017-11-15 18:11:45 -08001850error:
1851 res = _Py_INIT_ERR("can't initialize sys standard streams");
1852
1853done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001854 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001855
Nick Coghland6009512014-11-20 21:39:37 +10001856 Py_XDECREF(bimod);
1857 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001858 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001859}
1860
1861
Victor Stinner10dc4842015-03-24 12:01:30 +01001862static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001863_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001864{
Victor Stinner10dc4842015-03-24 12:01:30 +01001865 fputc('\n', stderr);
1866 fflush(stderr);
1867
1868 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001869 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001870}
Victor Stinner791da1c2016-03-14 16:53:12 +01001871
1872/* Print the current exception (if an exception is set) with its traceback,
1873 or display the current Python stack.
1874
1875 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1876 called on catastrophic cases.
1877
1878 Return 1 if the traceback was displayed, 0 otherwise. */
1879
1880static int
1881_Py_FatalError_PrintExc(int fd)
1882{
1883 PyObject *ferr, *res;
1884 PyObject *exception, *v, *tb;
1885 int has_tb;
1886
Victor Stinner791da1c2016-03-14 16:53:12 +01001887 PyErr_Fetch(&exception, &v, &tb);
1888 if (exception == NULL) {
1889 /* No current exception */
1890 return 0;
1891 }
1892
1893 ferr = _PySys_GetObjectId(&PyId_stderr);
1894 if (ferr == NULL || ferr == Py_None) {
1895 /* sys.stderr is not set yet or set to None,
1896 no need to try to display the exception */
1897 return 0;
1898 }
1899
1900 PyErr_NormalizeException(&exception, &v, &tb);
1901 if (tb == NULL) {
1902 tb = Py_None;
1903 Py_INCREF(tb);
1904 }
1905 PyException_SetTraceback(v, tb);
1906 if (exception == NULL) {
1907 /* PyErr_NormalizeException() failed */
1908 return 0;
1909 }
1910
1911 has_tb = (tb != Py_None);
1912 PyErr_Display(exception, v, tb);
1913 Py_XDECREF(exception);
1914 Py_XDECREF(v);
1915 Py_XDECREF(tb);
1916
1917 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001918 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001919 if (res == NULL)
1920 PyErr_Clear();
1921 else
1922 Py_DECREF(res);
1923
1924 return has_tb;
1925}
1926
Nick Coghland6009512014-11-20 21:39:37 +10001927/* Print fatal error message and abort */
1928
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001929#ifdef MS_WINDOWS
1930static void
1931fatal_output_debug(const char *msg)
1932{
1933 /* buffer of 256 bytes allocated on the stack */
1934 WCHAR buffer[256 / sizeof(WCHAR)];
1935 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1936 size_t msglen;
1937
1938 OutputDebugStringW(L"Fatal Python error: ");
1939
1940 msglen = strlen(msg);
1941 while (msglen) {
1942 size_t i;
1943
1944 if (buflen > msglen) {
1945 buflen = msglen;
1946 }
1947
1948 /* Convert the message to wchar_t. This uses a simple one-to-one
1949 conversion, assuming that the this error message actually uses
1950 ASCII only. If this ceases to be true, we will have to convert. */
1951 for (i=0; i < buflen; ++i) {
1952 buffer[i] = msg[i];
1953 }
1954 buffer[i] = L'\0';
1955 OutputDebugStringW(buffer);
1956
1957 msg += buflen;
1958 msglen -= buflen;
1959 }
1960 OutputDebugStringW(L"\n");
1961}
1962#endif
1963
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001964static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001965fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001966{
1967 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001968 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001969
1970 if (reentrant) {
1971 /* Py_FatalError() caused a second fatal error.
1972 Example: flush_std_files() raises a recursion error. */
1973 goto exit;
1974 }
1975 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001976
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001977 fprintf(stderr, "Fatal Python error: ");
1978 if (prefix) {
1979 fputs(prefix, stderr);
1980 fputs(": ", stderr);
1981 }
1982 if (msg) {
1983 fputs(msg, stderr);
1984 }
1985 else {
1986 fprintf(stderr, "<message not set>");
1987 }
1988 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001989 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001990
Victor Stinner3a228ab2018-11-01 00:26:41 +01001991 /* Check if the current thread has a Python thread state
1992 and holds the GIL */
1993 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
1994 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01001995 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01001996 if (tss_tstate != tstate) {
1997 /* The Python thread does not hold the GIL */
1998 tss_tstate = NULL;
1999 }
2000 }
2001 else {
2002 /* Py_FatalError() has been called from a C thread
2003 which has no Python thread state. */
2004 }
2005 int has_tstate_and_gil = (tss_tstate != NULL);
2006
2007 if (has_tstate_and_gil) {
2008 /* If an exception is set, print the exception with its traceback */
2009 if (!_Py_FatalError_PrintExc(fd)) {
2010 /* No exception is set, or an exception is set without traceback */
2011 _Py_FatalError_DumpTracebacks(fd);
2012 }
2013 }
2014 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002015 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002016 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002017
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002018 /* The main purpose of faulthandler is to display the traceback.
2019 This function already did its best to display a traceback.
2020 Disable faulthandler to prevent writing a second traceback
2021 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002022 _PyFaulthandler_Fini();
2023
Victor Stinner791da1c2016-03-14 16:53:12 +01002024 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002025 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002026 /* Flush sys.stdout and sys.stderr */
2027 flush_std_files();
2028 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002029
Nick Coghland6009512014-11-20 21:39:37 +10002030#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002031 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002032#endif /* MS_WINDOWS */
2033
2034exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002035 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002036#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002037 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002038#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002039 abort();
2040 }
2041 else {
2042 exit(status);
2043 }
2044}
2045
Victor Stinner19760862017-12-20 01:41:59 +01002046void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002047Py_FatalError(const char *msg)
2048{
2049 fatal_error(NULL, msg, -1);
2050}
2051
Victor Stinner19760862017-12-20 01:41:59 +01002052void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002053_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002054{
Victor Stinnerdfe88472019-03-01 12:14:41 +01002055 if (err.exitcode >= 0) {
2056 exit(err.exitcode);
2057 }
2058 else {
2059 /* On "user" error: exit with status 1.
2060 For all other errors, call abort(). */
2061 int status = err.user_err ? 1 : -1;
2062 fatal_error(err.prefix, err.msg, status);
2063 }
Nick Coghland6009512014-11-20 21:39:37 +10002064}
2065
2066/* Clean up and exit */
2067
Victor Stinnerd7292b52016-06-17 12:29:00 +02002068# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002069
Nick Coghland6009512014-11-20 21:39:37 +10002070/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002071void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002072{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002073 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002074
Antoine Pitroufc5db952017-12-13 02:29:07 +01002075 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002076 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2077
2078 is->pyexitfunc = func;
2079 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002080}
2081
2082static void
Marcel Plch776407f2017-12-20 11:17:58 +01002083call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002084{
Marcel Plch776407f2017-12-20 11:17:58 +01002085 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002086 return;
2087
Marcel Plch776407f2017-12-20 11:17:58 +01002088 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002089 PyErr_Clear();
2090}
2091
2092/* Wait until threading._shutdown completes, provided
2093 the threading module was imported in the first place.
2094 The shutdown routine will wait until all non-daemon
2095 "threading" threads have completed. */
2096static void
2097wait_for_thread_shutdown(void)
2098{
Nick Coghland6009512014-11-20 21:39:37 +10002099 _Py_IDENTIFIER(_shutdown);
2100 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002101 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002102 if (threading == NULL) {
2103 /* threading not imported */
2104 PyErr_Clear();
2105 return;
2106 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002107 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002108 if (result == NULL) {
2109 PyErr_WriteUnraisable(threading);
2110 }
2111 else {
2112 Py_DECREF(result);
2113 }
2114 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002115}
2116
2117#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002118int Py_AtExit(void (*func)(void))
2119{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002120 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002121 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002122 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002123 return 0;
2124}
2125
2126static void
2127call_ll_exitfuncs(void)
2128{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002129 while (_PyRuntime.nexitfuncs > 0)
2130 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002131
2132 fflush(stdout);
2133 fflush(stderr);
2134}
2135
Victor Stinnercfc88312018-08-01 16:41:25 +02002136void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002137Py_Exit(int sts)
2138{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002139 if (Py_FinalizeEx() < 0) {
2140 sts = 120;
2141 }
Nick Coghland6009512014-11-20 21:39:37 +10002142
2143 exit(sts);
2144}
2145
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002146static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002147initsigs(void)
2148{
2149#ifdef SIGPIPE
2150 PyOS_setsig(SIGPIPE, SIG_IGN);
2151#endif
2152#ifdef SIGXFZ
2153 PyOS_setsig(SIGXFZ, SIG_IGN);
2154#endif
2155#ifdef SIGXFSZ
2156 PyOS_setsig(SIGXFSZ, SIG_IGN);
2157#endif
2158 PyOS_InitInterrupts(); /* May imply initsignal() */
2159 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002160 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002161 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002162 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002163}
2164
2165
2166/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2167 *
2168 * All of the code in this function must only use async-signal-safe functions,
2169 * listed at `man 7 signal` or
2170 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2171 */
2172void
2173_Py_RestoreSignals(void)
2174{
2175#ifdef SIGPIPE
2176 PyOS_setsig(SIGPIPE, SIG_DFL);
2177#endif
2178#ifdef SIGXFZ
2179 PyOS_setsig(SIGXFZ, SIG_DFL);
2180#endif
2181#ifdef SIGXFSZ
2182 PyOS_setsig(SIGXFSZ, SIG_DFL);
2183#endif
2184}
2185
2186
2187/*
2188 * The file descriptor fd is considered ``interactive'' if either
2189 * a) isatty(fd) is TRUE, or
2190 * b) the -i flag was given, and the filename associated with
2191 * the descriptor is NULL or "<stdin>" or "???".
2192 */
2193int
2194Py_FdIsInteractive(FILE *fp, const char *filename)
2195{
2196 if (isatty((int)fileno(fp)))
2197 return 1;
2198 if (!Py_InteractiveFlag)
2199 return 0;
2200 return (filename == NULL) ||
2201 (strcmp(filename, "<stdin>") == 0) ||
2202 (strcmp(filename, "???") == 0);
2203}
2204
2205
Nick Coghland6009512014-11-20 21:39:37 +10002206/* Wrappers around sigaction() or signal(). */
2207
2208PyOS_sighandler_t
2209PyOS_getsig(int sig)
2210{
2211#ifdef HAVE_SIGACTION
2212 struct sigaction context;
2213 if (sigaction(sig, NULL, &context) == -1)
2214 return SIG_ERR;
2215 return context.sa_handler;
2216#else
2217 PyOS_sighandler_t handler;
2218/* Special signal handling for the secure CRT in Visual Studio 2005 */
2219#if defined(_MSC_VER) && _MSC_VER >= 1400
2220 switch (sig) {
2221 /* Only these signals are valid */
2222 case SIGINT:
2223 case SIGILL:
2224 case SIGFPE:
2225 case SIGSEGV:
2226 case SIGTERM:
2227 case SIGBREAK:
2228 case SIGABRT:
2229 break;
2230 /* Don't call signal() with other values or it will assert */
2231 default:
2232 return SIG_ERR;
2233 }
2234#endif /* _MSC_VER && _MSC_VER >= 1400 */
2235 handler = signal(sig, SIG_IGN);
2236 if (handler != SIG_ERR)
2237 signal(sig, handler);
2238 return handler;
2239#endif
2240}
2241
2242/*
2243 * All of the code in this function must only use async-signal-safe functions,
2244 * listed at `man 7 signal` or
2245 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2246 */
2247PyOS_sighandler_t
2248PyOS_setsig(int sig, PyOS_sighandler_t handler)
2249{
2250#ifdef HAVE_SIGACTION
2251 /* Some code in Modules/signalmodule.c depends on sigaction() being
2252 * used here if HAVE_SIGACTION is defined. Fix that if this code
2253 * changes to invalidate that assumption.
2254 */
2255 struct sigaction context, ocontext;
2256 context.sa_handler = handler;
2257 sigemptyset(&context.sa_mask);
2258 context.sa_flags = 0;
2259 if (sigaction(sig, &context, &ocontext) == -1)
2260 return SIG_ERR;
2261 return ocontext.sa_handler;
2262#else
2263 PyOS_sighandler_t oldhandler;
2264 oldhandler = signal(sig, handler);
2265#ifdef HAVE_SIGINTERRUPT
2266 siginterrupt(sig, 1);
2267#endif
2268 return oldhandler;
2269#endif
2270}
2271
2272#ifdef __cplusplus
2273}
2274#endif