blob: 1d65d3b86f7277be4ac8e7edbe9e6c18fd5f4029 [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 Stinner06e76082018-09-19 14:56:36 -0700290 if (core_config->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
483 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
484 Py_Initialize() ignores the new configuration. */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200485 if (core_config->allocator != NULL) {
486 const char *allocator = _PyMem_GetAllocatorsName();
487 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
488 return _Py_INIT_USER_ERR("cannot modify memory allocator "
489 "after first Py_Initialize()");
490 }
491 }
492
493 _PyCoreConfig_SetGlobalConfig(core_config);
494
495 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
496 return _Py_INIT_ERR("failed to copy core config");
497 }
498 core_config = &interp->core_config;
499
500 if (core_config->_install_importlib) {
501 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
502 if (_Py_INIT_FAILED(err)) {
503 return err;
504 }
505 }
506 return _Py_INIT_OK();
507}
508
509
Victor Stinner1dc6e392018-07-25 02:49:17 +0200510static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100511pycore_init_runtime(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000512{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200513 if (_PyRuntime.initialized) {
514 return _Py_INIT_ERR("main interpreter already initialized");
515 }
Victor Stinnerda273412017-12-15 01:46:02 +0100516
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200517 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000518
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100519 _PyInitError err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800520 if (_Py_INIT_FAILED(err)) {
521 return err;
522 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600523
Victor Stinner31e99082017-12-20 23:41:38 +0100524 if (core_config->allocator != NULL) {
525 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
526 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
527 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800528 }
529
Eric Snow1abcf672017-05-23 21:46:51 -0700530 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
531 * threads behave a little more gracefully at interpreter shutdown.
532 * We clobber it here so the new interpreter can start with a clean
533 * slate.
534 *
535 * However, this may still lead to misbehaviour if there are daemon
536 * threads still hanging around from a previous Py_Initialize/Finalize
537 * pair :(
538 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600539 _PyRuntime.finalizing = NULL;
540
Victor Stinnerda273412017-12-15 01:46:02 +0100541 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800542 if (_Py_INIT_FAILED(err)) {
543 return err;
544 }
545
Victor Stinnera7368ac2017-11-15 18:11:45 -0800546 err = _PyInterpreterState_Enable(&_PyRuntime);
547 if (_Py_INIT_FAILED(err)) {
548 return err;
549 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100550 return _Py_INIT_OK();
551}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800552
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100553
554static _PyInitError
555pycore_create_interpreter(const _PyCoreConfig *core_config,
556 PyInterpreterState **interp_p)
557{
558 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100559 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800560 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100561 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200562 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100563
564 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
565 return _Py_INIT_ERR("failed to copy core config");
566 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200567 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000568
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200569 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000570 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800571 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000572 (void) PyThreadState_Swap(tstate);
573
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000574 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000575 destroying the GIL might fail when it is being referenced from
576 another running thread (see issue #9901).
577 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000578 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000579 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100580
Nick Coghland6009512014-11-20 21:39:37 +1000581 /* Auto-thread-state API */
582 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000583
Victor Stinner2914bb32018-01-29 11:57:45 +0100584 /* Create the GIL */
585 PyEval_InitThreads();
586
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100587 return _Py_INIT_OK();
588}
Nick Coghland6009512014-11-20 21:39:37 +1000589
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100590
591static _PyInitError
592pycore_init_types(void)
593{
Victor Stinnerab672812019-01-23 15:04:40 +0100594 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100595 if (_Py_INIT_FAILED(err)) {
596 return err;
597 }
598
599 err = _PyUnicode_Init();
600 if (_Py_INIT_FAILED(err)) {
601 return err;
602 }
603
604 if (_PyStructSequence_Init() < 0) {
605 return _Py_INIT_ERR("can't initialize structseq");
606 }
607
608 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800609 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100610 }
Nick Coghland6009512014-11-20 21:39:37 +1000611
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100612 err = _PyExc_Init();
613 if (_Py_INIT_FAILED(err)) {
614 return err;
615 }
616
617 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800618 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100619 }
Nick Coghland6009512014-11-20 21:39:37 +1000620
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100621 if (!_PyContext_Init()) {
622 return _Py_INIT_ERR("can't init context");
623 }
624 return _Py_INIT_OK();
625}
626
627
628static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100629pycore_init_builtins(PyInterpreterState *interp)
630{
631 PyObject *bimod = _PyBuiltin_Init();
632 if (bimod == NULL) {
633 return _Py_INIT_ERR("can't initialize builtins modules");
634 }
635 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
636
637 interp->builtins = PyModule_GetDict(bimod);
638 if (interp->builtins == NULL) {
639 return _Py_INIT_ERR("can't initialize builtins dict");
640 }
641 Py_INCREF(interp->builtins);
642
643 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
644 if (_Py_INIT_FAILED(err)) {
645 return err;
646 }
647 return _Py_INIT_OK();
648}
649
650
651static _PyInitError
652pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
653{
654 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800655 if (_Py_INIT_FAILED(err)) {
656 return err;
657 }
Nick Coghland6009512014-11-20 21:39:37 +1000658
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800659 err = _PyImportHooks_Init();
660 if (_Py_INIT_FAILED(err)) {
661 return err;
662 }
Nick Coghland6009512014-11-20 21:39:37 +1000663
664 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100665 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100666 return _Py_INIT_ERR("can't initialize warnings");
667 }
Nick Coghland6009512014-11-20 21:39:37 +1000668
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100669 if (interp->core_config._install_importlib) {
670 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200671 if (_Py_INIT_FAILED(err)) {
672 return err;
673 }
674 }
675
Eric Snow1abcf672017-05-23 21:46:51 -0700676 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100677 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800678 err = initimport(interp, sysmod);
679 if (_Py_INIT_FAILED(err)) {
680 return err;
681 }
Eric Snow1abcf672017-05-23 21:46:51 -0700682 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100683 return _Py_INIT_OK();
684}
685
686
687static _PyInitError
688_Py_InitializeCore_impl(PyInterpreterState **interp_p,
689 const _PyCoreConfig *core_config)
690{
691 PyInterpreterState *interp;
692
693 _PyInitError err = pycore_init_runtime(core_config);
694 if (_Py_INIT_FAILED(err)) {
695 return err;
696 }
697
698 err = pycore_create_interpreter(core_config, &interp);
699 if (_Py_INIT_FAILED(err)) {
700 return err;
701 }
702 core_config = &interp->core_config;
703 *interp_p = interp;
704
705 err = pycore_init_types();
706 if (_Py_INIT_FAILED(err)) {
707 return err;
708 }
709
710 PyObject *sysmod;
Victor Stinnerab672812019-01-23 15:04:40 +0100711 err = _PySys_Create(interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100712 if (_Py_INIT_FAILED(err)) {
713 return err;
714 }
715
716 err = pycore_init_builtins(interp);
717 if (_Py_INIT_FAILED(err)) {
718 return err;
719 }
720
721 err = pycore_init_import_warnings(interp, sysmod);
722 if (_Py_INIT_FAILED(err)) {
723 return err;
724 }
Eric Snow1abcf672017-05-23 21:46:51 -0700725
726 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600727 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800728 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700729}
730
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100731/* Begin interpreter initialization
732 *
733 * On return, the first thread and interpreter state have been created,
734 * but the compiler, signal handling, multithreading and
735 * multiple interpreter support, and codec infrastructure are not yet
736 * available.
737 *
738 * The import system will support builtin and frozen modules only.
739 * The only supported io is writing to sys.stderr
740 *
741 * If any operation invoked by this function fails, a fatal error is
742 * issued and the function does not return.
743 *
744 * Any code invoked from this function should *not* assume it has access
745 * to the Python C API (unless the API is explicitly listed as being
746 * safe to call without calling Py_Initialize first)
747 */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200748_PyInitError
749_Py_InitializeCore(PyInterpreterState **interp_p,
750 const _PyCoreConfig *src_config)
751{
752 assert(src_config != NULL);
753
Victor Stinner1dc6e392018-07-25 02:49:17 +0200754 PyMemAllocatorEx old_alloc;
755 _PyInitError err;
756
757 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
758 (and the input configuration is read only). */
759 _PyCoreConfig config = _PyCoreConfig_INIT;
760
Victor Stinner177d9212018-08-29 11:25:15 +0200761 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200762 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200763
Victor Stinner1dc6e392018-07-25 02:49:17 +0200764 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
765 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
766 err = _PyCoreConfig_Read(&config);
767 }
768 else {
769 err = _Py_INIT_ERR("failed to copy core config");
770 }
771 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
772
773 if (_Py_INIT_FAILED(err)) {
774 goto done;
775 }
776
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100777 if (!_PyRuntime.core_initialized) {
778 err = _Py_InitializeCore_impl(interp_p, &config);
779 }
780 else {
781 err = _Py_Initialize_ReconfigureCore(interp_p, &config);
782 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200783
784done:
785 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
786 _PyCoreConfig_Clear(&config);
787 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
788
789 return err;
790}
791
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200792/* Py_Initialize() has already been called: update the main interpreter
793 configuration. Example of bpo-34008: Py_Main() called after
794 Py_Initialize(). */
795static _PyInitError
796_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
797 const _PyMainInterpreterConfig *config)
798{
799 if (config->argv != NULL) {
800 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
801 if (res < 0) {
802 return _Py_INIT_ERR("fail to set sys.argv");
803 }
804 }
805 return _Py_INIT_OK();
806}
807
Eric Snowc7ec9982017-05-23 23:00:52 -0700808/* Update interpreter state based on supplied configuration settings
809 *
810 * After calling this function, most of the restrictions on the interpreter
811 * are lifted. The only remaining incomplete settings are those related
812 * to the main module (sys.argv[0], __main__ metadata)
813 *
814 * Calling this when the interpreter is not initializing, is already
815 * initialized or without a valid current thread state is a fatal error.
816 * Other errors should be reported as normal Python exceptions with a
817 * non-zero return code.
818 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800819_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200820_Py_InitializeMainInterpreter(PyInterpreterState *interp,
821 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700822{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600823 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800824 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700825 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700826
Victor Stinner1dc6e392018-07-25 02:49:17 +0200827 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100828 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
829 return _Py_INIT_ERR("failed to copy main interpreter config");
830 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200831 config = &interp->config;
832 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700833
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200834 if (_PyRuntime.initialized) {
835 return _Py_ReconfigureMainInterpreter(interp, config);
836 }
837
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200838 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700839 /* Special mode for freeze_importlib: run with no import system
840 *
841 * This means anything which needs support from extension modules
842 * or pure Python code in the standard library won't work.
843 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600844 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800845 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700846 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100847
Victor Stinner33c377e2017-12-05 15:12:41 +0100848 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800849 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100850 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200851
Victor Stinnerab672812019-01-23 15:04:40 +0100852 if (_PySys_InitMain(interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800853 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100854 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800855
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200856 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800857 if (_Py_INIT_FAILED(err)) {
858 return err;
859 }
Nick Coghland6009512014-11-20 21:39:37 +1000860
861 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200862 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800863 if (_Py_INIT_FAILED(err)) {
864 return err;
865 }
Nick Coghland6009512014-11-20 21:39:37 +1000866
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800867 err = initfsencoding(interp);
868 if (_Py_INIT_FAILED(err)) {
869 return err;
870 }
Nick Coghland6009512014-11-20 21:39:37 +1000871
Victor Stinner1f151112017-11-23 10:43:14 +0100872 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800873 err = initsigs(); /* Signal handling stuff, including initintr() */
874 if (_Py_INIT_FAILED(err)) {
875 return err;
876 }
877 }
Nick Coghland6009512014-11-20 21:39:37 +1000878
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200879 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800880 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200881 }
Nick Coghland6009512014-11-20 21:39:37 +1000882
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800883 err = add_main_module(interp);
884 if (_Py_INIT_FAILED(err)) {
885 return err;
886 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800887
Victor Stinner91106cd2017-12-13 12:29:09 +0100888 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800889 if (_Py_INIT_FAILED(err)) {
890 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800891 }
Nick Coghland6009512014-11-20 21:39:37 +1000892
893 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100894 PyObject *warnoptions = PySys_GetObject("warnoptions");
895 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100896 {
Nick Coghland6009512014-11-20 21:39:37 +1000897 PyObject *warnings_module = PyImport_ImportModule("warnings");
898 if (warnings_module == NULL) {
899 fprintf(stderr, "'import warnings' failed; traceback:\n");
900 PyErr_Print();
901 }
902 Py_XDECREF(warnings_module);
903 }
904
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600905 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700906
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200907 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800908 err = initsite(); /* Module site */
909 if (_Py_INIT_FAILED(err)) {
910 return err;
911 }
912 }
Victor Stinnercf215042018-08-29 22:56:06 +0200913
914#ifndef MS_WINDOWS
915 _emit_stderr_warning_for_legacy_locale(core_config);
916#endif
917
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800918 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000919}
920
Eric Snowc7ec9982017-05-23 23:00:52 -0700921#undef _INIT_DEBUG_PRINT
922
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800923_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200924_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700925{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700926 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200928 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800929 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200930 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200932 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100933
Victor Stinner9cfc0022017-12-20 19:36:46 +0100934 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200935 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100936 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200937 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800938 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100939 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800940 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200941 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800942 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200943 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700944}
945
946
947void
Nick Coghland6009512014-11-20 21:39:37 +1000948Py_InitializeEx(int install_sigs)
949{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200950 if (_PyRuntime.initialized) {
951 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
952 return;
953 }
954
955 _PyInitError err;
956 _PyCoreConfig config = _PyCoreConfig_INIT;
957 config.install_signal_handlers = install_sigs;
958
959 err = _Py_InitializeFromConfig(&config);
960 _PyCoreConfig_Clear(&config);
961
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800962 if (_Py_INIT_FAILED(err)) {
963 _Py_FatalInitError(err);
964 }
Nick Coghland6009512014-11-20 21:39:37 +1000965}
966
967void
968Py_Initialize(void)
969{
970 Py_InitializeEx(1);
971}
972
973
974#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000975extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000976#endif
977
978/* Flush stdout and stderr */
979
980static int
981file_is_closed(PyObject *fobj)
982{
983 int r;
984 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
985 if (tmp == NULL) {
986 PyErr_Clear();
987 return 0;
988 }
989 r = PyObject_IsTrue(tmp);
990 Py_DECREF(tmp);
991 if (r < 0)
992 PyErr_Clear();
993 return r > 0;
994}
995
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000996static int
Nick Coghland6009512014-11-20 21:39:37 +1000997flush_std_files(void)
998{
999 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1000 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1001 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001002 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001003
1004 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001005 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001006 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001007 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001008 status = -1;
1009 }
Nick Coghland6009512014-11-20 21:39:37 +10001010 else
1011 Py_DECREF(tmp);
1012 }
1013
1014 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001015 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001016 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001017 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001018 status = -1;
1019 }
Nick Coghland6009512014-11-20 21:39:37 +10001020 else
1021 Py_DECREF(tmp);
1022 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001023
1024 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001025}
1026
1027/* Undo the effect of Py_Initialize().
1028
1029 Beware: if multiple interpreter and/or thread states exist, these
1030 are not wiped out; only the current thread and interpreter state
1031 are deleted. But since everything else is deleted, those other
1032 interpreter and thread states should no longer be used.
1033
1034 (XXX We should do better, e.g. wipe out all interpreters and
1035 threads.)
1036
1037 Locking: as above.
1038
1039*/
1040
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001041int
1042Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001043{
1044 PyInterpreterState *interp;
1045 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001046 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001047
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001048 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001049 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001050
1051 wait_for_thread_shutdown();
1052
Marcel Plch776407f2017-12-20 11:17:58 +01001053 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001054 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001055 interp = tstate->interp;
1056
Nick Coghland6009512014-11-20 21:39:37 +10001057 /* The interpreter is still entirely intact at this point, and the
1058 * exit funcs may be relying on that. In particular, if some thread
1059 * or exit func is still waiting to do an import, the import machinery
1060 * expects Py_IsInitialized() to return true. So don't say the
1061 * interpreter is uninitialized until after the exit funcs have run.
1062 * Note that Threading.py uses an exit func to do a join on all the
1063 * threads created thru it, so this also protects pending imports in
1064 * the threads created via Threading.
1065 */
Nick Coghland6009512014-11-20 21:39:37 +10001066
Marcel Plch776407f2017-12-20 11:17:58 +01001067 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001068
Victor Stinnerda273412017-12-15 01:46:02 +01001069 /* Copy the core config, PyInterpreterState_Delete() free
1070 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001071#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001072 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001073#endif
1074#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001075 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001076#endif
1077#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001078 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001079#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001080
Nick Coghland6009512014-11-20 21:39:37 +10001081 /* Remaining threads (e.g. daemon threads) will automatically exit
1082 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001083 _PyRuntime.finalizing = tstate;
1084 _PyRuntime.initialized = 0;
1085 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001086
Victor Stinnere0deff32015-03-24 13:46:18 +01001087 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001088 if (flush_std_files() < 0) {
1089 status = -1;
1090 }
Nick Coghland6009512014-11-20 21:39:37 +10001091
1092 /* Disable signal handling */
1093 PyOS_FiniInterrupts();
1094
1095 /* Collect garbage. This may call finalizers; it's nice to call these
1096 * before all modules are destroyed.
1097 * XXX If a __del__ or weakref callback is triggered here, and tries to
1098 * XXX import a module, bad things can happen, because Python no
1099 * XXX longer believes it's initialized.
1100 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1101 * XXX is easy to provoke that way. I've also seen, e.g.,
1102 * XXX Exception exceptions.ImportError: 'No module named sha'
1103 * XXX in <function callback at 0x008F5718> ignored
1104 * XXX but I'm unclear on exactly how that one happens. In any case,
1105 * XXX I haven't seen a real-life report of either of these.
1106 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001107 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001108#ifdef COUNT_ALLOCS
1109 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1110 each collection might release some types from the type
1111 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001112 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001113 /* nothing */;
1114#endif
Eric Snowdae02762017-09-14 00:35:58 -07001115
Nick Coghland6009512014-11-20 21:39:37 +10001116 /* Destroy all modules */
1117 PyImport_Cleanup();
1118
Victor Stinnere0deff32015-03-24 13:46:18 +01001119 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001120 if (flush_std_files() < 0) {
1121 status = -1;
1122 }
Nick Coghland6009512014-11-20 21:39:37 +10001123
1124 /* Collect final garbage. This disposes of cycles created by
1125 * class definitions, for example.
1126 * XXX This is disabled because it caused too many problems. If
1127 * XXX a __del__ or weakref callback triggers here, Python code has
1128 * XXX a hard time running, because even the sys module has been
1129 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1130 * XXX One symptom is a sequence of information-free messages
1131 * XXX coming from threads (if a __del__ or callback is invoked,
1132 * XXX other threads can execute too, and any exception they encounter
1133 * XXX triggers a comedy of errors as subsystem after subsystem
1134 * XXX fails to find what it *expects* to find in sys to help report
1135 * XXX the exception and consequent unexpected failures). I've also
1136 * XXX seen segfaults then, after adding print statements to the
1137 * XXX Python code getting called.
1138 */
1139#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001140 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001141#endif
1142
1143 /* Disable tracemalloc after all Python objects have been destroyed,
1144 so it is possible to use tracemalloc in objects destructor. */
1145 _PyTraceMalloc_Fini();
1146
1147 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1148 _PyImport_Fini();
1149
1150 /* Cleanup typeobject.c's internal caches. */
1151 _PyType_Fini();
1152
1153 /* unload faulthandler module */
1154 _PyFaulthandler_Fini();
1155
1156 /* Debugging stuff */
1157#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001158 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001159#endif
1160 /* dump hash stats */
1161 _PyHash_Fini();
1162
Eric Snowdae02762017-09-14 00:35:58 -07001163#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001164 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001165 _PyDebug_PrintTotalRefs();
1166 }
Eric Snowdae02762017-09-14 00:35:58 -07001167#endif
Nick Coghland6009512014-11-20 21:39:37 +10001168
1169#ifdef Py_TRACE_REFS
1170 /* Display all objects still alive -- this can invoke arbitrary
1171 * __repr__ overrides, so requires a mostly-intact interpreter.
1172 * Alas, a lot of stuff may still be alive now that will be cleaned
1173 * up later.
1174 */
Victor Stinnerda273412017-12-15 01:46:02 +01001175 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001176 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001177 }
Nick Coghland6009512014-11-20 21:39:37 +10001178#endif /* Py_TRACE_REFS */
1179
1180 /* Clear interpreter state and all thread states. */
1181 PyInterpreterState_Clear(interp);
1182
1183 /* Now we decref the exception classes. After this point nothing
1184 can raise an exception. That's okay, because each Fini() method
1185 below has been checked to make sure no exceptions are ever
1186 raised.
1187 */
1188
1189 _PyExc_Fini();
1190
1191 /* Sundry finalizers */
1192 PyMethod_Fini();
1193 PyFrame_Fini();
1194 PyCFunction_Fini();
1195 PyTuple_Fini();
1196 PyList_Fini();
1197 PySet_Fini();
1198 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001199 PyLong_Fini();
1200 PyFloat_Fini();
1201 PyDict_Fini();
1202 PySlice_Fini();
1203 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001204 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001205 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001206 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001207 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001208
1209 /* Cleanup Unicode implementation */
1210 _PyUnicode_Fini();
1211
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001212 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001213
1214 /* XXX Still allocated:
1215 - various static ad-hoc pointers to interned strings
1216 - int and float free list blocks
1217 - whatever various modules and libraries allocate
1218 */
1219
1220 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1221
1222 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001223 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001224
1225 /* Delete current thread. After this, many C API calls become crashy. */
1226 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001227
Nick Coghland6009512014-11-20 21:39:37 +10001228 PyInterpreterState_Delete(interp);
1229
1230#ifdef Py_TRACE_REFS
1231 /* Display addresses (& refcnts) of all objects still alive.
1232 * An address can be used to find the repr of the object, printed
1233 * above by _Py_PrintReferences.
1234 */
Victor Stinnerda273412017-12-15 01:46:02 +01001235 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001236 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001237 }
Nick Coghland6009512014-11-20 21:39:37 +10001238#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001239#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001240 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001241 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001242 }
Nick Coghland6009512014-11-20 21:39:37 +10001243#endif
1244
1245 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001246
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001247 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001248 return status;
1249}
1250
1251void
1252Py_Finalize(void)
1253{
1254 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001255}
1256
1257/* Create and initialize a new interpreter and thread, and return the
1258 new thread. This requires that Py_Initialize() has been called
1259 first.
1260
1261 Unsuccessful initialization yields a NULL pointer. Note that *no*
1262 exception information is available even in this case -- the
1263 exception information is held in the thread, and there is no
1264 thread.
1265
1266 Locking: as above.
1267
1268*/
1269
Victor Stinnera7368ac2017-11-15 18:11:45 -08001270static _PyInitError
1271new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001272{
1273 PyInterpreterState *interp;
1274 PyThreadState *tstate, *save_tstate;
1275 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001276 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001277
Victor Stinnera7368ac2017-11-15 18:11:45 -08001278 if (!_PyRuntime.initialized) {
1279 return _Py_INIT_ERR("Py_Initialize must be called first");
1280 }
Nick Coghland6009512014-11-20 21:39:37 +10001281
Victor Stinner8a1be612016-03-14 22:07:55 +01001282 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1283 interpreters: disable PyGILState_Check(). */
1284 _PyGILState_check_enabled = 0;
1285
Nick Coghland6009512014-11-20 21:39:37 +10001286 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001287 if (interp == NULL) {
1288 *tstate_p = NULL;
1289 return _Py_INIT_OK();
1290 }
Nick Coghland6009512014-11-20 21:39:37 +10001291
1292 tstate = PyThreadState_New(interp);
1293 if (tstate == NULL) {
1294 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001295 *tstate_p = NULL;
1296 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001297 }
1298
1299 save_tstate = PyThreadState_Swap(tstate);
1300
Eric Snow1abcf672017-05-23 21:46:51 -07001301 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001302 _PyCoreConfig *core_config;
1303 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001304 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001305 core_config = &save_tstate->interp->core_config;
1306 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001307 } else {
1308 /* No current thread state, copy from the main interpreter */
1309 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001310 core_config = &main_interp->core_config;
1311 config = &main_interp->config;
1312 }
1313
1314 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1315 return _Py_INIT_ERR("failed to copy core config");
1316 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001317 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001318 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1319 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001320 }
1321
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001322 err = _PyExc_Init();
1323 if (_Py_INIT_FAILED(err)) {
1324 return err;
1325 }
1326
Nick Coghland6009512014-11-20 21:39:37 +10001327 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001328 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001329 if (modules == NULL) {
1330 return _Py_INIT_ERR("can't make modules dictionary");
1331 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001332 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001333
Eric Snowd393c1b2017-09-14 12:18:12 -06001334 sysmod = _PyImport_FindBuiltin("sys", modules);
1335 if (sysmod != NULL) {
1336 interp->sysdict = PyModule_GetDict(sysmod);
1337 if (interp->sysdict == NULL)
1338 goto handle_error;
1339 Py_INCREF(interp->sysdict);
1340 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerab672812019-01-23 15:04:40 +01001341 if (_PySys_InitMain(interp) < 0) {
1342 return _Py_INIT_ERR("can't finish initializing sys");
1343 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001344 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001345 else if (PyErr_Occurred()) {
1346 goto handle_error;
1347 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001348
1349 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001350 if (bimod != NULL) {
1351 interp->builtins = PyModule_GetDict(bimod);
1352 if (interp->builtins == NULL)
1353 goto handle_error;
1354 Py_INCREF(interp->builtins);
1355 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001356 else if (PyErr_Occurred()) {
1357 goto handle_error;
1358 }
Nick Coghland6009512014-11-20 21:39:37 +10001359
Nick Coghland6009512014-11-20 21:39:37 +10001360 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001361 err = _PyBuiltins_AddExceptions(bimod);
1362 if (_Py_INIT_FAILED(err)) {
1363 return err;
1364 }
Nick Coghland6009512014-11-20 21:39:37 +10001365
Victor Stinnerab672812019-01-23 15:04:40 +01001366 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1367 if (_Py_INIT_FAILED(err)) {
1368 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001369 }
Nick Coghland6009512014-11-20 21:39:37 +10001370
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001371 err = _PyImportHooks_Init();
1372 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001373 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001374 }
Nick Coghland6009512014-11-20 21:39:37 +10001375
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001376 err = initimport(interp, sysmod);
1377 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001378 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001379 }
Nick Coghland6009512014-11-20 21:39:37 +10001380
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001381 err = initexternalimport(interp);
1382 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001383 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001384 }
Nick Coghland6009512014-11-20 21:39:37 +10001385
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001386 err = initfsencoding(interp);
1387 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001388 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001389 }
1390
Victor Stinner91106cd2017-12-13 12:29:09 +01001391 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001392 if (_Py_INIT_FAILED(err)) {
1393 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001394 }
1395
1396 err = add_main_module(interp);
1397 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001398 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001399 }
1400
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001401 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001402 err = initsite();
1403 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001404 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001405 }
1406 }
Nick Coghland6009512014-11-20 21:39:37 +10001407 }
1408
Victor Stinnera7368ac2017-11-15 18:11:45 -08001409 if (PyErr_Occurred()) {
1410 goto handle_error;
1411 }
Nick Coghland6009512014-11-20 21:39:37 +10001412
Victor Stinnera7368ac2017-11-15 18:11:45 -08001413 *tstate_p = tstate;
1414 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001415
Nick Coghland6009512014-11-20 21:39:37 +10001416handle_error:
1417 /* Oops, it didn't work. Undo it all. */
1418
1419 PyErr_PrintEx(0);
1420 PyThreadState_Clear(tstate);
1421 PyThreadState_Swap(save_tstate);
1422 PyThreadState_Delete(tstate);
1423 PyInterpreterState_Delete(interp);
1424
Victor Stinnera7368ac2017-11-15 18:11:45 -08001425 *tstate_p = NULL;
1426 return _Py_INIT_OK();
1427}
1428
1429PyThreadState *
1430Py_NewInterpreter(void)
1431{
1432 PyThreadState *tstate;
1433 _PyInitError err = new_interpreter(&tstate);
1434 if (_Py_INIT_FAILED(err)) {
1435 _Py_FatalInitError(err);
1436 }
1437 return tstate;
1438
Nick Coghland6009512014-11-20 21:39:37 +10001439}
1440
1441/* Delete an interpreter and its last thread. This requires that the
1442 given thread state is current, that the thread has no remaining
1443 frames, and that it is its interpreter's only remaining thread.
1444 It is a fatal error to violate these constraints.
1445
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001446 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001447 everything, regardless.)
1448
1449 Locking: as above.
1450
1451*/
1452
1453void
1454Py_EndInterpreter(PyThreadState *tstate)
1455{
1456 PyInterpreterState *interp = tstate->interp;
1457
Victor Stinner50b48572018-11-01 01:51:40 +01001458 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001459 Py_FatalError("Py_EndInterpreter: thread is not current");
1460 if (tstate->frame != NULL)
1461 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1462
Eric Snowef4ac962019-02-24 15:40:47 -08001463 // Mark as finalizing.
1464 if (interp->ceval.pending.lock != NULL) {
1465 PyThread_acquire_lock(interp->ceval.pending.lock, 1);
1466 }
1467 interp->finalizing = 1;
1468 if (interp->ceval.pending.lock != NULL) {
1469 PyThread_release_lock(interp->ceval.pending.lock);
1470 }
1471
1472 // Wrap up existing threads.
Nick Coghland6009512014-11-20 21:39:37 +10001473 wait_for_thread_shutdown();
1474
Eric Snowef4ac962019-02-24 15:40:47 -08001475 // Make any pending calls.
1476 if (_Py_atomic_load_relaxed(
1477 &(interp->ceval.pending.calls_to_do)))
1478 {
1479 // XXX Ensure that the interpreter is running in the current thread?
1480 if (_Py_MakePendingCalls(interp) < 0) {
1481 PyObject *exc, *val, *tb;
1482 PyErr_Fetch(&exc, &val, &tb);
1483 PyErr_BadInternalCall();
1484 _PyErr_ChainExceptions(exc, val, tb);
1485 PyErr_Print();
1486 }
1487 }
1488
Marcel Plch776407f2017-12-20 11:17:58 +01001489 call_py_exitfuncs(interp);
1490
Nick Coghland6009512014-11-20 21:39:37 +10001491 if (tstate != interp->tstate_head || tstate->next != NULL)
1492 Py_FatalError("Py_EndInterpreter: not the last thread");
1493
1494 PyImport_Cleanup();
1495 PyInterpreterState_Clear(interp);
1496 PyThreadState_Swap(NULL);
1497 PyInterpreterState_Delete(interp);
1498}
1499
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001500/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001501
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001502static _PyInitError
1503add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001504{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001505 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001506 m = PyImport_AddModule("__main__");
1507 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001508 return _Py_INIT_ERR("can't create __main__ module");
1509
Nick Coghland6009512014-11-20 21:39:37 +10001510 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001511 ann_dict = PyDict_New();
1512 if ((ann_dict == NULL) ||
1513 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001514 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001515 }
1516 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517
Nick Coghland6009512014-11-20 21:39:37 +10001518 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1519 PyObject *bimod = PyImport_ImportModule("builtins");
1520 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001521 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001522 }
1523 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001525 }
1526 Py_DECREF(bimod);
1527 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001528
Nick Coghland6009512014-11-20 21:39:37 +10001529 /* Main is a little special - imp.is_builtin("__main__") will return
1530 * False, but BuiltinImporter is still the most appropriate initial
1531 * setting for its __loader__ attribute. A more suitable value will
1532 * be set if __main__ gets further initialized later in the startup
1533 * process.
1534 */
1535 loader = PyDict_GetItemString(d, "__loader__");
1536 if (loader == NULL || loader == Py_None) {
1537 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1538 "BuiltinImporter");
1539 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001540 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001541 }
1542 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001543 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001544 }
1545 Py_DECREF(loader);
1546 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001547 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001548}
1549
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001550static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001551initfsencoding(PyInterpreterState *interp)
1552{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001553 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001554
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001555 char *encoding = get_codec_name(config->filesystem_encoding);
1556 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001557 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001558 memory, import a module of the standard library failed, etc. */
1559 return _Py_INIT_ERR("failed to get the Python codec "
1560 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001561 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001562
1563 /* Update the filesystem encoding to the normalized Python codec name.
1564 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1565 (Python codec name). */
1566 PyMem_RawFree(config->filesystem_encoding);
1567 config->filesystem_encoding = encoding;
1568
1569 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1570 global configuration variables. */
1571 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1572 config->filesystem_errors) < 0) {
1573 return _Py_INIT_NO_MEMORY();
1574 }
1575
1576 /* PyUnicode can now use the Python codec rather than C implementation
1577 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001578 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001579 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001580}
1581
1582/* Import the site module (not into __main__ though) */
1583
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001584static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001585initsite(void)
1586{
1587 PyObject *m;
1588 m = PyImport_ImportModule("site");
1589 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001590 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001591 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001592 Py_DECREF(m);
1593 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001594}
1595
Victor Stinner874dbe82015-09-04 17:29:57 +02001596/* Check if a file descriptor is valid or not.
1597 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1598static int
1599is_valid_fd(int fd)
1600{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001601#ifdef __APPLE__
1602 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1603 and the other side of the pipe is closed, dup(1) succeed, whereas
1604 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1605 such error. */
1606 struct stat st;
1607 return (fstat(fd, &st) == 0);
1608#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001609 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001610 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001611 return 0;
1612 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001613 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1614 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1615 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001616 fd2 = dup(fd);
1617 if (fd2 >= 0)
1618 close(fd2);
1619 _Py_END_SUPPRESS_IPH
1620 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001621#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001622}
1623
1624/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001625static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001626create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001627 int fd, int write_mode, const char* name,
1628 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001629{
1630 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1631 const char* mode;
1632 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001633 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001634 int buffering, isatty;
1635 _Py_IDENTIFIER(open);
1636 _Py_IDENTIFIER(isatty);
1637 _Py_IDENTIFIER(TextIOWrapper);
1638 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001639 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001640
Victor Stinner874dbe82015-09-04 17:29:57 +02001641 if (!is_valid_fd(fd))
1642 Py_RETURN_NONE;
1643
Nick Coghland6009512014-11-20 21:39:37 +10001644 /* stdin is always opened in buffered mode, first because it shouldn't
1645 make a difference in common use cases, second because TextIOWrapper
1646 depends on the presence of a read1() method which only exists on
1647 buffered streams.
1648 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001649 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001650 buffering = 0;
1651 else
1652 buffering = -1;
1653 if (write_mode)
1654 mode = "wb";
1655 else
1656 mode = "rb";
1657 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1658 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001659 Py_None, Py_None, /* encoding, errors */
1660 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001661 if (buf == NULL)
1662 goto error;
1663
1664 if (buffering) {
1665 _Py_IDENTIFIER(raw);
1666 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1667 if (raw == NULL)
1668 goto error;
1669 }
1670 else {
1671 raw = buf;
1672 Py_INCREF(raw);
1673 }
1674
Steve Dower39294992016-08-30 21:22:36 -07001675#ifdef MS_WINDOWS
1676 /* Windows console IO is always UTF-8 encoded */
1677 if (PyWindowsConsoleIO_Check(raw))
1678 encoding = "utf-8";
1679#endif
1680
Nick Coghland6009512014-11-20 21:39:37 +10001681 text = PyUnicode_FromString(name);
1682 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1683 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001684 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001685 if (res == NULL)
1686 goto error;
1687 isatty = PyObject_IsTrue(res);
1688 Py_DECREF(res);
1689 if (isatty == -1)
1690 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001691 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001692 write_through = Py_True;
1693 else
1694 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001695 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001696 line_buffering = Py_True;
1697 else
1698 line_buffering = Py_False;
1699
1700 Py_CLEAR(raw);
1701 Py_CLEAR(text);
1702
1703#ifdef MS_WINDOWS
1704 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1705 newlines to "\n".
1706 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1707 newline = NULL;
1708#else
1709 /* sys.stdin: split lines at "\n".
1710 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1711 newline = "\n";
1712#endif
1713
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001714 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001715 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001716 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001717 Py_CLEAR(buf);
1718 if (stream == NULL)
1719 goto error;
1720
1721 if (write_mode)
1722 mode = "w";
1723 else
1724 mode = "r";
1725 text = PyUnicode_FromString(mode);
1726 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1727 goto error;
1728 Py_CLEAR(text);
1729 return stream;
1730
1731error:
1732 Py_XDECREF(buf);
1733 Py_XDECREF(stream);
1734 Py_XDECREF(text);
1735 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001736
Victor Stinner874dbe82015-09-04 17:29:57 +02001737 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1738 /* Issue #24891: the file descriptor was closed after the first
1739 is_valid_fd() check was called. Ignore the OSError and set the
1740 stream to None. */
1741 PyErr_Clear();
1742 Py_RETURN_NONE;
1743 }
1744 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001745}
1746
1747/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001748static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001749init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001750{
1751 PyObject *iomod = NULL, *wrapper;
1752 PyObject *bimod = NULL;
1753 PyObject *m;
1754 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001755 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001756 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001757 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001758 _PyCoreConfig *config = &interp->core_config;
1759
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001760 /* Check that stdin is not a directory
1761 Using shell redirection, you can redirect stdin to a directory,
1762 crashing the Python interpreter. Catch this common mistake here
1763 and output a useful error message. Note that under MS Windows,
1764 the shell already prevents that. */
1765#ifndef MS_WINDOWS
1766 struct _Py_stat_struct sb;
1767 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1768 S_ISDIR(sb.st_mode)) {
1769 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1770 "cannot continue");
1771 }
1772#endif
1773
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001774 char *codec_name = get_codec_name(config->stdio_encoding);
1775 if (codec_name == NULL) {
1776 return _Py_INIT_ERR("failed to get the Python codec name "
1777 "of the stdio encoding");
1778 }
1779 PyMem_RawFree(config->stdio_encoding);
1780 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001781
1782 /* Hack to avoid a nasty recursion issue when Python is invoked
1783 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1784 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1785 goto error;
1786 }
1787 Py_DECREF(m);
1788
1789 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1790 goto error;
1791 }
1792 Py_DECREF(m);
1793
1794 if (!(bimod = PyImport_ImportModule("builtins"))) {
1795 goto error;
1796 }
1797
1798 if (!(iomod = PyImport_ImportModule("io"))) {
1799 goto error;
1800 }
1801 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1802 goto error;
1803 }
1804
1805 /* Set builtins.open */
1806 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1807 Py_DECREF(wrapper);
1808 goto error;
1809 }
1810 Py_DECREF(wrapper);
1811
Nick Coghland6009512014-11-20 21:39:37 +10001812 /* Set sys.stdin */
1813 fd = fileno(stdin);
1814 /* Under some conditions stdin, stdout and stderr may not be connected
1815 * and fileno() may point to an invalid file descriptor. For example
1816 * GUI apps don't have valid standard streams by default.
1817 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001818 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001819 config->stdio_encoding,
1820 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001821 if (std == NULL)
1822 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001823 PySys_SetObject("__stdin__", std);
1824 _PySys_SetObjectId(&PyId_stdin, std);
1825 Py_DECREF(std);
1826
1827 /* Set sys.stdout */
1828 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001829 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001830 config->stdio_encoding,
1831 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001832 if (std == NULL)
1833 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001834 PySys_SetObject("__stdout__", std);
1835 _PySys_SetObjectId(&PyId_stdout, std);
1836 Py_DECREF(std);
1837
1838#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1839 /* Set sys.stderr, replaces the preliminary stderr */
1840 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001841 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001842 config->stdio_encoding,
1843 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001844 if (std == NULL)
1845 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001846
1847 /* Same as hack above, pre-import stderr's codec to avoid recursion
1848 when import.c tries to write to stderr in verbose mode. */
1849 encoding_attr = PyObject_GetAttrString(std, "encoding");
1850 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001851 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001852 if (std_encoding != NULL) {
1853 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1854 Py_XDECREF(codec_info);
1855 }
1856 Py_DECREF(encoding_attr);
1857 }
1858 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1859
1860 if (PySys_SetObject("__stderr__", std) < 0) {
1861 Py_DECREF(std);
1862 goto error;
1863 }
1864 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1865 Py_DECREF(std);
1866 goto error;
1867 }
1868 Py_DECREF(std);
1869#endif
1870
Victor Stinnera7368ac2017-11-15 18:11:45 -08001871 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001872
Victor Stinnera7368ac2017-11-15 18:11:45 -08001873error:
1874 res = _Py_INIT_ERR("can't initialize sys standard streams");
1875
1876done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001877 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001878
Nick Coghland6009512014-11-20 21:39:37 +10001879 Py_XDECREF(bimod);
1880 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001881 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001882}
1883
1884
Victor Stinner10dc4842015-03-24 12:01:30 +01001885static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001886_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001887{
Victor Stinner10dc4842015-03-24 12:01:30 +01001888 fputc('\n', stderr);
1889 fflush(stderr);
1890
1891 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001892 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001893}
Victor Stinner791da1c2016-03-14 16:53:12 +01001894
1895/* Print the current exception (if an exception is set) with its traceback,
1896 or display the current Python stack.
1897
1898 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1899 called on catastrophic cases.
1900
1901 Return 1 if the traceback was displayed, 0 otherwise. */
1902
1903static int
1904_Py_FatalError_PrintExc(int fd)
1905{
1906 PyObject *ferr, *res;
1907 PyObject *exception, *v, *tb;
1908 int has_tb;
1909
Victor Stinner791da1c2016-03-14 16:53:12 +01001910 PyErr_Fetch(&exception, &v, &tb);
1911 if (exception == NULL) {
1912 /* No current exception */
1913 return 0;
1914 }
1915
1916 ferr = _PySys_GetObjectId(&PyId_stderr);
1917 if (ferr == NULL || ferr == Py_None) {
1918 /* sys.stderr is not set yet or set to None,
1919 no need to try to display the exception */
1920 return 0;
1921 }
1922
1923 PyErr_NormalizeException(&exception, &v, &tb);
1924 if (tb == NULL) {
1925 tb = Py_None;
1926 Py_INCREF(tb);
1927 }
1928 PyException_SetTraceback(v, tb);
1929 if (exception == NULL) {
1930 /* PyErr_NormalizeException() failed */
1931 return 0;
1932 }
1933
1934 has_tb = (tb != Py_None);
1935 PyErr_Display(exception, v, tb);
1936 Py_XDECREF(exception);
1937 Py_XDECREF(v);
1938 Py_XDECREF(tb);
1939
1940 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001941 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001942 if (res == NULL)
1943 PyErr_Clear();
1944 else
1945 Py_DECREF(res);
1946
1947 return has_tb;
1948}
1949
Nick Coghland6009512014-11-20 21:39:37 +10001950/* Print fatal error message and abort */
1951
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001952#ifdef MS_WINDOWS
1953static void
1954fatal_output_debug(const char *msg)
1955{
1956 /* buffer of 256 bytes allocated on the stack */
1957 WCHAR buffer[256 / sizeof(WCHAR)];
1958 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1959 size_t msglen;
1960
1961 OutputDebugStringW(L"Fatal Python error: ");
1962
1963 msglen = strlen(msg);
1964 while (msglen) {
1965 size_t i;
1966
1967 if (buflen > msglen) {
1968 buflen = msglen;
1969 }
1970
1971 /* Convert the message to wchar_t. This uses a simple one-to-one
1972 conversion, assuming that the this error message actually uses
1973 ASCII only. If this ceases to be true, we will have to convert. */
1974 for (i=0; i < buflen; ++i) {
1975 buffer[i] = msg[i];
1976 }
1977 buffer[i] = L'\0';
1978 OutputDebugStringW(buffer);
1979
1980 msg += buflen;
1981 msglen -= buflen;
1982 }
1983 OutputDebugStringW(L"\n");
1984}
1985#endif
1986
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001987static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001988fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001989{
1990 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001991 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001992
1993 if (reentrant) {
1994 /* Py_FatalError() caused a second fatal error.
1995 Example: flush_std_files() raises a recursion error. */
1996 goto exit;
1997 }
1998 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001999
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002000 fprintf(stderr, "Fatal Python error: ");
2001 if (prefix) {
2002 fputs(prefix, stderr);
2003 fputs(": ", stderr);
2004 }
2005 if (msg) {
2006 fputs(msg, stderr);
2007 }
2008 else {
2009 fprintf(stderr, "<message not set>");
2010 }
2011 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002012 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002013
Victor Stinner3a228ab2018-11-01 00:26:41 +01002014 /* Check if the current thread has a Python thread state
2015 and holds the GIL */
2016 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2017 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002018 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002019 if (tss_tstate != tstate) {
2020 /* The Python thread does not hold the GIL */
2021 tss_tstate = NULL;
2022 }
2023 }
2024 else {
2025 /* Py_FatalError() has been called from a C thread
2026 which has no Python thread state. */
2027 }
2028 int has_tstate_and_gil = (tss_tstate != NULL);
2029
2030 if (has_tstate_and_gil) {
2031 /* If an exception is set, print the exception with its traceback */
2032 if (!_Py_FatalError_PrintExc(fd)) {
2033 /* No exception is set, or an exception is set without traceback */
2034 _Py_FatalError_DumpTracebacks(fd);
2035 }
2036 }
2037 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002038 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002039 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002040
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002041 /* The main purpose of faulthandler is to display the traceback.
2042 This function already did its best to display a traceback.
2043 Disable faulthandler to prevent writing a second traceback
2044 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002045 _PyFaulthandler_Fini();
2046
Victor Stinner791da1c2016-03-14 16:53:12 +01002047 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002048 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002049 /* Flush sys.stdout and sys.stderr */
2050 flush_std_files();
2051 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002052
Nick Coghland6009512014-11-20 21:39:37 +10002053#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002054 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002055#endif /* MS_WINDOWS */
2056
2057exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002058 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002059#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002060 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002061#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002062 abort();
2063 }
2064 else {
2065 exit(status);
2066 }
2067}
2068
Victor Stinner19760862017-12-20 01:41:59 +01002069void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002070Py_FatalError(const char *msg)
2071{
2072 fatal_error(NULL, msg, -1);
2073}
2074
Victor Stinner19760862017-12-20 01:41:59 +01002075void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002076_Py_FatalInitError(_PyInitError err)
2077{
2078 /* On "user" error: exit with status 1.
2079 For all other errors, call abort(). */
2080 int status = err.user_err ? 1 : -1;
2081 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002082}
2083
2084/* Clean up and exit */
2085
Victor Stinnerd7292b52016-06-17 12:29:00 +02002086# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002087
Nick Coghland6009512014-11-20 21:39:37 +10002088/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002089void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002090{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002091 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002092
Antoine Pitroufc5db952017-12-13 02:29:07 +01002093 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002094 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2095
2096 is->pyexitfunc = func;
2097 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002098}
2099
2100static void
Marcel Plch776407f2017-12-20 11:17:58 +01002101call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002102{
Marcel Plch776407f2017-12-20 11:17:58 +01002103 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002104 return;
2105
Marcel Plch776407f2017-12-20 11:17:58 +01002106 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002107 PyErr_Clear();
2108}
2109
2110/* Wait until threading._shutdown completes, provided
2111 the threading module was imported in the first place.
2112 The shutdown routine will wait until all non-daemon
2113 "threading" threads have completed. */
2114static void
2115wait_for_thread_shutdown(void)
2116{
Nick Coghland6009512014-11-20 21:39:37 +10002117 _Py_IDENTIFIER(_shutdown);
2118 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002119 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002120 if (threading == NULL) {
2121 /* threading not imported */
2122 PyErr_Clear();
2123 return;
2124 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002125 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002126 if (result == NULL) {
2127 PyErr_WriteUnraisable(threading);
2128 }
2129 else {
2130 Py_DECREF(result);
2131 }
2132 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002133}
2134
2135#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002136int Py_AtExit(void (*func)(void))
2137{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002138 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002139 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002140 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002141 return 0;
2142}
2143
2144static void
2145call_ll_exitfuncs(void)
2146{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002147 while (_PyRuntime.nexitfuncs > 0)
2148 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002149
2150 fflush(stdout);
2151 fflush(stderr);
2152}
2153
Victor Stinnercfc88312018-08-01 16:41:25 +02002154void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002155Py_Exit(int sts)
2156{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002157 if (Py_FinalizeEx() < 0) {
2158 sts = 120;
2159 }
Nick Coghland6009512014-11-20 21:39:37 +10002160
2161 exit(sts);
2162}
2163
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002164static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002165initsigs(void)
2166{
2167#ifdef SIGPIPE
2168 PyOS_setsig(SIGPIPE, SIG_IGN);
2169#endif
2170#ifdef SIGXFZ
2171 PyOS_setsig(SIGXFZ, SIG_IGN);
2172#endif
2173#ifdef SIGXFSZ
2174 PyOS_setsig(SIGXFSZ, SIG_IGN);
2175#endif
2176 PyOS_InitInterrupts(); /* May imply initsignal() */
2177 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002178 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002179 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002180 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002181}
2182
2183
2184/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2185 *
2186 * All of the code in this function must only use async-signal-safe functions,
2187 * listed at `man 7 signal` or
2188 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2189 */
2190void
2191_Py_RestoreSignals(void)
2192{
2193#ifdef SIGPIPE
2194 PyOS_setsig(SIGPIPE, SIG_DFL);
2195#endif
2196#ifdef SIGXFZ
2197 PyOS_setsig(SIGXFZ, SIG_DFL);
2198#endif
2199#ifdef SIGXFSZ
2200 PyOS_setsig(SIGXFSZ, SIG_DFL);
2201#endif
2202}
2203
2204
2205/*
2206 * The file descriptor fd is considered ``interactive'' if either
2207 * a) isatty(fd) is TRUE, or
2208 * b) the -i flag was given, and the filename associated with
2209 * the descriptor is NULL or "<stdin>" or "???".
2210 */
2211int
2212Py_FdIsInteractive(FILE *fp, const char *filename)
2213{
2214 if (isatty((int)fileno(fp)))
2215 return 1;
2216 if (!Py_InteractiveFlag)
2217 return 0;
2218 return (filename == NULL) ||
2219 (strcmp(filename, "<stdin>") == 0) ||
2220 (strcmp(filename, "???") == 0);
2221}
2222
2223
Nick Coghland6009512014-11-20 21:39:37 +10002224/* Wrappers around sigaction() or signal(). */
2225
2226PyOS_sighandler_t
2227PyOS_getsig(int sig)
2228{
2229#ifdef HAVE_SIGACTION
2230 struct sigaction context;
2231 if (sigaction(sig, NULL, &context) == -1)
2232 return SIG_ERR;
2233 return context.sa_handler;
2234#else
2235 PyOS_sighandler_t handler;
2236/* Special signal handling for the secure CRT in Visual Studio 2005 */
2237#if defined(_MSC_VER) && _MSC_VER >= 1400
2238 switch (sig) {
2239 /* Only these signals are valid */
2240 case SIGINT:
2241 case SIGILL:
2242 case SIGFPE:
2243 case SIGSEGV:
2244 case SIGTERM:
2245 case SIGBREAK:
2246 case SIGABRT:
2247 break;
2248 /* Don't call signal() with other values or it will assert */
2249 default:
2250 return SIG_ERR;
2251 }
2252#endif /* _MSC_VER && _MSC_VER >= 1400 */
2253 handler = signal(sig, SIG_IGN);
2254 if (handler != SIG_ERR)
2255 signal(sig, handler);
2256 return handler;
2257#endif
2258}
2259
2260/*
2261 * All of the code in this function must only use async-signal-safe functions,
2262 * listed at `man 7 signal` or
2263 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2264 */
2265PyOS_sighandler_t
2266PyOS_setsig(int sig, PyOS_sighandler_t handler)
2267{
2268#ifdef HAVE_SIGACTION
2269 /* Some code in Modules/signalmodule.c depends on sigaction() being
2270 * used here if HAVE_SIGACTION is defined. Fix that if this code
2271 * changes to invalidate that assumption.
2272 */
2273 struct sigaction context, ocontext;
2274 context.sa_handler = handler;
2275 sigemptyset(&context.sa_mask);
2276 context.sa_flags = 0;
2277 if (sigaction(sig, &context, &ocontext) == -1)
2278 return SIG_ERR;
2279 return ocontext.sa_handler;
2280#else
2281 PyOS_sighandler_t oldhandler;
2282 oldhandler = signal(sig, handler);
2283#ifdef HAVE_SIGINTERRUPT
2284 siginterrupt(sig, 1);
2285#endif
2286 return oldhandler;
2287#endif
2288}
2289
2290#ifdef __cplusplus
2291}
2292#endif