blob: 379e860b5ba4b4eac123ef3bb00e366ad45a8ca8 [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"
6#undef Yield /* undefine macro conflicting with winbase.h */
Yury Selivanovf23746a2018-01-22 19:11:18 -05007#include "internal/context.h"
8#include "internal/hamt.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06009#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100010#include "grammar.h"
11#include "node.h"
12#include "token.h"
13#include "parsetok.h"
14#include "errcode.h"
15#include "code.h"
16#include "symtable.h"
17#include "ast.h"
18#include "marshal.h"
19#include "osdefs.h"
20#include <locale.h>
21
22#ifdef HAVE_SIGNAL_H
23#include <signal.h>
24#endif
25
26#ifdef MS_WINDOWS
27#include "malloc.h" /* for alloca */
28#endif
29
30#ifdef HAVE_LANGINFO_H
31#include <langinfo.h>
32#endif
33
34#ifdef MS_WINDOWS
35#undef BYTE
36#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070037
38extern PyTypeObject PyWindowsConsoleIO_Type;
39#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100040#endif
41
42_Py_IDENTIFIER(flush);
43_Py_IDENTIFIER(name);
44_Py_IDENTIFIER(stdin);
45_Py_IDENTIFIER(stdout);
46_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060047_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100048
49#ifdef __cplusplus
50extern "C" {
51#endif
52
Nick Coghland6009512014-11-20 21:39:37 +100053extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056static _PyInitError add_main_module(PyInterpreterState *interp);
57static _PyInitError initfsencoding(PyInterpreterState *interp);
58static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010059static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010061static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100062static void wait_for_thread_shutdown(void);
63static void call_ll_exitfuncs(void);
64extern int _PyUnicode_Init(void);
65extern int _PyStructSequence_Init(void);
66extern void _PyUnicode_Fini(void);
67extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080069extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100070extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080072extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100073extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070074extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100075
Nick Coghland6009512014-11-20 21:39:37 +100076extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082_PyRuntime_Initialize(void)
83{
84 /* XXX We only initialize once in the process, which aligns with
85 the static initialization of the former globals now found in
86 _PyRuntime. However, _PyRuntime *should* be initialized with
87 every Py_Initialize() call, but doing so breaks the runtime.
88 This is because the runtime state is not properly finalized
89 currently. */
90 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091 if (initialized) {
92 return _Py_INIT_OK();
93 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095
96 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99void
100_PyRuntime_Finalize(void)
101{
102 _PyRuntimeState_Fini(&_PyRuntime);
103}
104
105int
106_Py_IsFinalizing(void)
107{
108 return _PyRuntime.finalizing != NULL;
109}
110
Nick Coghland6009512014-11-20 21:39:37 +1000111/* Hack to force loading of object files */
112int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
113 PyOS_mystrnicmp; /* Python/pystrcmp.o */
114
115/* PyModule_GetWarningsModule is no longer necessary as of 2.6
116since _warnings is builtin. This API should not be used. */
117PyObject *
118PyModule_GetWarningsModule(void)
119{
120 return PyImport_ImportModule("warnings");
121}
122
Eric Snowc7ec9982017-05-23 23:00:52 -0700123
Eric Snow1abcf672017-05-23 21:46:51 -0700124/* APIs to access the initialization flags
125 *
126 * Can be called prior to Py_Initialize.
127 */
Nick Coghland6009512014-11-20 21:39:37 +1000128
Eric Snow1abcf672017-05-23 21:46:51 -0700129int
130_Py_IsCoreInitialized(void)
131{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600132 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700133}
Nick Coghland6009512014-11-20 21:39:37 +1000134
135int
136Py_IsInitialized(void)
137{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600138 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000139}
140
Nick Coghlan6ea41862017-06-11 13:16:15 +1000141
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000142/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
143 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000144 initializations fail, a fatal error is issued and the function does
145 not return. On return, the first thread and interpreter state have
146 been created.
147
148 Locking: you must hold the interpreter lock while calling this.
149 (If the lock has not yet been initialized, that's equivalent to
150 having the lock, but you cannot use multiple threads.)
151
152*/
153
Nick Coghland6009512014-11-20 21:39:37 +1000154static char*
155get_codec_name(const char *encoding)
156{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200157 const char *name_utf8;
158 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000159 PyObject *codec, *name = NULL;
160
161 codec = _PyCodec_Lookup(encoding);
162 if (!codec)
163 goto error;
164
165 name = _PyObject_GetAttrId(codec, &PyId_name);
166 Py_CLEAR(codec);
167 if (!name)
168 goto error;
169
Serhiy Storchaka06515832016-11-20 09:13:07 +0200170 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000171 if (name_utf8 == NULL)
172 goto error;
173 name_str = _PyMem_RawStrdup(name_utf8);
174 Py_DECREF(name);
175 if (name_str == NULL) {
176 PyErr_NoMemory();
177 return NULL;
178 }
179 return name_str;
180
181error:
182 Py_XDECREF(codec);
183 Py_XDECREF(name);
184 return NULL;
185}
186
Nick Coghland6009512014-11-20 21:39:37 +1000187
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800188static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700189initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000190{
191 PyObject *importlib;
192 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000193 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800194 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000195
196 /* Import _importlib through its frozen version, _frozen_importlib. */
197 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800198 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000199 }
200 else if (Py_VerboseFlag) {
201 PySys_FormatStderr("import _frozen_importlib # frozen\n");
202 }
203 importlib = PyImport_AddModule("_frozen_importlib");
204 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800205 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000206 }
207 interp->importlib = importlib;
208 Py_INCREF(interp->importlib);
209
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300210 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
211 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800212 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300213 Py_INCREF(interp->import_func);
214
Victor Stinnercd6e6942015-09-18 09:11:57 +0200215 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800216 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000217 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800218 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000219 }
220 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200221 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000222 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600223 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800224 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000225 }
226
Victor Stinnercd6e6942015-09-18 09:11:57 +0200227 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000228 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
229 if (value == NULL) {
230 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800231 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000232 }
233 Py_DECREF(value);
234 Py_DECREF(impmod);
235
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800236 err = _PyImportZip_Init();
237 if (_Py_INIT_FAILED(err)) {
238 return err;
239 }
240
241 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000242}
243
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800244static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700245initexternalimport(PyInterpreterState *interp)
246{
247 PyObject *value;
248 value = PyObject_CallMethod(interp->importlib,
249 "_install_external_importers", "");
250 if (value == NULL) {
251 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800252 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700253 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200254 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800255 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700256}
Nick Coghland6009512014-11-20 21:39:37 +1000257
Nick Coghlan6ea41862017-06-11 13:16:15 +1000258/* Helper functions to better handle the legacy C locale
259 *
260 * The legacy C locale assumes ASCII as the default text encoding, which
261 * causes problems not only for the CPython runtime, but also other
262 * components like GNU readline.
263 *
264 * Accordingly, when the CLI detects it, it attempts to coerce it to a
265 * more capable UTF-8 based alternative as follows:
266 *
267 * if (_Py_LegacyLocaleDetected()) {
268 * _Py_CoerceLegacyLocale();
269 * }
270 *
271 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
272 *
273 * Locale coercion also impacts the default error handler for the standard
274 * streams: while the usual default is "strict", the default for the legacy
275 * C locale and for any of the coercion target locales is "surrogateescape".
276 */
277
278int
279_Py_LegacyLocaleDetected(void)
280{
281#ifndef MS_WINDOWS
282 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000283 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
284 * the POSIX locale as a simple alias for the C locale, so
285 * we may also want to check for that explicitly.
286 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000287 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
288 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
289#else
290 /* Windows uses code pages instead of locales, so no locale is legacy */
291 return 0;
292#endif
293}
294
Nick Coghlaneb817952017-06-18 12:29:42 +1000295static const char *_C_LOCALE_WARNING =
296 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
297 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
298 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
299 "locales is recommended.\n";
300
Nick Coghlaneb817952017-06-18 12:29:42 +1000301static void
Victor Stinner94540602017-12-16 04:54:22 +0100302_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000303{
Victor Stinnercf215042018-08-29 22:56:06 +0200304 if (core_config->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
305 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000306 }
307}
308
Nick Coghlan6ea41862017-06-11 13:16:15 +1000309typedef struct _CandidateLocale {
310 const char *locale_name; /* The locale to try as a coercion target */
311} _LocaleCoercionTarget;
312
313static _LocaleCoercionTarget _TARGET_LOCALES[] = {
314 {"C.UTF-8"},
315 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000316 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000317 {NULL}
318};
319
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200320
321int
322_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000323{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200324 const _LocaleCoercionTarget *target = NULL;
325 for (target = _TARGET_LOCALES; target->locale_name; target++) {
326 if (strcmp(ctype_loc, target->locale_name) == 0) {
327 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200329 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200330 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000331}
332
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200333
Nick Coghlan6ea41862017-06-11 13:16:15 +1000334#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100335static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000336 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
337 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
338
339static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200340_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000341{
342 const char *newloc = target->locale_name;
343
344 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100345 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000346
347 /* Set the relevant locale environment variable */
348 if (setenv("LC_CTYPE", newloc, 1)) {
349 fprintf(stderr,
350 "Error setting LC_CTYPE, skipping C locale coercion\n");
351 return;
352 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200353 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100354 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000355 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000356
357 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100358 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000359}
360#endif
361
362void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200363_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000364{
365#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200366 char *oldloc = NULL;
367
368 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
369 if (oldloc == NULL) {
370 return;
371 }
372
Victor Stinner94540602017-12-16 04:54:22 +0100373 const char *locale_override = getenv("LC_ALL");
374 if (locale_override == NULL || *locale_override == '\0') {
375 /* LC_ALL is also not set (or is set to an empty string) */
376 const _LocaleCoercionTarget *target = NULL;
377 for (target = _TARGET_LOCALES; target->locale_name; target++) {
378 const char *new_locale = setlocale(LC_CTYPE,
379 target->locale_name);
380 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100381#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100382defined(HAVE_LANGINFO_H) && defined(CODESET)
383 /* Also ensure that nl_langinfo works in this locale */
384 char *codeset = nl_langinfo(CODESET);
385 if (!codeset || *codeset == '\0') {
386 /* CODESET is not set or empty, so skip coercion */
387 new_locale = NULL;
388 _Py_SetLocaleFromEnv(LC_CTYPE);
389 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000390 }
Victor Stinner94540602017-12-16 04:54:22 +0100391#endif
392 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200393 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200394 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000395 }
396 }
397 }
398 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200399
400 setlocale(LC_CTYPE, oldloc);
401
402done:
403 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000404#endif
405}
406
xdegaye1588be62017-11-12 12:45:59 +0100407/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
408 * isolate the idiosyncrasies of different libc implementations. It reads the
409 * appropriate environment variable and uses its value to select the locale for
410 * 'category'. */
411char *
412_Py_SetLocaleFromEnv(int category)
413{
414#ifdef __ANDROID__
415 const char *locale;
416 const char **pvar;
417#ifdef PY_COERCE_C_LOCALE
418 const char *coerce_c_locale;
419#endif
420 const char *utf8_locale = "C.UTF-8";
421 const char *env_var_set[] = {
422 "LC_ALL",
423 "LC_CTYPE",
424 "LANG",
425 NULL,
426 };
427
428 /* Android setlocale(category, "") doesn't check the environment variables
429 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
430 * check the environment variables listed in env_var_set. */
431 for (pvar=env_var_set; *pvar; pvar++) {
432 locale = getenv(*pvar);
433 if (locale != NULL && *locale != '\0') {
434 if (strcmp(locale, utf8_locale) == 0 ||
435 strcmp(locale, "en_US.UTF-8") == 0) {
436 return setlocale(category, utf8_locale);
437 }
438 return setlocale(category, "C");
439 }
440 }
441
442 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
443 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
444 * Quote from POSIX section "8.2 Internationalization Variables":
445 * "4. If the LANG environment variable is not set or is set to the empty
446 * string, the implementation-defined default locale shall be used." */
447
448#ifdef PY_COERCE_C_LOCALE
449 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
450 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
451 /* Some other ported code may check the environment variables (e.g. in
452 * extension modules), so we make sure that they match the locale
453 * configuration */
454 if (setenv("LC_CTYPE", utf8_locale, 1)) {
455 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
456 "environment variable to %s\n", utf8_locale);
457 }
458 }
459#endif
460 return setlocale(category, utf8_locale);
461#else /* __ANDROID__ */
462 return setlocale(category, "");
463#endif /* __ANDROID__ */
464}
465
Nick Coghlan6ea41862017-06-11 13:16:15 +1000466
Eric Snow1abcf672017-05-23 21:46:51 -0700467/* Global initializations. Can be undone by Py_Finalize(). Don't
468 call this twice without an intervening Py_Finalize() call.
469
Victor Stinner1dc6e392018-07-25 02:49:17 +0200470 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700471 must have a corresponding call to Py_Finalize.
472
473 Locking: you must hold the interpreter lock while calling these APIs.
474 (If the lock has not yet been initialized, that's equivalent to
475 having the lock, but you cannot use multiple threads.)
476
477*/
478
Victor Stinner1dc6e392018-07-25 02:49:17 +0200479static _PyInitError
480_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
481 const _PyCoreConfig *core_config)
482{
483 if (core_config->allocator != NULL) {
484 const char *allocator = _PyMem_GetAllocatorsName();
485 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
486 return _Py_INIT_USER_ERR("cannot modify memory allocator "
487 "after first Py_Initialize()");
488 }
489 }
490
491 _PyCoreConfig_SetGlobalConfig(core_config);
492
493 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
494 return _Py_INIT_ERR("failed to copy core config");
495 }
496 core_config = &interp->core_config;
497
498 if (core_config->_install_importlib) {
499 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
500 if (_Py_INIT_FAILED(err)) {
501 return err;
502 }
503 }
504 return _Py_INIT_OK();
505}
506
507
Eric Snow1abcf672017-05-23 21:46:51 -0700508/* Begin interpreter initialization
509 *
510 * On return, the first thread and interpreter state have been created,
511 * but the compiler, signal handling, multithreading and
512 * multiple interpreter support, and codec infrastructure are not yet
513 * available.
514 *
515 * The import system will support builtin and frozen modules only.
516 * The only supported io is writing to sys.stderr
517 *
518 * If any operation invoked by this function fails, a fatal error is
519 * issued and the function does not return.
520 *
521 * Any code invoked from this function should *not* assume it has access
522 * to the Python C API (unless the API is explicitly listed as being
523 * safe to call without calling Py_Initialize first)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200524 *
525 * The caller is responsible to call _PyCoreConfig_Read().
Eric Snow1abcf672017-05-23 21:46:51 -0700526 */
527
Victor Stinner1dc6e392018-07-25 02:49:17 +0200528static _PyInitError
529_Py_InitializeCore_impl(PyInterpreterState **interp_p,
530 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000531{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200532 PyInterpreterState *interp;
533 _PyInitError err;
534
535 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
536 Py_Initialize() ignores the new configuration. */
537 if (_PyRuntime.core_initialized) {
538 PyThreadState *tstate = PyThreadState_GET();
539 if (!tstate) {
540 return _Py_INIT_ERR("failed to read thread state");
541 }
542
543 interp = tstate->interp;
544 if (interp == NULL) {
545 return _Py_INIT_ERR("can't make main interpreter");
546 }
547 *interp_p = interp;
548
549 return _Py_Initialize_ReconfigureCore(interp, core_config);
550 }
551
552 if (_PyRuntime.initialized) {
553 return _Py_INIT_ERR("main interpreter already initialized");
554 }
Victor Stinnerda273412017-12-15 01:46:02 +0100555
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200556 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000557
Victor Stinner1dc6e392018-07-25 02:49:17 +0200558 err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800559 if (_Py_INIT_FAILED(err)) {
560 return err;
561 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600562
Victor Stinner31e99082017-12-20 23:41:38 +0100563 if (core_config->allocator != NULL) {
564 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
565 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
566 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800567 }
568
Eric Snow1abcf672017-05-23 21:46:51 -0700569 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
570 * threads behave a little more gracefully at interpreter shutdown.
571 * We clobber it here so the new interpreter can start with a clean
572 * slate.
573 *
574 * However, this may still lead to misbehaviour if there are daemon
575 * threads still hanging around from a previous Py_Initialize/Finalize
576 * pair :(
577 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600578 _PyRuntime.finalizing = NULL;
579
Victor Stinnerda273412017-12-15 01:46:02 +0100580 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800581 if (_Py_INIT_FAILED(err)) {
582 return err;
583 }
584
Victor Stinnera7368ac2017-11-15 18:11:45 -0800585 err = _PyInterpreterState_Enable(&_PyRuntime);
586 if (_Py_INIT_FAILED(err)) {
587 return err;
588 }
589
Victor Stinner1dc6e392018-07-25 02:49:17 +0200590 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100591 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800592 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100593 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200594 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100595
596 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
597 return _Py_INIT_ERR("failed to copy core config");
598 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200599 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000600
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200601 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000602 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800603 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000604 (void) PyThreadState_Swap(tstate);
605
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000606 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000607 destroying the GIL might fail when it is being referenced from
608 another running thread (see issue #9901).
609 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000610 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000611 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100612
Nick Coghland6009512014-11-20 21:39:37 +1000613 /* Auto-thread-state API */
614 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000615
Victor Stinner2914bb32018-01-29 11:57:45 +0100616 /* Create the GIL */
617 PyEval_InitThreads();
618
Nick Coghland6009512014-11-20 21:39:37 +1000619 _Py_ReadyTypes();
620
Nick Coghland6009512014-11-20 21:39:37 +1000621 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800622 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000623
624 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800625 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000626
627 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800628 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000629
Eric Snowd393c1b2017-09-14 12:18:12 -0600630 PyObject *modules = PyDict_New();
631 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800632 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600633 interp->modules = modules;
634
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200635 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800636 err = _PySys_BeginInit(&sysmod);
637 if (_Py_INIT_FAILED(err)) {
638 return err;
639 }
640
Eric Snowd393c1b2017-09-14 12:18:12 -0600641 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800642 if (interp->sysdict == NULL) {
643 return _Py_INIT_ERR("can't initialize sys dict");
644 }
645
Eric Snowd393c1b2017-09-14 12:18:12 -0600646 Py_INCREF(interp->sysdict);
647 PyDict_SetItemString(interp->sysdict, "modules", modules);
648 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000649
650 /* Init Unicode implementation; relies on the codec registry */
651 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800652 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700653
Nick Coghland6009512014-11-20 21:39:37 +1000654 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800655 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000656
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200657 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000658 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800659 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600660 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000661 interp->builtins = PyModule_GetDict(bimod);
662 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800663 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000664 Py_INCREF(interp->builtins);
665
666 /* initialize builtin exceptions */
667 _PyExc_Init(bimod);
668
Nick Coghland6009512014-11-20 21:39:37 +1000669 /* Set up a preliminary stderr printer until we have enough
670 infrastructure for the io module in place. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200671 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000672 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800673 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000674 _PySys_SetObjectId(&PyId_stderr, pstderr);
675 PySys_SetObject("__stderr__", pstderr);
676 Py_DECREF(pstderr);
677
Victor Stinner672b6ba2017-12-06 17:25:50 +0100678 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800679 if (_Py_INIT_FAILED(err)) {
680 return err;
681 }
Nick Coghland6009512014-11-20 21:39:37 +1000682
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800683 err = _PyImportHooks_Init();
684 if (_Py_INIT_FAILED(err)) {
685 return err;
686 }
Nick Coghland6009512014-11-20 21:39:37 +1000687
688 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100689 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100690 return _Py_INIT_ERR("can't initialize warnings");
691 }
Nick Coghland6009512014-11-20 21:39:37 +1000692
Yury Selivanovf23746a2018-01-22 19:11:18 -0500693 if (!_PyContext_Init())
694 return _Py_INIT_ERR("can't init context");
695
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200696 if (core_config->_install_importlib) {
Victor Stinnerb1147e42018-07-21 02:06:16 +0200697 err = _PyCoreConfig_SetPathConfig(core_config);
698 if (_Py_INIT_FAILED(err)) {
699 return err;
700 }
701 }
702
Eric Snow1abcf672017-05-23 21:46:51 -0700703 /* This call sets up builtin and frozen import support */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200704 if (core_config->_install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800705 err = initimport(interp, sysmod);
706 if (_Py_INIT_FAILED(err)) {
707 return err;
708 }
Eric Snow1abcf672017-05-23 21:46:51 -0700709 }
710
711 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600712 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800713 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700714}
715
Victor Stinner1dc6e392018-07-25 02:49:17 +0200716_PyInitError
717_Py_InitializeCore(PyInterpreterState **interp_p,
718 const _PyCoreConfig *src_config)
719{
720 assert(src_config != NULL);
721
Victor Stinner1dc6e392018-07-25 02:49:17 +0200722 PyMemAllocatorEx old_alloc;
723 _PyInitError err;
724
725 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
726 (and the input configuration is read only). */
727 _PyCoreConfig config = _PyCoreConfig_INIT;
728
Victor Stinner177d9212018-08-29 11:25:15 +0200729 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200730 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200731
Victor Stinner1dc6e392018-07-25 02:49:17 +0200732 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
733 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
734 err = _PyCoreConfig_Read(&config);
735 }
736 else {
737 err = _Py_INIT_ERR("failed to copy core config");
738 }
739 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
740
741 if (_Py_INIT_FAILED(err)) {
742 goto done;
743 }
744
745 err = _Py_InitializeCore_impl(interp_p, &config);
746
747done:
748 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
749 _PyCoreConfig_Clear(&config);
750 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
751
752 return err;
753}
754
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200755/* Py_Initialize() has already been called: update the main interpreter
756 configuration. Example of bpo-34008: Py_Main() called after
757 Py_Initialize(). */
758static _PyInitError
759_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
760 const _PyMainInterpreterConfig *config)
761{
762 if (config->argv != NULL) {
763 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
764 if (res < 0) {
765 return _Py_INIT_ERR("fail to set sys.argv");
766 }
767 }
768 return _Py_INIT_OK();
769}
770
Eric Snowc7ec9982017-05-23 23:00:52 -0700771/* Update interpreter state based on supplied configuration settings
772 *
773 * After calling this function, most of the restrictions on the interpreter
774 * are lifted. The only remaining incomplete settings are those related
775 * to the main module (sys.argv[0], __main__ metadata)
776 *
777 * Calling this when the interpreter is not initializing, is already
778 * initialized or without a valid current thread state is a fatal error.
779 * Other errors should be reported as normal Python exceptions with a
780 * non-zero return code.
781 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800782_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200783_Py_InitializeMainInterpreter(PyInterpreterState *interp,
784 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700785{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600786 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800787 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700788 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700789
Victor Stinner1dc6e392018-07-25 02:49:17 +0200790 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100791 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
792 return _Py_INIT_ERR("failed to copy main interpreter config");
793 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200794 config = &interp->config;
795 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700796
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200797 if (_PyRuntime.initialized) {
798 return _Py_ReconfigureMainInterpreter(interp, config);
799 }
800
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200801 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700802 /* Special mode for freeze_importlib: run with no import system
803 *
804 * This means anything which needs support from extension modules
805 * or pure Python code in the standard library won't work.
806 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600807 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800808 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700809 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100810
Victor Stinner33c377e2017-12-05 15:12:41 +0100811 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800812 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100813 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200814
Victor Stinnerfbca9082018-08-30 00:50:45 +0200815 if (_PySys_EndInit(interp->sysdict, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800816 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100817 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800818
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200819 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800820 if (_Py_INIT_FAILED(err)) {
821 return err;
822 }
Nick Coghland6009512014-11-20 21:39:37 +1000823
824 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200825 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800826 if (_Py_INIT_FAILED(err)) {
827 return err;
828 }
Nick Coghland6009512014-11-20 21:39:37 +1000829
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800830 err = initfsencoding(interp);
831 if (_Py_INIT_FAILED(err)) {
832 return err;
833 }
Nick Coghland6009512014-11-20 21:39:37 +1000834
Victor Stinner1f151112017-11-23 10:43:14 +0100835 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800836 err = initsigs(); /* Signal handling stuff, including initintr() */
837 if (_Py_INIT_FAILED(err)) {
838 return err;
839 }
840 }
Nick Coghland6009512014-11-20 21:39:37 +1000841
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200842 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800843 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200844 }
Nick Coghland6009512014-11-20 21:39:37 +1000845
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800846 err = add_main_module(interp);
847 if (_Py_INIT_FAILED(err)) {
848 return err;
849 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800850
Victor Stinner91106cd2017-12-13 12:29:09 +0100851 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800852 if (_Py_INIT_FAILED(err)) {
853 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800854 }
Nick Coghland6009512014-11-20 21:39:37 +1000855
856 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100857 if (interp->config.warnoptions != NULL &&
858 PyList_Size(interp->config.warnoptions) > 0)
859 {
Nick Coghland6009512014-11-20 21:39:37 +1000860 PyObject *warnings_module = PyImport_ImportModule("warnings");
861 if (warnings_module == NULL) {
862 fprintf(stderr, "'import warnings' failed; traceback:\n");
863 PyErr_Print();
864 }
865 Py_XDECREF(warnings_module);
866 }
867
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600868 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700869
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200870 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800871 err = initsite(); /* Module site */
872 if (_Py_INIT_FAILED(err)) {
873 return err;
874 }
875 }
Victor Stinnercf215042018-08-29 22:56:06 +0200876
877#ifndef MS_WINDOWS
878 _emit_stderr_warning_for_legacy_locale(core_config);
879#endif
880
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800881 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000882}
883
Eric Snowc7ec9982017-05-23 23:00:52 -0700884#undef _INIT_DEBUG_PRINT
885
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800886_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200887_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700888{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700889 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800890 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200891 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800892 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200893 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800894 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200895 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100896
Victor Stinner9cfc0022017-12-20 19:36:46 +0100897 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200898 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100899 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200900 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800901 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100902 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800903 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200904 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800905 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200906 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700907}
908
909
910void
Nick Coghland6009512014-11-20 21:39:37 +1000911Py_InitializeEx(int install_sigs)
912{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200913 if (_PyRuntime.initialized) {
914 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
915 return;
916 }
917
918 _PyInitError err;
919 _PyCoreConfig config = _PyCoreConfig_INIT;
920 config.install_signal_handlers = install_sigs;
921
922 err = _Py_InitializeFromConfig(&config);
923 _PyCoreConfig_Clear(&config);
924
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800925 if (_Py_INIT_FAILED(err)) {
926 _Py_FatalInitError(err);
927 }
Nick Coghland6009512014-11-20 21:39:37 +1000928}
929
930void
931Py_Initialize(void)
932{
933 Py_InitializeEx(1);
934}
935
936
937#ifdef COUNT_ALLOCS
938extern void dump_counts(FILE*);
939#endif
940
941/* Flush stdout and stderr */
942
943static int
944file_is_closed(PyObject *fobj)
945{
946 int r;
947 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
948 if (tmp == NULL) {
949 PyErr_Clear();
950 return 0;
951 }
952 r = PyObject_IsTrue(tmp);
953 Py_DECREF(tmp);
954 if (r < 0)
955 PyErr_Clear();
956 return r > 0;
957}
958
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000959static int
Nick Coghland6009512014-11-20 21:39:37 +1000960flush_std_files(void)
961{
962 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
963 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
964 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000965 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000966
967 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700968 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000969 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000970 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000971 status = -1;
972 }
Nick Coghland6009512014-11-20 21:39:37 +1000973 else
974 Py_DECREF(tmp);
975 }
976
977 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700978 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000979 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000980 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000981 status = -1;
982 }
Nick Coghland6009512014-11-20 21:39:37 +1000983 else
984 Py_DECREF(tmp);
985 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000986
987 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000988}
989
990/* Undo the effect of Py_Initialize().
991
992 Beware: if multiple interpreter and/or thread states exist, these
993 are not wiped out; only the current thread and interpreter state
994 are deleted. But since everything else is deleted, those other
995 interpreter and thread states should no longer be used.
996
997 (XXX We should do better, e.g. wipe out all interpreters and
998 threads.)
999
1000 Locking: as above.
1001
1002*/
1003
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001004int
1005Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001006{
1007 PyInterpreterState *interp;
1008 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001009 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001010
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001011 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001012 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001013
1014 wait_for_thread_shutdown();
1015
Marcel Plch776407f2017-12-20 11:17:58 +01001016 /* Get current thread state and interpreter pointer */
1017 tstate = PyThreadState_GET();
1018 interp = tstate->interp;
1019
Nick Coghland6009512014-11-20 21:39:37 +10001020 /* The interpreter is still entirely intact at this point, and the
1021 * exit funcs may be relying on that. In particular, if some thread
1022 * or exit func is still waiting to do an import, the import machinery
1023 * expects Py_IsInitialized() to return true. So don't say the
1024 * interpreter is uninitialized until after the exit funcs have run.
1025 * Note that Threading.py uses an exit func to do a join on all the
1026 * threads created thru it, so this also protects pending imports in
1027 * the threads created via Threading.
1028 */
Nick Coghland6009512014-11-20 21:39:37 +10001029
Marcel Plch776407f2017-12-20 11:17:58 +01001030 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001031
Victor Stinnerda273412017-12-15 01:46:02 +01001032 /* Copy the core config, PyInterpreterState_Delete() free
1033 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001034#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001035 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001036#endif
1037#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001038 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001039#endif
1040#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001041 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001042#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001043
Nick Coghland6009512014-11-20 21:39:37 +10001044 /* Remaining threads (e.g. daemon threads) will automatically exit
1045 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001046 _PyRuntime.finalizing = tstate;
1047 _PyRuntime.initialized = 0;
1048 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001049
Victor Stinnere0deff32015-03-24 13:46:18 +01001050 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001051 if (flush_std_files() < 0) {
1052 status = -1;
1053 }
Nick Coghland6009512014-11-20 21:39:37 +10001054
1055 /* Disable signal handling */
1056 PyOS_FiniInterrupts();
1057
1058 /* Collect garbage. This may call finalizers; it's nice to call these
1059 * before all modules are destroyed.
1060 * XXX If a __del__ or weakref callback is triggered here, and tries to
1061 * XXX import a module, bad things can happen, because Python no
1062 * XXX longer believes it's initialized.
1063 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1064 * XXX is easy to provoke that way. I've also seen, e.g.,
1065 * XXX Exception exceptions.ImportError: 'No module named sha'
1066 * XXX in <function callback at 0x008F5718> ignored
1067 * XXX but I'm unclear on exactly how that one happens. In any case,
1068 * XXX I haven't seen a real-life report of either of these.
1069 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001070 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001071#ifdef COUNT_ALLOCS
1072 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1073 each collection might release some types from the type
1074 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001075 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001076 /* nothing */;
1077#endif
Eric Snowdae02762017-09-14 00:35:58 -07001078
Nick Coghland6009512014-11-20 21:39:37 +10001079 /* Destroy all modules */
1080 PyImport_Cleanup();
1081
Victor Stinnere0deff32015-03-24 13:46:18 +01001082 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001083 if (flush_std_files() < 0) {
1084 status = -1;
1085 }
Nick Coghland6009512014-11-20 21:39:37 +10001086
1087 /* Collect final garbage. This disposes of cycles created by
1088 * class definitions, for example.
1089 * XXX This is disabled because it caused too many problems. If
1090 * XXX a __del__ or weakref callback triggers here, Python code has
1091 * XXX a hard time running, because even the sys module has been
1092 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1093 * XXX One symptom is a sequence of information-free messages
1094 * XXX coming from threads (if a __del__ or callback is invoked,
1095 * XXX other threads can execute too, and any exception they encounter
1096 * XXX triggers a comedy of errors as subsystem after subsystem
1097 * XXX fails to find what it *expects* to find in sys to help report
1098 * XXX the exception and consequent unexpected failures). I've also
1099 * XXX seen segfaults then, after adding print statements to the
1100 * XXX Python code getting called.
1101 */
1102#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001103 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001104#endif
1105
1106 /* Disable tracemalloc after all Python objects have been destroyed,
1107 so it is possible to use tracemalloc in objects destructor. */
1108 _PyTraceMalloc_Fini();
1109
1110 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1111 _PyImport_Fini();
1112
1113 /* Cleanup typeobject.c's internal caches. */
1114 _PyType_Fini();
1115
1116 /* unload faulthandler module */
1117 _PyFaulthandler_Fini();
1118
1119 /* Debugging stuff */
1120#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001121 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001122#endif
1123 /* dump hash stats */
1124 _PyHash_Fini();
1125
Eric Snowdae02762017-09-14 00:35:58 -07001126#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001127 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001128 _PyDebug_PrintTotalRefs();
1129 }
Eric Snowdae02762017-09-14 00:35:58 -07001130#endif
Nick Coghland6009512014-11-20 21:39:37 +10001131
1132#ifdef Py_TRACE_REFS
1133 /* Display all objects still alive -- this can invoke arbitrary
1134 * __repr__ overrides, so requires a mostly-intact interpreter.
1135 * Alas, a lot of stuff may still be alive now that will be cleaned
1136 * up later.
1137 */
Victor Stinnerda273412017-12-15 01:46:02 +01001138 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001139 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001140 }
Nick Coghland6009512014-11-20 21:39:37 +10001141#endif /* Py_TRACE_REFS */
1142
1143 /* Clear interpreter state and all thread states. */
1144 PyInterpreterState_Clear(interp);
1145
1146 /* Now we decref the exception classes. After this point nothing
1147 can raise an exception. That's okay, because each Fini() method
1148 below has been checked to make sure no exceptions are ever
1149 raised.
1150 */
1151
1152 _PyExc_Fini();
1153
1154 /* Sundry finalizers */
1155 PyMethod_Fini();
1156 PyFrame_Fini();
1157 PyCFunction_Fini();
1158 PyTuple_Fini();
1159 PyList_Fini();
1160 PySet_Fini();
1161 PyBytes_Fini();
1162 PyByteArray_Fini();
1163 PyLong_Fini();
1164 PyFloat_Fini();
1165 PyDict_Fini();
1166 PySlice_Fini();
1167 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001168 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001169 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001170 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001171 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001172
1173 /* Cleanup Unicode implementation */
1174 _PyUnicode_Fini();
1175
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001176 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001177
1178 /* XXX Still allocated:
1179 - various static ad-hoc pointers to interned strings
1180 - int and float free list blocks
1181 - whatever various modules and libraries allocate
1182 */
1183
1184 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1185
1186 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001187 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001188
1189 /* Delete current thread. After this, many C API calls become crashy. */
1190 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001191
Nick Coghland6009512014-11-20 21:39:37 +10001192 PyInterpreterState_Delete(interp);
1193
1194#ifdef Py_TRACE_REFS
1195 /* Display addresses (& refcnts) of all objects still alive.
1196 * An address can be used to find the repr of the object, printed
1197 * above by _Py_PrintReferences.
1198 */
Victor Stinnerda273412017-12-15 01:46:02 +01001199 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001200 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001201 }
Nick Coghland6009512014-11-20 21:39:37 +10001202#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001203#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001204 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001205 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001206 }
Nick Coghland6009512014-11-20 21:39:37 +10001207#endif
1208
1209 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001210
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001211 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001212 return status;
1213}
1214
1215void
1216Py_Finalize(void)
1217{
1218 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001219}
1220
1221/* Create and initialize a new interpreter and thread, and return the
1222 new thread. This requires that Py_Initialize() has been called
1223 first.
1224
1225 Unsuccessful initialization yields a NULL pointer. Note that *no*
1226 exception information is available even in this case -- the
1227 exception information is held in the thread, and there is no
1228 thread.
1229
1230 Locking: as above.
1231
1232*/
1233
Victor Stinnera7368ac2017-11-15 18:11:45 -08001234static _PyInitError
1235new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001236{
1237 PyInterpreterState *interp;
1238 PyThreadState *tstate, *save_tstate;
1239 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001240 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001241
Victor Stinnera7368ac2017-11-15 18:11:45 -08001242 if (!_PyRuntime.initialized) {
1243 return _Py_INIT_ERR("Py_Initialize must be called first");
1244 }
Nick Coghland6009512014-11-20 21:39:37 +10001245
Victor Stinner8a1be612016-03-14 22:07:55 +01001246 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1247 interpreters: disable PyGILState_Check(). */
1248 _PyGILState_check_enabled = 0;
1249
Nick Coghland6009512014-11-20 21:39:37 +10001250 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001251 if (interp == NULL) {
1252 *tstate_p = NULL;
1253 return _Py_INIT_OK();
1254 }
Nick Coghland6009512014-11-20 21:39:37 +10001255
1256 tstate = PyThreadState_New(interp);
1257 if (tstate == NULL) {
1258 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001259 *tstate_p = NULL;
1260 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001261 }
1262
1263 save_tstate = PyThreadState_Swap(tstate);
1264
Eric Snow1abcf672017-05-23 21:46:51 -07001265 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001266 _PyCoreConfig *core_config;
1267 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001268 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001269 core_config = &save_tstate->interp->core_config;
1270 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001271 } else {
1272 /* No current thread state, copy from the main interpreter */
1273 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001274 core_config = &main_interp->core_config;
1275 config = &main_interp->config;
1276 }
1277
1278 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1279 return _Py_INIT_ERR("failed to copy core config");
1280 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001281 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001282 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1283 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001284 }
1285
Nick Coghland6009512014-11-20 21:39:37 +10001286 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001287 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001288 if (modules == NULL) {
1289 return _Py_INIT_ERR("can't make modules dictionary");
1290 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001291 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001292
Eric Snowd393c1b2017-09-14 12:18:12 -06001293 sysmod = _PyImport_FindBuiltin("sys", modules);
1294 if (sysmod != NULL) {
1295 interp->sysdict = PyModule_GetDict(sysmod);
1296 if (interp->sysdict == NULL)
1297 goto handle_error;
1298 Py_INCREF(interp->sysdict);
1299 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001300 _PySys_EndInit(interp->sysdict, interp);
Eric Snowd393c1b2017-09-14 12:18:12 -06001301 }
1302
1303 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001304 if (bimod != NULL) {
1305 interp->builtins = PyModule_GetDict(bimod);
1306 if (interp->builtins == NULL)
1307 goto handle_error;
1308 Py_INCREF(interp->builtins);
1309 }
1310
1311 /* initialize builtin exceptions */
1312 _PyExc_Init(bimod);
1313
Nick Coghland6009512014-11-20 21:39:37 +10001314 if (bimod != NULL && sysmod != NULL) {
1315 PyObject *pstderr;
1316
Nick Coghland6009512014-11-20 21:39:37 +10001317 /* Set up a preliminary stderr printer until we have enough
1318 infrastructure for the io module in place. */
1319 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001320 if (pstderr == NULL) {
1321 return _Py_INIT_ERR("can't set preliminary stderr");
1322 }
Nick Coghland6009512014-11-20 21:39:37 +10001323 _PySys_SetObjectId(&PyId_stderr, pstderr);
1324 PySys_SetObject("__stderr__", pstderr);
1325 Py_DECREF(pstderr);
1326
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001327 err = _PyImportHooks_Init();
1328 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001329 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001330 }
Nick Coghland6009512014-11-20 21:39:37 +10001331
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001332 err = initimport(interp, sysmod);
1333 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001334 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001335 }
Nick Coghland6009512014-11-20 21:39:37 +10001336
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001337 err = initexternalimport(interp);
1338 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001339 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001340 }
Nick Coghland6009512014-11-20 21:39:37 +10001341
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001342 err = initfsencoding(interp);
1343 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001344 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001345 }
1346
Victor Stinner91106cd2017-12-13 12:29:09 +01001347 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001348 if (_Py_INIT_FAILED(err)) {
1349 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001350 }
1351
1352 err = add_main_module(interp);
1353 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001354 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001355 }
1356
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001357 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001358 err = initsite();
1359 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001360 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001361 }
1362 }
Nick Coghland6009512014-11-20 21:39:37 +10001363 }
1364
Victor Stinnera7368ac2017-11-15 18:11:45 -08001365 if (PyErr_Occurred()) {
1366 goto handle_error;
1367 }
Nick Coghland6009512014-11-20 21:39:37 +10001368
Victor Stinnera7368ac2017-11-15 18:11:45 -08001369 *tstate_p = tstate;
1370 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001371
Nick Coghland6009512014-11-20 21:39:37 +10001372handle_error:
1373 /* Oops, it didn't work. Undo it all. */
1374
1375 PyErr_PrintEx(0);
1376 PyThreadState_Clear(tstate);
1377 PyThreadState_Swap(save_tstate);
1378 PyThreadState_Delete(tstate);
1379 PyInterpreterState_Delete(interp);
1380
Victor Stinnera7368ac2017-11-15 18:11:45 -08001381 *tstate_p = NULL;
1382 return _Py_INIT_OK();
1383}
1384
1385PyThreadState *
1386Py_NewInterpreter(void)
1387{
1388 PyThreadState *tstate;
1389 _PyInitError err = new_interpreter(&tstate);
1390 if (_Py_INIT_FAILED(err)) {
1391 _Py_FatalInitError(err);
1392 }
1393 return tstate;
1394
Nick Coghland6009512014-11-20 21:39:37 +10001395}
1396
1397/* Delete an interpreter and its last thread. This requires that the
1398 given thread state is current, that the thread has no remaining
1399 frames, and that it is its interpreter's only remaining thread.
1400 It is a fatal error to violate these constraints.
1401
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001402 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001403 everything, regardless.)
1404
1405 Locking: as above.
1406
1407*/
1408
1409void
1410Py_EndInterpreter(PyThreadState *tstate)
1411{
1412 PyInterpreterState *interp = tstate->interp;
1413
1414 if (tstate != PyThreadState_GET())
1415 Py_FatalError("Py_EndInterpreter: thread is not current");
1416 if (tstate->frame != NULL)
1417 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1418
1419 wait_for_thread_shutdown();
1420
Marcel Plch776407f2017-12-20 11:17:58 +01001421 call_py_exitfuncs(interp);
1422
Nick Coghland6009512014-11-20 21:39:37 +10001423 if (tstate != interp->tstate_head || tstate->next != NULL)
1424 Py_FatalError("Py_EndInterpreter: not the last thread");
1425
1426 PyImport_Cleanup();
1427 PyInterpreterState_Clear(interp);
1428 PyThreadState_Swap(NULL);
1429 PyInterpreterState_Delete(interp);
1430}
1431
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001432/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001433
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001434static _PyInitError
1435add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001436{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001437 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001438 m = PyImport_AddModule("__main__");
1439 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001440 return _Py_INIT_ERR("can't create __main__ module");
1441
Nick Coghland6009512014-11-20 21:39:37 +10001442 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001443 ann_dict = PyDict_New();
1444 if ((ann_dict == NULL) ||
1445 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001446 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001447 }
1448 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001449
Nick Coghland6009512014-11-20 21:39:37 +10001450 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1451 PyObject *bimod = PyImport_ImportModule("builtins");
1452 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001453 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001454 }
1455 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001456 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001457 }
1458 Py_DECREF(bimod);
1459 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001460
Nick Coghland6009512014-11-20 21:39:37 +10001461 /* Main is a little special - imp.is_builtin("__main__") will return
1462 * False, but BuiltinImporter is still the most appropriate initial
1463 * setting for its __loader__ attribute. A more suitable value will
1464 * be set if __main__ gets further initialized later in the startup
1465 * process.
1466 */
1467 loader = PyDict_GetItemString(d, "__loader__");
1468 if (loader == NULL || loader == Py_None) {
1469 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1470 "BuiltinImporter");
1471 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001472 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001473 }
1474 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001475 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001476 }
1477 Py_DECREF(loader);
1478 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001479 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001480}
1481
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001482static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001483initfsencoding(PyInterpreterState *interp)
1484{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001485 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001486
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001487 char *encoding = get_codec_name(config->filesystem_encoding);
1488 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001489 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001490 memory, import a module of the standard library failed, etc. */
1491 return _Py_INIT_ERR("failed to get the Python codec "
1492 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001493 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001494
1495 /* Update the filesystem encoding to the normalized Python codec name.
1496 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1497 (Python codec name). */
1498 PyMem_RawFree(config->filesystem_encoding);
1499 config->filesystem_encoding = encoding;
1500
1501 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1502 global configuration variables. */
1503 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1504 config->filesystem_errors) < 0) {
1505 return _Py_INIT_NO_MEMORY();
1506 }
1507
1508 /* PyUnicode can now use the Python codec rather than C implementation
1509 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001510 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001511 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001512}
1513
1514/* Import the site module (not into __main__ though) */
1515
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001516static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001517initsite(void)
1518{
1519 PyObject *m;
1520 m = PyImport_ImportModule("site");
1521 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001522 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001523 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524 Py_DECREF(m);
1525 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001526}
1527
Victor Stinner874dbe82015-09-04 17:29:57 +02001528/* Check if a file descriptor is valid or not.
1529 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1530static int
1531is_valid_fd(int fd)
1532{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001533#ifdef __APPLE__
1534 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1535 and the other side of the pipe is closed, dup(1) succeed, whereas
1536 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1537 such error. */
1538 struct stat st;
1539 return (fstat(fd, &st) == 0);
1540#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001541 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001542 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001543 return 0;
1544 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001545 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1546 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1547 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001548 fd2 = dup(fd);
1549 if (fd2 >= 0)
1550 close(fd2);
1551 _Py_END_SUPPRESS_IPH
1552 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001553#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001554}
1555
1556/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001557static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001558create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001559 int fd, int write_mode, const char* name,
1560 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001561{
1562 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1563 const char* mode;
1564 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001565 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001566 int buffering, isatty;
1567 _Py_IDENTIFIER(open);
1568 _Py_IDENTIFIER(isatty);
1569 _Py_IDENTIFIER(TextIOWrapper);
1570 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001571 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001572
Victor Stinner874dbe82015-09-04 17:29:57 +02001573 if (!is_valid_fd(fd))
1574 Py_RETURN_NONE;
1575
Nick Coghland6009512014-11-20 21:39:37 +10001576 /* stdin is always opened in buffered mode, first because it shouldn't
1577 make a difference in common use cases, second because TextIOWrapper
1578 depends on the presence of a read1() method which only exists on
1579 buffered streams.
1580 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001581 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001582 buffering = 0;
1583 else
1584 buffering = -1;
1585 if (write_mode)
1586 mode = "wb";
1587 else
1588 mode = "rb";
1589 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1590 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001591 Py_None, Py_None, /* encoding, errors */
1592 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001593 if (buf == NULL)
1594 goto error;
1595
1596 if (buffering) {
1597 _Py_IDENTIFIER(raw);
1598 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1599 if (raw == NULL)
1600 goto error;
1601 }
1602 else {
1603 raw = buf;
1604 Py_INCREF(raw);
1605 }
1606
Steve Dower39294992016-08-30 21:22:36 -07001607#ifdef MS_WINDOWS
1608 /* Windows console IO is always UTF-8 encoded */
1609 if (PyWindowsConsoleIO_Check(raw))
1610 encoding = "utf-8";
1611#endif
1612
Nick Coghland6009512014-11-20 21:39:37 +10001613 text = PyUnicode_FromString(name);
1614 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1615 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001616 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001617 if (res == NULL)
1618 goto error;
1619 isatty = PyObject_IsTrue(res);
1620 Py_DECREF(res);
1621 if (isatty == -1)
1622 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001623 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001624 write_through = Py_True;
1625 else
1626 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001627 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001628 line_buffering = Py_True;
1629 else
1630 line_buffering = Py_False;
1631
1632 Py_CLEAR(raw);
1633 Py_CLEAR(text);
1634
1635#ifdef MS_WINDOWS
1636 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1637 newlines to "\n".
1638 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1639 newline = NULL;
1640#else
1641 /* sys.stdin: split lines at "\n".
1642 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1643 newline = "\n";
1644#endif
1645
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001646 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001647 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001648 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001649 Py_CLEAR(buf);
1650 if (stream == NULL)
1651 goto error;
1652
1653 if (write_mode)
1654 mode = "w";
1655 else
1656 mode = "r";
1657 text = PyUnicode_FromString(mode);
1658 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1659 goto error;
1660 Py_CLEAR(text);
1661 return stream;
1662
1663error:
1664 Py_XDECREF(buf);
1665 Py_XDECREF(stream);
1666 Py_XDECREF(text);
1667 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001668
Victor Stinner874dbe82015-09-04 17:29:57 +02001669 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1670 /* Issue #24891: the file descriptor was closed after the first
1671 is_valid_fd() check was called. Ignore the OSError and set the
1672 stream to None. */
1673 PyErr_Clear();
1674 Py_RETURN_NONE;
1675 }
1676 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001677}
1678
1679/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001680static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001681init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001682{
1683 PyObject *iomod = NULL, *wrapper;
1684 PyObject *bimod = NULL;
1685 PyObject *m;
1686 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001687 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001688 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001689 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001690 _PyCoreConfig *config = &interp->core_config;
1691
1692 char *codec_name = get_codec_name(config->stdio_encoding);
1693 if (codec_name == NULL) {
1694 return _Py_INIT_ERR("failed to get the Python codec name "
1695 "of the stdio encoding");
1696 }
1697 PyMem_RawFree(config->stdio_encoding);
1698 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001699
1700 /* Hack to avoid a nasty recursion issue when Python is invoked
1701 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1702 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1703 goto error;
1704 }
1705 Py_DECREF(m);
1706
1707 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1708 goto error;
1709 }
1710 Py_DECREF(m);
1711
1712 if (!(bimod = PyImport_ImportModule("builtins"))) {
1713 goto error;
1714 }
1715
1716 if (!(iomod = PyImport_ImportModule("io"))) {
1717 goto error;
1718 }
1719 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1720 goto error;
1721 }
1722
1723 /* Set builtins.open */
1724 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1725 Py_DECREF(wrapper);
1726 goto error;
1727 }
1728 Py_DECREF(wrapper);
1729
Nick Coghland6009512014-11-20 21:39:37 +10001730 /* Set sys.stdin */
1731 fd = fileno(stdin);
1732 /* Under some conditions stdin, stdout and stderr may not be connected
1733 * and fileno() may point to an invalid file descriptor. For example
1734 * GUI apps don't have valid standard streams by default.
1735 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001736 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001737 config->stdio_encoding,
1738 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001739 if (std == NULL)
1740 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001741 PySys_SetObject("__stdin__", std);
1742 _PySys_SetObjectId(&PyId_stdin, std);
1743 Py_DECREF(std);
1744
1745 /* Set sys.stdout */
1746 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001747 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001748 config->stdio_encoding,
1749 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001750 if (std == NULL)
1751 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001752 PySys_SetObject("__stdout__", std);
1753 _PySys_SetObjectId(&PyId_stdout, std);
1754 Py_DECREF(std);
1755
1756#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1757 /* Set sys.stderr, replaces the preliminary stderr */
1758 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001759 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001760 config->stdio_encoding,
1761 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001762 if (std == NULL)
1763 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001764
1765 /* Same as hack above, pre-import stderr's codec to avoid recursion
1766 when import.c tries to write to stderr in verbose mode. */
1767 encoding_attr = PyObject_GetAttrString(std, "encoding");
1768 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001769 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001770 if (std_encoding != NULL) {
1771 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1772 Py_XDECREF(codec_info);
1773 }
1774 Py_DECREF(encoding_attr);
1775 }
1776 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1777
1778 if (PySys_SetObject("__stderr__", std) < 0) {
1779 Py_DECREF(std);
1780 goto error;
1781 }
1782 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1783 Py_DECREF(std);
1784 goto error;
1785 }
1786 Py_DECREF(std);
1787#endif
1788
Victor Stinnera7368ac2017-11-15 18:11:45 -08001789 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001790
Victor Stinnera7368ac2017-11-15 18:11:45 -08001791error:
1792 res = _Py_INIT_ERR("can't initialize sys standard streams");
1793
1794done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001795 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001796
Nick Coghland6009512014-11-20 21:39:37 +10001797 Py_XDECREF(bimod);
1798 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001799 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001800}
1801
1802
Victor Stinner10dc4842015-03-24 12:01:30 +01001803static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001804_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001805{
Victor Stinner10dc4842015-03-24 12:01:30 +01001806 fputc('\n', stderr);
1807 fflush(stderr);
1808
1809 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001810 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001811}
Victor Stinner791da1c2016-03-14 16:53:12 +01001812
1813/* Print the current exception (if an exception is set) with its traceback,
1814 or display the current Python stack.
1815
1816 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1817 called on catastrophic cases.
1818
1819 Return 1 if the traceback was displayed, 0 otherwise. */
1820
1821static int
1822_Py_FatalError_PrintExc(int fd)
1823{
1824 PyObject *ferr, *res;
1825 PyObject *exception, *v, *tb;
1826 int has_tb;
1827
1828 if (PyThreadState_GET() == NULL) {
1829 /* The GIL is released: trying to acquire it is likely to deadlock,
1830 just give up. */
1831 return 0;
1832 }
1833
1834 PyErr_Fetch(&exception, &v, &tb);
1835 if (exception == NULL) {
1836 /* No current exception */
1837 return 0;
1838 }
1839
1840 ferr = _PySys_GetObjectId(&PyId_stderr);
1841 if (ferr == NULL || ferr == Py_None) {
1842 /* sys.stderr is not set yet or set to None,
1843 no need to try to display the exception */
1844 return 0;
1845 }
1846
1847 PyErr_NormalizeException(&exception, &v, &tb);
1848 if (tb == NULL) {
1849 tb = Py_None;
1850 Py_INCREF(tb);
1851 }
1852 PyException_SetTraceback(v, tb);
1853 if (exception == NULL) {
1854 /* PyErr_NormalizeException() failed */
1855 return 0;
1856 }
1857
1858 has_tb = (tb != Py_None);
1859 PyErr_Display(exception, v, tb);
1860 Py_XDECREF(exception);
1861 Py_XDECREF(v);
1862 Py_XDECREF(tb);
1863
1864 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001865 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001866 if (res == NULL)
1867 PyErr_Clear();
1868 else
1869 Py_DECREF(res);
1870
1871 return has_tb;
1872}
1873
Nick Coghland6009512014-11-20 21:39:37 +10001874/* Print fatal error message and abort */
1875
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001876#ifdef MS_WINDOWS
1877static void
1878fatal_output_debug(const char *msg)
1879{
1880 /* buffer of 256 bytes allocated on the stack */
1881 WCHAR buffer[256 / sizeof(WCHAR)];
1882 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1883 size_t msglen;
1884
1885 OutputDebugStringW(L"Fatal Python error: ");
1886
1887 msglen = strlen(msg);
1888 while (msglen) {
1889 size_t i;
1890
1891 if (buflen > msglen) {
1892 buflen = msglen;
1893 }
1894
1895 /* Convert the message to wchar_t. This uses a simple one-to-one
1896 conversion, assuming that the this error message actually uses
1897 ASCII only. If this ceases to be true, we will have to convert. */
1898 for (i=0; i < buflen; ++i) {
1899 buffer[i] = msg[i];
1900 }
1901 buffer[i] = L'\0';
1902 OutputDebugStringW(buffer);
1903
1904 msg += buflen;
1905 msglen -= buflen;
1906 }
1907 OutputDebugStringW(L"\n");
1908}
1909#endif
1910
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001911static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001912fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001913{
1914 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001915 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001916
1917 if (reentrant) {
1918 /* Py_FatalError() caused a second fatal error.
1919 Example: flush_std_files() raises a recursion error. */
1920 goto exit;
1921 }
1922 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001923
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001924 fprintf(stderr, "Fatal Python error: ");
1925 if (prefix) {
1926 fputs(prefix, stderr);
1927 fputs(": ", stderr);
1928 }
1929 if (msg) {
1930 fputs(msg, stderr);
1931 }
1932 else {
1933 fprintf(stderr, "<message not set>");
1934 }
1935 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001936 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001937
Victor Stinnere0deff32015-03-24 13:46:18 +01001938 /* Print the exception (if an exception is set) with its traceback,
1939 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001940 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001941 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001942 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001943
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001944 /* The main purpose of faulthandler is to display the traceback.
1945 This function already did its best to display a traceback.
1946 Disable faulthandler to prevent writing a second traceback
1947 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001948 _PyFaulthandler_Fini();
1949
Victor Stinner791da1c2016-03-14 16:53:12 +01001950 /* Check if the current Python thread hold the GIL */
1951 if (PyThreadState_GET() != NULL) {
1952 /* Flush sys.stdout and sys.stderr */
1953 flush_std_files();
1954 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001955
Nick Coghland6009512014-11-20 21:39:37 +10001956#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001957 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001958#endif /* MS_WINDOWS */
1959
1960exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001961 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01001962#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001963 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10001964#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001965 abort();
1966 }
1967 else {
1968 exit(status);
1969 }
1970}
1971
Victor Stinner19760862017-12-20 01:41:59 +01001972void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001973Py_FatalError(const char *msg)
1974{
1975 fatal_error(NULL, msg, -1);
1976}
1977
Victor Stinner19760862017-12-20 01:41:59 +01001978void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001979_Py_FatalInitError(_PyInitError err)
1980{
1981 /* On "user" error: exit with status 1.
1982 For all other errors, call abort(). */
1983 int status = err.user_err ? 1 : -1;
1984 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10001985}
1986
1987/* Clean up and exit */
1988
Victor Stinnerd7292b52016-06-17 12:29:00 +02001989# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001990
Nick Coghland6009512014-11-20 21:39:37 +10001991/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01001992void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10001993{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001994 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01001995
Antoine Pitroufc5db952017-12-13 02:29:07 +01001996 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01001997 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
1998
1999 is->pyexitfunc = func;
2000 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002001}
2002
2003static void
Marcel Plch776407f2017-12-20 11:17:58 +01002004call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002005{
Marcel Plch776407f2017-12-20 11:17:58 +01002006 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002007 return;
2008
Marcel Plch776407f2017-12-20 11:17:58 +01002009 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002010 PyErr_Clear();
2011}
2012
2013/* Wait until threading._shutdown completes, provided
2014 the threading module was imported in the first place.
2015 The shutdown routine will wait until all non-daemon
2016 "threading" threads have completed. */
2017static void
2018wait_for_thread_shutdown(void)
2019{
Nick Coghland6009512014-11-20 21:39:37 +10002020 _Py_IDENTIFIER(_shutdown);
2021 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002022 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002023 if (threading == NULL) {
2024 /* threading not imported */
2025 PyErr_Clear();
2026 return;
2027 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002028 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002029 if (result == NULL) {
2030 PyErr_WriteUnraisable(threading);
2031 }
2032 else {
2033 Py_DECREF(result);
2034 }
2035 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002036}
2037
2038#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002039int Py_AtExit(void (*func)(void))
2040{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002041 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002042 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002043 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002044 return 0;
2045}
2046
2047static void
2048call_ll_exitfuncs(void)
2049{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002050 while (_PyRuntime.nexitfuncs > 0)
2051 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002052
2053 fflush(stdout);
2054 fflush(stderr);
2055}
2056
Victor Stinnercfc88312018-08-01 16:41:25 +02002057void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002058Py_Exit(int sts)
2059{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002060 if (Py_FinalizeEx() < 0) {
2061 sts = 120;
2062 }
Nick Coghland6009512014-11-20 21:39:37 +10002063
2064 exit(sts);
2065}
2066
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002067static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002068initsigs(void)
2069{
2070#ifdef SIGPIPE
2071 PyOS_setsig(SIGPIPE, SIG_IGN);
2072#endif
2073#ifdef SIGXFZ
2074 PyOS_setsig(SIGXFZ, SIG_IGN);
2075#endif
2076#ifdef SIGXFSZ
2077 PyOS_setsig(SIGXFSZ, SIG_IGN);
2078#endif
2079 PyOS_InitInterrupts(); /* May imply initsignal() */
2080 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002081 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002082 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002083 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002084}
2085
2086
2087/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2088 *
2089 * All of the code in this function must only use async-signal-safe functions,
2090 * listed at `man 7 signal` or
2091 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2092 */
2093void
2094_Py_RestoreSignals(void)
2095{
2096#ifdef SIGPIPE
2097 PyOS_setsig(SIGPIPE, SIG_DFL);
2098#endif
2099#ifdef SIGXFZ
2100 PyOS_setsig(SIGXFZ, SIG_DFL);
2101#endif
2102#ifdef SIGXFSZ
2103 PyOS_setsig(SIGXFSZ, SIG_DFL);
2104#endif
2105}
2106
2107
2108/*
2109 * The file descriptor fd is considered ``interactive'' if either
2110 * a) isatty(fd) is TRUE, or
2111 * b) the -i flag was given, and the filename associated with
2112 * the descriptor is NULL or "<stdin>" or "???".
2113 */
2114int
2115Py_FdIsInteractive(FILE *fp, const char *filename)
2116{
2117 if (isatty((int)fileno(fp)))
2118 return 1;
2119 if (!Py_InteractiveFlag)
2120 return 0;
2121 return (filename == NULL) ||
2122 (strcmp(filename, "<stdin>") == 0) ||
2123 (strcmp(filename, "???") == 0);
2124}
2125
2126
Nick Coghland6009512014-11-20 21:39:37 +10002127/* Wrappers around sigaction() or signal(). */
2128
2129PyOS_sighandler_t
2130PyOS_getsig(int sig)
2131{
2132#ifdef HAVE_SIGACTION
2133 struct sigaction context;
2134 if (sigaction(sig, NULL, &context) == -1)
2135 return SIG_ERR;
2136 return context.sa_handler;
2137#else
2138 PyOS_sighandler_t handler;
2139/* Special signal handling for the secure CRT in Visual Studio 2005 */
2140#if defined(_MSC_VER) && _MSC_VER >= 1400
2141 switch (sig) {
2142 /* Only these signals are valid */
2143 case SIGINT:
2144 case SIGILL:
2145 case SIGFPE:
2146 case SIGSEGV:
2147 case SIGTERM:
2148 case SIGBREAK:
2149 case SIGABRT:
2150 break;
2151 /* Don't call signal() with other values or it will assert */
2152 default:
2153 return SIG_ERR;
2154 }
2155#endif /* _MSC_VER && _MSC_VER >= 1400 */
2156 handler = signal(sig, SIG_IGN);
2157 if (handler != SIG_ERR)
2158 signal(sig, handler);
2159 return handler;
2160#endif
2161}
2162
2163/*
2164 * All of the code in this function must only use async-signal-safe functions,
2165 * listed at `man 7 signal` or
2166 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2167 */
2168PyOS_sighandler_t
2169PyOS_setsig(int sig, PyOS_sighandler_t handler)
2170{
2171#ifdef HAVE_SIGACTION
2172 /* Some code in Modules/signalmodule.c depends on sigaction() being
2173 * used here if HAVE_SIGACTION is defined. Fix that if this code
2174 * changes to invalidate that assumption.
2175 */
2176 struct sigaction context, ocontext;
2177 context.sa_handler = handler;
2178 sigemptyset(&context.sa_mask);
2179 context.sa_flags = 0;
2180 if (sigaction(sig, &context, &ocontext) == -1)
2181 return SIG_ERR;
2182 return ocontext.sa_handler;
2183#else
2184 PyOS_sighandler_t oldhandler;
2185 oldhandler = signal(sig, handler);
2186#ifdef HAVE_SIGINTERRUPT
2187 siginterrupt(sig, 1);
2188#endif
2189 return oldhandler;
2190#endif
2191}
2192
2193#ifdef __cplusplus
2194}
2195#endif