blob: 58e16473100e3a65e4225922cb3c782916517c21 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01006#include "pycore_context.h"
7#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +01008#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pylifecycle.h"
10#include "pycore_pymem.h"
11#include "pycore_pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100012#include "grammar.h"
13#include "node.h"
14#include "token.h"
15#include "parsetok.h"
16#include "errcode.h"
17#include "code.h"
18#include "symtable.h"
19#include "ast.h"
20#include "marshal.h"
21#include "osdefs.h"
22#include <locale.h>
23
24#ifdef HAVE_SIGNAL_H
25#include <signal.h>
26#endif
27
28#ifdef MS_WINDOWS
29#include "malloc.h" /* for alloca */
30#endif
31
32#ifdef HAVE_LANGINFO_H
33#include <langinfo.h>
34#endif
35
36#ifdef MS_WINDOWS
37#undef BYTE
38#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070039
40extern PyTypeObject PyWindowsConsoleIO_Type;
41#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100042#endif
43
44_Py_IDENTIFIER(flush);
45_Py_IDENTIFIER(name);
46_Py_IDENTIFIER(stdin);
47_Py_IDENTIFIER(stdout);
48_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060049_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100050
51#ifdef __cplusplus
52extern "C" {
53#endif
54
Nick Coghland6009512014-11-20 21:39:37 +100055extern grammar _PyParser_Grammar; /* From graminit.c */
56
57/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080058static _PyInitError add_main_module(PyInterpreterState *interp);
59static _PyInitError initfsencoding(PyInterpreterState *interp);
60static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010061static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080062static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010063static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100064static void wait_for_thread_shutdown(void);
65static void call_ll_exitfuncs(void);
Nick Coghland6009512014-11-20 21:39:37 +100066
Victor Stinnerf7e5b562017-11-15 15:48:08 -080067_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060068
Victor Stinnerf7e5b562017-11-15 15:48:08 -080069_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060070_PyRuntime_Initialize(void)
71{
72 /* XXX We only initialize once in the process, which aligns with
73 the static initialization of the former globals now found in
74 _PyRuntime. However, _PyRuntime *should* be initialized with
75 every Py_Initialize() call, but doing so breaks the runtime.
76 This is because the runtime state is not properly finalized
77 currently. */
78 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079 if (initialized) {
80 return _Py_INIT_OK();
81 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080083
84 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060085}
86
87void
88_PyRuntime_Finalize(void)
89{
90 _PyRuntimeState_Fini(&_PyRuntime);
91}
92
93int
94_Py_IsFinalizing(void)
95{
96 return _PyRuntime.finalizing != NULL;
97}
98
Nick Coghland6009512014-11-20 21:39:37 +100099/* Hack to force loading of object files */
100int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
101 PyOS_mystrnicmp; /* Python/pystrcmp.o */
102
103/* PyModule_GetWarningsModule is no longer necessary as of 2.6
104since _warnings is builtin. This API should not be used. */
105PyObject *
106PyModule_GetWarningsModule(void)
107{
108 return PyImport_ImportModule("warnings");
109}
110
Eric Snowc7ec9982017-05-23 23:00:52 -0700111
Eric Snow1abcf672017-05-23 21:46:51 -0700112/* APIs to access the initialization flags
113 *
114 * Can be called prior to Py_Initialize.
115 */
Nick Coghland6009512014-11-20 21:39:37 +1000116
Eric Snow1abcf672017-05-23 21:46:51 -0700117int
118_Py_IsCoreInitialized(void)
119{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600120 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700121}
Nick Coghland6009512014-11-20 21:39:37 +1000122
123int
124Py_IsInitialized(void)
125{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600126 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000127}
128
Nick Coghlan6ea41862017-06-11 13:16:15 +1000129
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000130/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
131 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000132 initializations fail, a fatal error is issued and the function does
133 not return. On return, the first thread and interpreter state have
134 been created.
135
136 Locking: you must hold the interpreter lock while calling this.
137 (If the lock has not yet been initialized, that's equivalent to
138 having the lock, but you cannot use multiple threads.)
139
140*/
141
Nick Coghland6009512014-11-20 21:39:37 +1000142static char*
143get_codec_name(const char *encoding)
144{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200145 const char *name_utf8;
146 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000147 PyObject *codec, *name = NULL;
148
149 codec = _PyCodec_Lookup(encoding);
150 if (!codec)
151 goto error;
152
153 name = _PyObject_GetAttrId(codec, &PyId_name);
154 Py_CLEAR(codec);
155 if (!name)
156 goto error;
157
Serhiy Storchaka06515832016-11-20 09:13:07 +0200158 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000159 if (name_utf8 == NULL)
160 goto error;
161 name_str = _PyMem_RawStrdup(name_utf8);
162 Py_DECREF(name);
163 if (name_str == NULL) {
164 PyErr_NoMemory();
165 return NULL;
166 }
167 return name_str;
168
169error:
170 Py_XDECREF(codec);
171 Py_XDECREF(name);
172 return NULL;
173}
174
Nick Coghland6009512014-11-20 21:39:37 +1000175
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800176static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700177initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000178{
179 PyObject *importlib;
180 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000181 PyObject *value;
182
183 /* Import _importlib through its frozen version, _frozen_importlib. */
184 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800185 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000186 }
187 else if (Py_VerboseFlag) {
188 PySys_FormatStderr("import _frozen_importlib # frozen\n");
189 }
190 importlib = PyImport_AddModule("_frozen_importlib");
191 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800192 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000193 }
194 interp->importlib = importlib;
195 Py_INCREF(interp->importlib);
196
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300197 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
198 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800199 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300200 Py_INCREF(interp->import_func);
201
Victor Stinnercd6e6942015-09-18 09:11:57 +0200202 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800203 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000204 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800205 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000206 }
207 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200208 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000209 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600210 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800211 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000212 }
213
Victor Stinnercd6e6942015-09-18 09:11:57 +0200214 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000215 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
216 if (value == NULL) {
217 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800218 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000219 }
220 Py_DECREF(value);
221 Py_DECREF(impmod);
222
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800223 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000224}
225
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800226static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700227initexternalimport(PyInterpreterState *interp)
228{
229 PyObject *value;
230 value = PyObject_CallMethod(interp->importlib,
231 "_install_external_importers", "");
232 if (value == NULL) {
233 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800234 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700235 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200236 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300237 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700238}
Nick Coghland6009512014-11-20 21:39:37 +1000239
Nick Coghlan6ea41862017-06-11 13:16:15 +1000240/* Helper functions to better handle the legacy C locale
241 *
242 * The legacy C locale assumes ASCII as the default text encoding, which
243 * causes problems not only for the CPython runtime, but also other
244 * components like GNU readline.
245 *
246 * Accordingly, when the CLI detects it, it attempts to coerce it to a
247 * more capable UTF-8 based alternative as follows:
248 *
249 * if (_Py_LegacyLocaleDetected()) {
250 * _Py_CoerceLegacyLocale();
251 * }
252 *
253 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
254 *
255 * Locale coercion also impacts the default error handler for the standard
256 * streams: while the usual default is "strict", the default for the legacy
257 * C locale and for any of the coercion target locales is "surrogateescape".
258 */
259
260int
261_Py_LegacyLocaleDetected(void)
262{
263#ifndef MS_WINDOWS
264 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000265 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
266 * the POSIX locale as a simple alias for the C locale, so
267 * we may also want to check for that explicitly.
268 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000269 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
270 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
271#else
272 /* Windows uses code pages instead of locales, so no locale is legacy */
273 return 0;
274#endif
275}
276
Nick Coghlaneb817952017-06-18 12:29:42 +1000277static const char *_C_LOCALE_WARNING =
278 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
279 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
280 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
281 "locales is recommended.\n";
282
Nick Coghlaneb817952017-06-18 12:29:42 +1000283static void
Victor Stinner94540602017-12-16 04:54:22 +0100284_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000285{
Victor Stinner06e76082018-09-19 14:56:36 -0700286 if (core_config->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200287 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000288 }
289}
290
Nick Coghlan6ea41862017-06-11 13:16:15 +1000291typedef struct _CandidateLocale {
292 const char *locale_name; /* The locale to try as a coercion target */
293} _LocaleCoercionTarget;
294
295static _LocaleCoercionTarget _TARGET_LOCALES[] = {
296 {"C.UTF-8"},
297 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000298 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000299 {NULL}
300};
301
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200302
303int
304_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000305{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200306 const _LocaleCoercionTarget *target = NULL;
307 for (target = _TARGET_LOCALES; target->locale_name; target++) {
308 if (strcmp(ctype_loc, target->locale_name) == 0) {
309 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000310 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200311 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200312 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000313}
314
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200315
Nick Coghlan6ea41862017-06-11 13:16:15 +1000316#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100317static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
319 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
320
321static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200322_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000323{
324 const char *newloc = target->locale_name;
325
326 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100327 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328
329 /* Set the relevant locale environment variable */
330 if (setenv("LC_CTYPE", newloc, 1)) {
331 fprintf(stderr,
332 "Error setting LC_CTYPE, skipping C locale coercion\n");
333 return;
334 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200335 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100336 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000337 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000338
339 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100340 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000341}
342#endif
343
344void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200345_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000346{
347#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200348 char *oldloc = NULL;
349
350 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
351 if (oldloc == NULL) {
352 return;
353 }
354
Victor Stinner94540602017-12-16 04:54:22 +0100355 const char *locale_override = getenv("LC_ALL");
356 if (locale_override == NULL || *locale_override == '\0') {
357 /* LC_ALL is also not set (or is set to an empty string) */
358 const _LocaleCoercionTarget *target = NULL;
359 for (target = _TARGET_LOCALES; target->locale_name; target++) {
360 const char *new_locale = setlocale(LC_CTYPE,
361 target->locale_name);
362 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100363#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100364defined(HAVE_LANGINFO_H) && defined(CODESET)
365 /* Also ensure that nl_langinfo works in this locale */
366 char *codeset = nl_langinfo(CODESET);
367 if (!codeset || *codeset == '\0') {
368 /* CODESET is not set or empty, so skip coercion */
369 new_locale = NULL;
370 _Py_SetLocaleFromEnv(LC_CTYPE);
371 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000372 }
Victor Stinner94540602017-12-16 04:54:22 +0100373#endif
374 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200375 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200376 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000377 }
378 }
379 }
380 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200381
382 setlocale(LC_CTYPE, oldloc);
383
384done:
385 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000386#endif
387}
388
xdegaye1588be62017-11-12 12:45:59 +0100389/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
390 * isolate the idiosyncrasies of different libc implementations. It reads the
391 * appropriate environment variable and uses its value to select the locale for
392 * 'category'. */
393char *
394_Py_SetLocaleFromEnv(int category)
395{
396#ifdef __ANDROID__
397 const char *locale;
398 const char **pvar;
399#ifdef PY_COERCE_C_LOCALE
400 const char *coerce_c_locale;
401#endif
402 const char *utf8_locale = "C.UTF-8";
403 const char *env_var_set[] = {
404 "LC_ALL",
405 "LC_CTYPE",
406 "LANG",
407 NULL,
408 };
409
410 /* Android setlocale(category, "") doesn't check the environment variables
411 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
412 * check the environment variables listed in env_var_set. */
413 for (pvar=env_var_set; *pvar; pvar++) {
414 locale = getenv(*pvar);
415 if (locale != NULL && *locale != '\0') {
416 if (strcmp(locale, utf8_locale) == 0 ||
417 strcmp(locale, "en_US.UTF-8") == 0) {
418 return setlocale(category, utf8_locale);
419 }
420 return setlocale(category, "C");
421 }
422 }
423
424 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
425 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
426 * Quote from POSIX section "8.2 Internationalization Variables":
427 * "4. If the LANG environment variable is not set or is set to the empty
428 * string, the implementation-defined default locale shall be used." */
429
430#ifdef PY_COERCE_C_LOCALE
431 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
432 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
433 /* Some other ported code may check the environment variables (e.g. in
434 * extension modules), so we make sure that they match the locale
435 * configuration */
436 if (setenv("LC_CTYPE", utf8_locale, 1)) {
437 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
438 "environment variable to %s\n", utf8_locale);
439 }
440 }
441#endif
442 return setlocale(category, utf8_locale);
443#else /* __ANDROID__ */
444 return setlocale(category, "");
445#endif /* __ANDROID__ */
446}
447
Nick Coghlan6ea41862017-06-11 13:16:15 +1000448
Eric Snow1abcf672017-05-23 21:46:51 -0700449/* Global initializations. Can be undone by Py_Finalize(). Don't
450 call this twice without an intervening Py_Finalize() call.
451
Victor Stinner1dc6e392018-07-25 02:49:17 +0200452 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700453 must have a corresponding call to Py_Finalize.
454
455 Locking: you must hold the interpreter lock while calling these APIs.
456 (If the lock has not yet been initialized, that's equivalent to
457 having the lock, but you cannot use multiple threads.)
458
459*/
460
Victor Stinner1dc6e392018-07-25 02:49:17 +0200461static _PyInitError
462_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
463 const _PyCoreConfig *core_config)
464{
465 if (core_config->allocator != NULL) {
466 const char *allocator = _PyMem_GetAllocatorsName();
467 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
468 return _Py_INIT_USER_ERR("cannot modify memory allocator "
469 "after first Py_Initialize()");
470 }
471 }
472
473 _PyCoreConfig_SetGlobalConfig(core_config);
474
475 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
476 return _Py_INIT_ERR("failed to copy core config");
477 }
478 core_config = &interp->core_config;
479
480 if (core_config->_install_importlib) {
481 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
482 if (_Py_INIT_FAILED(err)) {
483 return err;
484 }
485 }
486 return _Py_INIT_OK();
487}
488
489
Eric Snow1abcf672017-05-23 21:46:51 -0700490/* Begin interpreter initialization
491 *
492 * On return, the first thread and interpreter state have been created,
493 * but the compiler, signal handling, multithreading and
494 * multiple interpreter support, and codec infrastructure are not yet
495 * available.
496 *
497 * The import system will support builtin and frozen modules only.
498 * The only supported io is writing to sys.stderr
499 *
500 * If any operation invoked by this function fails, a fatal error is
501 * issued and the function does not return.
502 *
503 * Any code invoked from this function should *not* assume it has access
504 * to the Python C API (unless the API is explicitly listed as being
505 * safe to call without calling Py_Initialize first)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200506 *
507 * The caller is responsible to call _PyCoreConfig_Read().
Eric Snow1abcf672017-05-23 21:46:51 -0700508 */
509
Victor Stinner1dc6e392018-07-25 02:49:17 +0200510static _PyInitError
511_Py_InitializeCore_impl(PyInterpreterState **interp_p,
512 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000513{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200514 PyInterpreterState *interp;
515 _PyInitError err;
516
517 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
518 Py_Initialize() ignores the new configuration. */
519 if (_PyRuntime.core_initialized) {
Victor Stinner50b48572018-11-01 01:51:40 +0100520 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200521 if (!tstate) {
522 return _Py_INIT_ERR("failed to read thread state");
523 }
524
525 interp = tstate->interp;
526 if (interp == NULL) {
527 return _Py_INIT_ERR("can't make main interpreter");
528 }
529 *interp_p = interp;
530
531 return _Py_Initialize_ReconfigureCore(interp, core_config);
532 }
533
534 if (_PyRuntime.initialized) {
535 return _Py_INIT_ERR("main interpreter already initialized");
536 }
Victor Stinnerda273412017-12-15 01:46:02 +0100537
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200538 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000539
Victor Stinner1dc6e392018-07-25 02:49:17 +0200540 err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800541 if (_Py_INIT_FAILED(err)) {
542 return err;
543 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600544
Victor Stinner31e99082017-12-20 23:41:38 +0100545 if (core_config->allocator != NULL) {
546 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
547 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
548 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800549 }
550
Eric Snow1abcf672017-05-23 21:46:51 -0700551 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
552 * threads behave a little more gracefully at interpreter shutdown.
553 * We clobber it here so the new interpreter can start with a clean
554 * slate.
555 *
556 * However, this may still lead to misbehaviour if there are daemon
557 * threads still hanging around from a previous Py_Initialize/Finalize
558 * pair :(
559 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600560 _PyRuntime.finalizing = NULL;
561
Victor Stinnerda273412017-12-15 01:46:02 +0100562 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800563 if (_Py_INIT_FAILED(err)) {
564 return err;
565 }
566
Victor Stinnera7368ac2017-11-15 18:11:45 -0800567 err = _PyInterpreterState_Enable(&_PyRuntime);
568 if (_Py_INIT_FAILED(err)) {
569 return err;
570 }
571
Victor Stinner1dc6e392018-07-25 02:49:17 +0200572 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100573 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800574 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100575 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200576 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100577
578 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
579 return _Py_INIT_ERR("failed to copy core config");
580 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200581 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000582
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200583 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000584 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800585 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000586 (void) PyThreadState_Swap(tstate);
587
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000588 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000589 destroying the GIL might fail when it is being referenced from
590 another running thread (see issue #9901).
591 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000592 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000593 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100594
Nick Coghland6009512014-11-20 21:39:37 +1000595 /* Auto-thread-state API */
596 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000597
Victor Stinner2914bb32018-01-29 11:57:45 +0100598 /* Create the GIL */
599 PyEval_InitThreads();
600
Nick Coghland6009512014-11-20 21:39:37 +1000601 _Py_ReadyTypes();
602
Nick Coghland6009512014-11-20 21:39:37 +1000603 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800604 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000605
606 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800607 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000608
609 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800610 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000611
Eric Snowd393c1b2017-09-14 12:18:12 -0600612 PyObject *modules = PyDict_New();
613 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800614 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600615 interp->modules = modules;
616
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200617 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800618 err = _PySys_BeginInit(&sysmod);
619 if (_Py_INIT_FAILED(err)) {
620 return err;
621 }
622
Eric Snowd393c1b2017-09-14 12:18:12 -0600623 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800624 if (interp->sysdict == NULL) {
625 return _Py_INIT_ERR("can't initialize sys dict");
626 }
627
Eric Snowd393c1b2017-09-14 12:18:12 -0600628 Py_INCREF(interp->sysdict);
629 PyDict_SetItemString(interp->sysdict, "modules", modules);
630 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000631
632 /* Init Unicode implementation; relies on the codec registry */
633 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800634 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700635
Nick Coghland6009512014-11-20 21:39:37 +1000636 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800637 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000638
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200639 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000640 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800641 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600642 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000643 interp->builtins = PyModule_GetDict(bimod);
644 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800645 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000646 Py_INCREF(interp->builtins);
647
648 /* initialize builtin exceptions */
649 _PyExc_Init(bimod);
650
Nick Coghland6009512014-11-20 21:39:37 +1000651 /* Set up a preliminary stderr printer until we have enough
652 infrastructure for the io module in place. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200653 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000654 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800655 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000656 _PySys_SetObjectId(&PyId_stderr, pstderr);
657 PySys_SetObject("__stderr__", pstderr);
658 Py_DECREF(pstderr);
659
Victor Stinner672b6ba2017-12-06 17:25:50 +0100660 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800661 if (_Py_INIT_FAILED(err)) {
662 return err;
663 }
Nick Coghland6009512014-11-20 21:39:37 +1000664
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800665 err = _PyImportHooks_Init();
666 if (_Py_INIT_FAILED(err)) {
667 return err;
668 }
Nick Coghland6009512014-11-20 21:39:37 +1000669
670 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100671 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100672 return _Py_INIT_ERR("can't initialize warnings");
673 }
Nick Coghland6009512014-11-20 21:39:37 +1000674
Yury Selivanovf23746a2018-01-22 19:11:18 -0500675 if (!_PyContext_Init())
676 return _Py_INIT_ERR("can't init context");
677
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200678 if (core_config->_install_importlib) {
Victor Stinnerb1147e42018-07-21 02:06:16 +0200679 err = _PyCoreConfig_SetPathConfig(core_config);
680 if (_Py_INIT_FAILED(err)) {
681 return err;
682 }
683 }
684
Eric Snow1abcf672017-05-23 21:46:51 -0700685 /* This call sets up builtin and frozen import support */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200686 if (core_config->_install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800687 err = initimport(interp, sysmod);
688 if (_Py_INIT_FAILED(err)) {
689 return err;
690 }
Eric Snow1abcf672017-05-23 21:46:51 -0700691 }
692
693 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600694 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800695 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700696}
697
Victor Stinner1dc6e392018-07-25 02:49:17 +0200698_PyInitError
699_Py_InitializeCore(PyInterpreterState **interp_p,
700 const _PyCoreConfig *src_config)
701{
702 assert(src_config != NULL);
703
Victor Stinner1dc6e392018-07-25 02:49:17 +0200704 PyMemAllocatorEx old_alloc;
705 _PyInitError err;
706
707 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
708 (and the input configuration is read only). */
709 _PyCoreConfig config = _PyCoreConfig_INIT;
710
Victor Stinner177d9212018-08-29 11:25:15 +0200711 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200712 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200713
Victor Stinner1dc6e392018-07-25 02:49:17 +0200714 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
715 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
716 err = _PyCoreConfig_Read(&config);
717 }
718 else {
719 err = _Py_INIT_ERR("failed to copy core config");
720 }
721 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
722
723 if (_Py_INIT_FAILED(err)) {
724 goto done;
725 }
726
727 err = _Py_InitializeCore_impl(interp_p, &config);
728
729done:
730 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
731 _PyCoreConfig_Clear(&config);
732 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
733
734 return err;
735}
736
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200737/* Py_Initialize() has already been called: update the main interpreter
738 configuration. Example of bpo-34008: Py_Main() called after
739 Py_Initialize(). */
740static _PyInitError
741_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
742 const _PyMainInterpreterConfig *config)
743{
744 if (config->argv != NULL) {
745 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
746 if (res < 0) {
747 return _Py_INIT_ERR("fail to set sys.argv");
748 }
749 }
750 return _Py_INIT_OK();
751}
752
Eric Snowc7ec9982017-05-23 23:00:52 -0700753/* Update interpreter state based on supplied configuration settings
754 *
755 * After calling this function, most of the restrictions on the interpreter
756 * are lifted. The only remaining incomplete settings are those related
757 * to the main module (sys.argv[0], __main__ metadata)
758 *
759 * Calling this when the interpreter is not initializing, is already
760 * initialized or without a valid current thread state is a fatal error.
761 * Other errors should be reported as normal Python exceptions with a
762 * non-zero return code.
763 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800764_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200765_Py_InitializeMainInterpreter(PyInterpreterState *interp,
766 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700767{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600768 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800769 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700770 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700771
Victor Stinner1dc6e392018-07-25 02:49:17 +0200772 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100773 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
774 return _Py_INIT_ERR("failed to copy main interpreter config");
775 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200776 config = &interp->config;
777 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700778
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200779 if (_PyRuntime.initialized) {
780 return _Py_ReconfigureMainInterpreter(interp, config);
781 }
782
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200783 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700784 /* Special mode for freeze_importlib: run with no import system
785 *
786 * This means anything which needs support from extension modules
787 * or pure Python code in the standard library won't work.
788 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600789 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800790 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700791 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100792
Victor Stinner33c377e2017-12-05 15:12:41 +0100793 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800794 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100795 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200796
Victor Stinnerfbca9082018-08-30 00:50:45 +0200797 if (_PySys_EndInit(interp->sysdict, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800798 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100799 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800800
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200801 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800802 if (_Py_INIT_FAILED(err)) {
803 return err;
804 }
Nick Coghland6009512014-11-20 21:39:37 +1000805
806 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200807 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800808 if (_Py_INIT_FAILED(err)) {
809 return err;
810 }
Nick Coghland6009512014-11-20 21:39:37 +1000811
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800812 err = initfsencoding(interp);
813 if (_Py_INIT_FAILED(err)) {
814 return err;
815 }
Nick Coghland6009512014-11-20 21:39:37 +1000816
Victor Stinner1f151112017-11-23 10:43:14 +0100817 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800818 err = initsigs(); /* Signal handling stuff, including initintr() */
819 if (_Py_INIT_FAILED(err)) {
820 return err;
821 }
822 }
Nick Coghland6009512014-11-20 21:39:37 +1000823
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200824 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800825 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200826 }
Nick Coghland6009512014-11-20 21:39:37 +1000827
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800828 err = add_main_module(interp);
829 if (_Py_INIT_FAILED(err)) {
830 return err;
831 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800832
Victor Stinner91106cd2017-12-13 12:29:09 +0100833 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800834 if (_Py_INIT_FAILED(err)) {
835 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800836 }
Nick Coghland6009512014-11-20 21:39:37 +1000837
838 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100839 PyObject *warnoptions = PySys_GetObject("warnoptions");
840 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100841 {
Nick Coghland6009512014-11-20 21:39:37 +1000842 PyObject *warnings_module = PyImport_ImportModule("warnings");
843 if (warnings_module == NULL) {
844 fprintf(stderr, "'import warnings' failed; traceback:\n");
845 PyErr_Print();
846 }
847 Py_XDECREF(warnings_module);
848 }
849
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600850 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700851
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200852 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800853 err = initsite(); /* Module site */
854 if (_Py_INIT_FAILED(err)) {
855 return err;
856 }
857 }
Victor Stinnercf215042018-08-29 22:56:06 +0200858
859#ifndef MS_WINDOWS
860 _emit_stderr_warning_for_legacy_locale(core_config);
861#endif
862
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800863 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000864}
865
Eric Snowc7ec9982017-05-23 23:00:52 -0700866#undef _INIT_DEBUG_PRINT
867
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800868_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200869_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700870{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700871 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800872 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200873 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800874 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200875 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800876 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200877 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100878
Victor Stinner9cfc0022017-12-20 19:36:46 +0100879 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200880 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100881 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200882 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800883 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100884 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800885 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200886 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800887 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200888 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700889}
890
891
892void
Nick Coghland6009512014-11-20 21:39:37 +1000893Py_InitializeEx(int install_sigs)
894{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200895 if (_PyRuntime.initialized) {
896 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
897 return;
898 }
899
900 _PyInitError err;
901 _PyCoreConfig config = _PyCoreConfig_INIT;
902 config.install_signal_handlers = install_sigs;
903
904 err = _Py_InitializeFromConfig(&config);
905 _PyCoreConfig_Clear(&config);
906
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800907 if (_Py_INIT_FAILED(err)) {
908 _Py_FatalInitError(err);
909 }
Nick Coghland6009512014-11-20 21:39:37 +1000910}
911
912void
913Py_Initialize(void)
914{
915 Py_InitializeEx(1);
916}
917
918
919#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000920extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000921#endif
922
923/* Flush stdout and stderr */
924
925static int
926file_is_closed(PyObject *fobj)
927{
928 int r;
929 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
930 if (tmp == NULL) {
931 PyErr_Clear();
932 return 0;
933 }
934 r = PyObject_IsTrue(tmp);
935 Py_DECREF(tmp);
936 if (r < 0)
937 PyErr_Clear();
938 return r > 0;
939}
940
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000941static int
Nick Coghland6009512014-11-20 21:39:37 +1000942flush_std_files(void)
943{
944 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
945 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
946 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000947 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000948
949 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700950 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000951 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000952 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000953 status = -1;
954 }
Nick Coghland6009512014-11-20 21:39:37 +1000955 else
956 Py_DECREF(tmp);
957 }
958
959 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700960 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000961 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000962 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000963 status = -1;
964 }
Nick Coghland6009512014-11-20 21:39:37 +1000965 else
966 Py_DECREF(tmp);
967 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000968
969 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000970}
971
972/* Undo the effect of Py_Initialize().
973
974 Beware: if multiple interpreter and/or thread states exist, these
975 are not wiped out; only the current thread and interpreter state
976 are deleted. But since everything else is deleted, those other
977 interpreter and thread states should no longer be used.
978
979 (XXX We should do better, e.g. wipe out all interpreters and
980 threads.)
981
982 Locking: as above.
983
984*/
985
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000986int
987Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000988{
989 PyInterpreterState *interp;
990 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000991 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000992
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600993 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000994 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000995
996 wait_for_thread_shutdown();
997
Marcel Plch776407f2017-12-20 11:17:58 +0100998 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +0100999 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001000 interp = tstate->interp;
1001
Nick Coghland6009512014-11-20 21:39:37 +10001002 /* The interpreter is still entirely intact at this point, and the
1003 * exit funcs may be relying on that. In particular, if some thread
1004 * or exit func is still waiting to do an import, the import machinery
1005 * expects Py_IsInitialized() to return true. So don't say the
1006 * interpreter is uninitialized until after the exit funcs have run.
1007 * Note that Threading.py uses an exit func to do a join on all the
1008 * threads created thru it, so this also protects pending imports in
1009 * the threads created via Threading.
1010 */
Nick Coghland6009512014-11-20 21:39:37 +10001011
Marcel Plch776407f2017-12-20 11:17:58 +01001012 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001013
Victor Stinnerda273412017-12-15 01:46:02 +01001014 /* Copy the core config, PyInterpreterState_Delete() free
1015 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001016#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001017 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001018#endif
1019#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001020 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001021#endif
1022#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001023 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001024#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001025
Nick Coghland6009512014-11-20 21:39:37 +10001026 /* Remaining threads (e.g. daemon threads) will automatically exit
1027 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001028 _PyRuntime.finalizing = tstate;
1029 _PyRuntime.initialized = 0;
1030 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001031
Victor Stinnere0deff32015-03-24 13:46:18 +01001032 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001033 if (flush_std_files() < 0) {
1034 status = -1;
1035 }
Nick Coghland6009512014-11-20 21:39:37 +10001036
1037 /* Disable signal handling */
1038 PyOS_FiniInterrupts();
1039
1040 /* Collect garbage. This may call finalizers; it's nice to call these
1041 * before all modules are destroyed.
1042 * XXX If a __del__ or weakref callback is triggered here, and tries to
1043 * XXX import a module, bad things can happen, because Python no
1044 * XXX longer believes it's initialized.
1045 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1046 * XXX is easy to provoke that way. I've also seen, e.g.,
1047 * XXX Exception exceptions.ImportError: 'No module named sha'
1048 * XXX in <function callback at 0x008F5718> ignored
1049 * XXX but I'm unclear on exactly how that one happens. In any case,
1050 * XXX I haven't seen a real-life report of either of these.
1051 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001052 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001053#ifdef COUNT_ALLOCS
1054 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1055 each collection might release some types from the type
1056 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001057 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001058 /* nothing */;
1059#endif
Eric Snowdae02762017-09-14 00:35:58 -07001060
Nick Coghland6009512014-11-20 21:39:37 +10001061 /* Destroy all modules */
1062 PyImport_Cleanup();
1063
Victor Stinnere0deff32015-03-24 13:46:18 +01001064 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001065 if (flush_std_files() < 0) {
1066 status = -1;
1067 }
Nick Coghland6009512014-11-20 21:39:37 +10001068
1069 /* Collect final garbage. This disposes of cycles created by
1070 * class definitions, for example.
1071 * XXX This is disabled because it caused too many problems. If
1072 * XXX a __del__ or weakref callback triggers here, Python code has
1073 * XXX a hard time running, because even the sys module has been
1074 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1075 * XXX One symptom is a sequence of information-free messages
1076 * XXX coming from threads (if a __del__ or callback is invoked,
1077 * XXX other threads can execute too, and any exception they encounter
1078 * XXX triggers a comedy of errors as subsystem after subsystem
1079 * XXX fails to find what it *expects* to find in sys to help report
1080 * XXX the exception and consequent unexpected failures). I've also
1081 * XXX seen segfaults then, after adding print statements to the
1082 * XXX Python code getting called.
1083 */
1084#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001085 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001086#endif
1087
1088 /* Disable tracemalloc after all Python objects have been destroyed,
1089 so it is possible to use tracemalloc in objects destructor. */
1090 _PyTraceMalloc_Fini();
1091
1092 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1093 _PyImport_Fini();
1094
1095 /* Cleanup typeobject.c's internal caches. */
1096 _PyType_Fini();
1097
1098 /* unload faulthandler module */
1099 _PyFaulthandler_Fini();
1100
1101 /* Debugging stuff */
1102#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001103 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001104#endif
1105 /* dump hash stats */
1106 _PyHash_Fini();
1107
Eric Snowdae02762017-09-14 00:35:58 -07001108#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001109 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001110 _PyDebug_PrintTotalRefs();
1111 }
Eric Snowdae02762017-09-14 00:35:58 -07001112#endif
Nick Coghland6009512014-11-20 21:39:37 +10001113
1114#ifdef Py_TRACE_REFS
1115 /* Display all objects still alive -- this can invoke arbitrary
1116 * __repr__ overrides, so requires a mostly-intact interpreter.
1117 * Alas, a lot of stuff may still be alive now that will be cleaned
1118 * up later.
1119 */
Victor Stinnerda273412017-12-15 01:46:02 +01001120 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001121 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001122 }
Nick Coghland6009512014-11-20 21:39:37 +10001123#endif /* Py_TRACE_REFS */
1124
1125 /* Clear interpreter state and all thread states. */
1126 PyInterpreterState_Clear(interp);
1127
1128 /* Now we decref the exception classes. After this point nothing
1129 can raise an exception. That's okay, because each Fini() method
1130 below has been checked to make sure no exceptions are ever
1131 raised.
1132 */
1133
1134 _PyExc_Fini();
1135
1136 /* Sundry finalizers */
1137 PyMethod_Fini();
1138 PyFrame_Fini();
1139 PyCFunction_Fini();
1140 PyTuple_Fini();
1141 PyList_Fini();
1142 PySet_Fini();
1143 PyBytes_Fini();
1144 PyByteArray_Fini();
1145 PyLong_Fini();
1146 PyFloat_Fini();
1147 PyDict_Fini();
1148 PySlice_Fini();
1149 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001150 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001151 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001152 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001153 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001154
1155 /* Cleanup Unicode implementation */
1156 _PyUnicode_Fini();
1157
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001158 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001159
1160 /* XXX Still allocated:
1161 - various static ad-hoc pointers to interned strings
1162 - int and float free list blocks
1163 - whatever various modules and libraries allocate
1164 */
1165
1166 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1167
1168 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001169 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001170
1171 /* Delete current thread. After this, many C API calls become crashy. */
1172 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001173
Nick Coghland6009512014-11-20 21:39:37 +10001174 PyInterpreterState_Delete(interp);
1175
1176#ifdef Py_TRACE_REFS
1177 /* Display addresses (& refcnts) of all objects still alive.
1178 * An address can be used to find the repr of the object, printed
1179 * above by _Py_PrintReferences.
1180 */
Victor Stinnerda273412017-12-15 01:46:02 +01001181 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001182 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001183 }
Nick Coghland6009512014-11-20 21:39:37 +10001184#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001185#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001186 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001187 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001188 }
Nick Coghland6009512014-11-20 21:39:37 +10001189#endif
1190
1191 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001192
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001193 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001194 return status;
1195}
1196
1197void
1198Py_Finalize(void)
1199{
1200 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001201}
1202
1203/* Create and initialize a new interpreter and thread, and return the
1204 new thread. This requires that Py_Initialize() has been called
1205 first.
1206
1207 Unsuccessful initialization yields a NULL pointer. Note that *no*
1208 exception information is available even in this case -- the
1209 exception information is held in the thread, and there is no
1210 thread.
1211
1212 Locking: as above.
1213
1214*/
1215
Victor Stinnera7368ac2017-11-15 18:11:45 -08001216static _PyInitError
1217new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001218{
1219 PyInterpreterState *interp;
1220 PyThreadState *tstate, *save_tstate;
1221 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001222 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001223
Victor Stinnera7368ac2017-11-15 18:11:45 -08001224 if (!_PyRuntime.initialized) {
1225 return _Py_INIT_ERR("Py_Initialize must be called first");
1226 }
Nick Coghland6009512014-11-20 21:39:37 +10001227
Victor Stinner8a1be612016-03-14 22:07:55 +01001228 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1229 interpreters: disable PyGILState_Check(). */
1230 _PyGILState_check_enabled = 0;
1231
Nick Coghland6009512014-11-20 21:39:37 +10001232 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001233 if (interp == NULL) {
1234 *tstate_p = NULL;
1235 return _Py_INIT_OK();
1236 }
Nick Coghland6009512014-11-20 21:39:37 +10001237
1238 tstate = PyThreadState_New(interp);
1239 if (tstate == NULL) {
1240 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001241 *tstate_p = NULL;
1242 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001243 }
1244
1245 save_tstate = PyThreadState_Swap(tstate);
1246
Eric Snow1abcf672017-05-23 21:46:51 -07001247 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001248 _PyCoreConfig *core_config;
1249 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001250 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001251 core_config = &save_tstate->interp->core_config;
1252 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001253 } else {
1254 /* No current thread state, copy from the main interpreter */
1255 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001256 core_config = &main_interp->core_config;
1257 config = &main_interp->config;
1258 }
1259
1260 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1261 return _Py_INIT_ERR("failed to copy core config");
1262 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001263 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001264 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1265 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001266 }
1267
Nick Coghland6009512014-11-20 21:39:37 +10001268 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001269 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001270 if (modules == NULL) {
1271 return _Py_INIT_ERR("can't make modules dictionary");
1272 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001273 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001274
Eric Snowd393c1b2017-09-14 12:18:12 -06001275 sysmod = _PyImport_FindBuiltin("sys", modules);
1276 if (sysmod != NULL) {
1277 interp->sysdict = PyModule_GetDict(sysmod);
1278 if (interp->sysdict == NULL)
1279 goto handle_error;
1280 Py_INCREF(interp->sysdict);
1281 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001282 _PySys_EndInit(interp->sysdict, interp);
Eric Snowd393c1b2017-09-14 12:18:12 -06001283 }
1284
1285 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001286 if (bimod != NULL) {
1287 interp->builtins = PyModule_GetDict(bimod);
1288 if (interp->builtins == NULL)
1289 goto handle_error;
1290 Py_INCREF(interp->builtins);
1291 }
1292
1293 /* initialize builtin exceptions */
1294 _PyExc_Init(bimod);
1295
Nick Coghland6009512014-11-20 21:39:37 +10001296 if (bimod != NULL && sysmod != NULL) {
1297 PyObject *pstderr;
1298
Nick Coghland6009512014-11-20 21:39:37 +10001299 /* Set up a preliminary stderr printer until we have enough
1300 infrastructure for the io module in place. */
1301 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001302 if (pstderr == NULL) {
1303 return _Py_INIT_ERR("can't set preliminary stderr");
1304 }
Nick Coghland6009512014-11-20 21:39:37 +10001305 _PySys_SetObjectId(&PyId_stderr, pstderr);
1306 PySys_SetObject("__stderr__", pstderr);
1307 Py_DECREF(pstderr);
1308
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001309 err = _PyImportHooks_Init();
1310 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001311 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001312 }
Nick Coghland6009512014-11-20 21:39:37 +10001313
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001314 err = initimport(interp, sysmod);
1315 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001316 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001317 }
Nick Coghland6009512014-11-20 21:39:37 +10001318
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001319 err = initexternalimport(interp);
1320 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001321 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001322 }
Nick Coghland6009512014-11-20 21:39:37 +10001323
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001324 err = initfsencoding(interp);
1325 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001326 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001327 }
1328
Victor Stinner91106cd2017-12-13 12:29:09 +01001329 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001330 if (_Py_INIT_FAILED(err)) {
1331 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001332 }
1333
1334 err = add_main_module(interp);
1335 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001336 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001337 }
1338
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001339 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001340 err = initsite();
1341 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001342 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001343 }
1344 }
Nick Coghland6009512014-11-20 21:39:37 +10001345 }
1346
Victor Stinnera7368ac2017-11-15 18:11:45 -08001347 if (PyErr_Occurred()) {
1348 goto handle_error;
1349 }
Nick Coghland6009512014-11-20 21:39:37 +10001350
Victor Stinnera7368ac2017-11-15 18:11:45 -08001351 *tstate_p = tstate;
1352 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001353
Nick Coghland6009512014-11-20 21:39:37 +10001354handle_error:
1355 /* Oops, it didn't work. Undo it all. */
1356
1357 PyErr_PrintEx(0);
1358 PyThreadState_Clear(tstate);
1359 PyThreadState_Swap(save_tstate);
1360 PyThreadState_Delete(tstate);
1361 PyInterpreterState_Delete(interp);
1362
Victor Stinnera7368ac2017-11-15 18:11:45 -08001363 *tstate_p = NULL;
1364 return _Py_INIT_OK();
1365}
1366
1367PyThreadState *
1368Py_NewInterpreter(void)
1369{
1370 PyThreadState *tstate;
1371 _PyInitError err = new_interpreter(&tstate);
1372 if (_Py_INIT_FAILED(err)) {
1373 _Py_FatalInitError(err);
1374 }
1375 return tstate;
1376
Nick Coghland6009512014-11-20 21:39:37 +10001377}
1378
1379/* Delete an interpreter and its last thread. This requires that the
1380 given thread state is current, that the thread has no remaining
1381 frames, and that it is its interpreter's only remaining thread.
1382 It is a fatal error to violate these constraints.
1383
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001384 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001385 everything, regardless.)
1386
1387 Locking: as above.
1388
1389*/
1390
1391void
1392Py_EndInterpreter(PyThreadState *tstate)
1393{
1394 PyInterpreterState *interp = tstate->interp;
1395
Victor Stinner50b48572018-11-01 01:51:40 +01001396 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001397 Py_FatalError("Py_EndInterpreter: thread is not current");
1398 if (tstate->frame != NULL)
1399 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1400
1401 wait_for_thread_shutdown();
1402
Marcel Plch776407f2017-12-20 11:17:58 +01001403 call_py_exitfuncs(interp);
1404
Nick Coghland6009512014-11-20 21:39:37 +10001405 if (tstate != interp->tstate_head || tstate->next != NULL)
1406 Py_FatalError("Py_EndInterpreter: not the last thread");
1407
1408 PyImport_Cleanup();
1409 PyInterpreterState_Clear(interp);
1410 PyThreadState_Swap(NULL);
1411 PyInterpreterState_Delete(interp);
1412}
1413
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001414/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001415
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001416static _PyInitError
1417add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001418{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001419 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001420 m = PyImport_AddModule("__main__");
1421 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001422 return _Py_INIT_ERR("can't create __main__ module");
1423
Nick Coghland6009512014-11-20 21:39:37 +10001424 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001425 ann_dict = PyDict_New();
1426 if ((ann_dict == NULL) ||
1427 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001428 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001429 }
1430 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001431
Nick Coghland6009512014-11-20 21:39:37 +10001432 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1433 PyObject *bimod = PyImport_ImportModule("builtins");
1434 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001435 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001436 }
1437 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001438 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001439 }
1440 Py_DECREF(bimod);
1441 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001442
Nick Coghland6009512014-11-20 21:39:37 +10001443 /* Main is a little special - imp.is_builtin("__main__") will return
1444 * False, but BuiltinImporter is still the most appropriate initial
1445 * setting for its __loader__ attribute. A more suitable value will
1446 * be set if __main__ gets further initialized later in the startup
1447 * process.
1448 */
1449 loader = PyDict_GetItemString(d, "__loader__");
1450 if (loader == NULL || loader == Py_None) {
1451 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1452 "BuiltinImporter");
1453 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001454 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001455 }
1456 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001457 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001458 }
1459 Py_DECREF(loader);
1460 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001461 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001462}
1463
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001464static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001465initfsencoding(PyInterpreterState *interp)
1466{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001467 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001468
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001469 char *encoding = get_codec_name(config->filesystem_encoding);
1470 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001471 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001472 memory, import a module of the standard library failed, etc. */
1473 return _Py_INIT_ERR("failed to get the Python codec "
1474 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001475 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001476
1477 /* Update the filesystem encoding to the normalized Python codec name.
1478 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1479 (Python codec name). */
1480 PyMem_RawFree(config->filesystem_encoding);
1481 config->filesystem_encoding = encoding;
1482
1483 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1484 global configuration variables. */
1485 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1486 config->filesystem_errors) < 0) {
1487 return _Py_INIT_NO_MEMORY();
1488 }
1489
1490 /* PyUnicode can now use the Python codec rather than C implementation
1491 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001492 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001493 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001494}
1495
1496/* Import the site module (not into __main__ though) */
1497
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001499initsite(void)
1500{
1501 PyObject *m;
1502 m = PyImport_ImportModule("site");
1503 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001504 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001505 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001506 Py_DECREF(m);
1507 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001508}
1509
Victor Stinner874dbe82015-09-04 17:29:57 +02001510/* Check if a file descriptor is valid or not.
1511 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1512static int
1513is_valid_fd(int fd)
1514{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001515#ifdef __APPLE__
1516 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1517 and the other side of the pipe is closed, dup(1) succeed, whereas
1518 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1519 such error. */
1520 struct stat st;
1521 return (fstat(fd, &st) == 0);
1522#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001523 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001524 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001525 return 0;
1526 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001527 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1528 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1529 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001530 fd2 = dup(fd);
1531 if (fd2 >= 0)
1532 close(fd2);
1533 _Py_END_SUPPRESS_IPH
1534 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001535#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001536}
1537
1538/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001539static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001540create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001541 int fd, int write_mode, const char* name,
1542 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001543{
1544 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1545 const char* mode;
1546 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001547 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001548 int buffering, isatty;
1549 _Py_IDENTIFIER(open);
1550 _Py_IDENTIFIER(isatty);
1551 _Py_IDENTIFIER(TextIOWrapper);
1552 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001553 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001554
Victor Stinner874dbe82015-09-04 17:29:57 +02001555 if (!is_valid_fd(fd))
1556 Py_RETURN_NONE;
1557
Nick Coghland6009512014-11-20 21:39:37 +10001558 /* stdin is always opened in buffered mode, first because it shouldn't
1559 make a difference in common use cases, second because TextIOWrapper
1560 depends on the presence of a read1() method which only exists on
1561 buffered streams.
1562 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001563 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001564 buffering = 0;
1565 else
1566 buffering = -1;
1567 if (write_mode)
1568 mode = "wb";
1569 else
1570 mode = "rb";
1571 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1572 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001573 Py_None, Py_None, /* encoding, errors */
1574 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001575 if (buf == NULL)
1576 goto error;
1577
1578 if (buffering) {
1579 _Py_IDENTIFIER(raw);
1580 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1581 if (raw == NULL)
1582 goto error;
1583 }
1584 else {
1585 raw = buf;
1586 Py_INCREF(raw);
1587 }
1588
Steve Dower39294992016-08-30 21:22:36 -07001589#ifdef MS_WINDOWS
1590 /* Windows console IO is always UTF-8 encoded */
1591 if (PyWindowsConsoleIO_Check(raw))
1592 encoding = "utf-8";
1593#endif
1594
Nick Coghland6009512014-11-20 21:39:37 +10001595 text = PyUnicode_FromString(name);
1596 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1597 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001598 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001599 if (res == NULL)
1600 goto error;
1601 isatty = PyObject_IsTrue(res);
1602 Py_DECREF(res);
1603 if (isatty == -1)
1604 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001605 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001606 write_through = Py_True;
1607 else
1608 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001609 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001610 line_buffering = Py_True;
1611 else
1612 line_buffering = Py_False;
1613
1614 Py_CLEAR(raw);
1615 Py_CLEAR(text);
1616
1617#ifdef MS_WINDOWS
1618 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1619 newlines to "\n".
1620 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1621 newline = NULL;
1622#else
1623 /* sys.stdin: split lines at "\n".
1624 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1625 newline = "\n";
1626#endif
1627
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001628 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001629 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001630 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001631 Py_CLEAR(buf);
1632 if (stream == NULL)
1633 goto error;
1634
1635 if (write_mode)
1636 mode = "w";
1637 else
1638 mode = "r";
1639 text = PyUnicode_FromString(mode);
1640 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1641 goto error;
1642 Py_CLEAR(text);
1643 return stream;
1644
1645error:
1646 Py_XDECREF(buf);
1647 Py_XDECREF(stream);
1648 Py_XDECREF(text);
1649 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001650
Victor Stinner874dbe82015-09-04 17:29:57 +02001651 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1652 /* Issue #24891: the file descriptor was closed after the first
1653 is_valid_fd() check was called. Ignore the OSError and set the
1654 stream to None. */
1655 PyErr_Clear();
1656 Py_RETURN_NONE;
1657 }
1658 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001659}
1660
1661/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001662static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001663init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001664{
1665 PyObject *iomod = NULL, *wrapper;
1666 PyObject *bimod = NULL;
1667 PyObject *m;
1668 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001669 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001670 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001671 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001672 _PyCoreConfig *config = &interp->core_config;
1673
1674 char *codec_name = get_codec_name(config->stdio_encoding);
1675 if (codec_name == NULL) {
1676 return _Py_INIT_ERR("failed to get the Python codec name "
1677 "of the stdio encoding");
1678 }
1679 PyMem_RawFree(config->stdio_encoding);
1680 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001681
1682 /* Hack to avoid a nasty recursion issue when Python is invoked
1683 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1684 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1685 goto error;
1686 }
1687 Py_DECREF(m);
1688
1689 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1690 goto error;
1691 }
1692 Py_DECREF(m);
1693
1694 if (!(bimod = PyImport_ImportModule("builtins"))) {
1695 goto error;
1696 }
1697
1698 if (!(iomod = PyImport_ImportModule("io"))) {
1699 goto error;
1700 }
1701 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1702 goto error;
1703 }
1704
1705 /* Set builtins.open */
1706 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1707 Py_DECREF(wrapper);
1708 goto error;
1709 }
1710 Py_DECREF(wrapper);
1711
Nick Coghland6009512014-11-20 21:39:37 +10001712 /* Set sys.stdin */
1713 fd = fileno(stdin);
1714 /* Under some conditions stdin, stdout and stderr may not be connected
1715 * and fileno() may point to an invalid file descriptor. For example
1716 * GUI apps don't have valid standard streams by default.
1717 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001718 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001719 config->stdio_encoding,
1720 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001721 if (std == NULL)
1722 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001723 PySys_SetObject("__stdin__", std);
1724 _PySys_SetObjectId(&PyId_stdin, std);
1725 Py_DECREF(std);
1726
1727 /* Set sys.stdout */
1728 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001729 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001730 config->stdio_encoding,
1731 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001732 if (std == NULL)
1733 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001734 PySys_SetObject("__stdout__", std);
1735 _PySys_SetObjectId(&PyId_stdout, std);
1736 Py_DECREF(std);
1737
1738#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1739 /* Set sys.stderr, replaces the preliminary stderr */
1740 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001741 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001742 config->stdio_encoding,
1743 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001744 if (std == NULL)
1745 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001746
1747 /* Same as hack above, pre-import stderr's codec to avoid recursion
1748 when import.c tries to write to stderr in verbose mode. */
1749 encoding_attr = PyObject_GetAttrString(std, "encoding");
1750 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001751 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001752 if (std_encoding != NULL) {
1753 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1754 Py_XDECREF(codec_info);
1755 }
1756 Py_DECREF(encoding_attr);
1757 }
1758 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1759
1760 if (PySys_SetObject("__stderr__", std) < 0) {
1761 Py_DECREF(std);
1762 goto error;
1763 }
1764 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1765 Py_DECREF(std);
1766 goto error;
1767 }
1768 Py_DECREF(std);
1769#endif
1770
Victor Stinnera7368ac2017-11-15 18:11:45 -08001771 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001772
Victor Stinnera7368ac2017-11-15 18:11:45 -08001773error:
1774 res = _Py_INIT_ERR("can't initialize sys standard streams");
1775
1776done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001777 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001778
Nick Coghland6009512014-11-20 21:39:37 +10001779 Py_XDECREF(bimod);
1780 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001781 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001782}
1783
1784
Victor Stinner10dc4842015-03-24 12:01:30 +01001785static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001786_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001787{
Victor Stinner10dc4842015-03-24 12:01:30 +01001788 fputc('\n', stderr);
1789 fflush(stderr);
1790
1791 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001792 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001793}
Victor Stinner791da1c2016-03-14 16:53:12 +01001794
1795/* Print the current exception (if an exception is set) with its traceback,
1796 or display the current Python stack.
1797
1798 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1799 called on catastrophic cases.
1800
1801 Return 1 if the traceback was displayed, 0 otherwise. */
1802
1803static int
1804_Py_FatalError_PrintExc(int fd)
1805{
1806 PyObject *ferr, *res;
1807 PyObject *exception, *v, *tb;
1808 int has_tb;
1809
Victor Stinner791da1c2016-03-14 16:53:12 +01001810 PyErr_Fetch(&exception, &v, &tb);
1811 if (exception == NULL) {
1812 /* No current exception */
1813 return 0;
1814 }
1815
1816 ferr = _PySys_GetObjectId(&PyId_stderr);
1817 if (ferr == NULL || ferr == Py_None) {
1818 /* sys.stderr is not set yet or set to None,
1819 no need to try to display the exception */
1820 return 0;
1821 }
1822
1823 PyErr_NormalizeException(&exception, &v, &tb);
1824 if (tb == NULL) {
1825 tb = Py_None;
1826 Py_INCREF(tb);
1827 }
1828 PyException_SetTraceback(v, tb);
1829 if (exception == NULL) {
1830 /* PyErr_NormalizeException() failed */
1831 return 0;
1832 }
1833
1834 has_tb = (tb != Py_None);
1835 PyErr_Display(exception, v, tb);
1836 Py_XDECREF(exception);
1837 Py_XDECREF(v);
1838 Py_XDECREF(tb);
1839
1840 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001841 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001842 if (res == NULL)
1843 PyErr_Clear();
1844 else
1845 Py_DECREF(res);
1846
1847 return has_tb;
1848}
1849
Nick Coghland6009512014-11-20 21:39:37 +10001850/* Print fatal error message and abort */
1851
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001852#ifdef MS_WINDOWS
1853static void
1854fatal_output_debug(const char *msg)
1855{
1856 /* buffer of 256 bytes allocated on the stack */
1857 WCHAR buffer[256 / sizeof(WCHAR)];
1858 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1859 size_t msglen;
1860
1861 OutputDebugStringW(L"Fatal Python error: ");
1862
1863 msglen = strlen(msg);
1864 while (msglen) {
1865 size_t i;
1866
1867 if (buflen > msglen) {
1868 buflen = msglen;
1869 }
1870
1871 /* Convert the message to wchar_t. This uses a simple one-to-one
1872 conversion, assuming that the this error message actually uses
1873 ASCII only. If this ceases to be true, we will have to convert. */
1874 for (i=0; i < buflen; ++i) {
1875 buffer[i] = msg[i];
1876 }
1877 buffer[i] = L'\0';
1878 OutputDebugStringW(buffer);
1879
1880 msg += buflen;
1881 msglen -= buflen;
1882 }
1883 OutputDebugStringW(L"\n");
1884}
1885#endif
1886
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001887static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001888fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001889{
1890 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001891 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001892
1893 if (reentrant) {
1894 /* Py_FatalError() caused a second fatal error.
1895 Example: flush_std_files() raises a recursion error. */
1896 goto exit;
1897 }
1898 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001899
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001900 fprintf(stderr, "Fatal Python error: ");
1901 if (prefix) {
1902 fputs(prefix, stderr);
1903 fputs(": ", stderr);
1904 }
1905 if (msg) {
1906 fputs(msg, stderr);
1907 }
1908 else {
1909 fprintf(stderr, "<message not set>");
1910 }
1911 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001912 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001913
Victor Stinner3a228ab2018-11-01 00:26:41 +01001914 /* Check if the current thread has a Python thread state
1915 and holds the GIL */
1916 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
1917 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01001918 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01001919 if (tss_tstate != tstate) {
1920 /* The Python thread does not hold the GIL */
1921 tss_tstate = NULL;
1922 }
1923 }
1924 else {
1925 /* Py_FatalError() has been called from a C thread
1926 which has no Python thread state. */
1927 }
1928 int has_tstate_and_gil = (tss_tstate != NULL);
1929
1930 if (has_tstate_and_gil) {
1931 /* If an exception is set, print the exception with its traceback */
1932 if (!_Py_FatalError_PrintExc(fd)) {
1933 /* No exception is set, or an exception is set without traceback */
1934 _Py_FatalError_DumpTracebacks(fd);
1935 }
1936 }
1937 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01001938 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001939 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001940
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001941 /* The main purpose of faulthandler is to display the traceback.
1942 This function already did its best to display a traceback.
1943 Disable faulthandler to prevent writing a second traceback
1944 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001945 _PyFaulthandler_Fini();
1946
Victor Stinner791da1c2016-03-14 16:53:12 +01001947 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01001948 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001949 /* Flush sys.stdout and sys.stderr */
1950 flush_std_files();
1951 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001952
Nick Coghland6009512014-11-20 21:39:37 +10001953#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001954 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001955#endif /* MS_WINDOWS */
1956
1957exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001958 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01001959#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001960 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10001961#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001962 abort();
1963 }
1964 else {
1965 exit(status);
1966 }
1967}
1968
Victor Stinner19760862017-12-20 01:41:59 +01001969void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001970Py_FatalError(const char *msg)
1971{
1972 fatal_error(NULL, msg, -1);
1973}
1974
Victor Stinner19760862017-12-20 01:41:59 +01001975void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001976_Py_FatalInitError(_PyInitError err)
1977{
1978 /* On "user" error: exit with status 1.
1979 For all other errors, call abort(). */
1980 int status = err.user_err ? 1 : -1;
1981 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10001982}
1983
1984/* Clean up and exit */
1985
Victor Stinnerd7292b52016-06-17 12:29:00 +02001986# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001987
Nick Coghland6009512014-11-20 21:39:37 +10001988/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01001989void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10001990{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001991 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01001992
Antoine Pitroufc5db952017-12-13 02:29:07 +01001993 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01001994 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
1995
1996 is->pyexitfunc = func;
1997 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10001998}
1999
2000static void
Marcel Plch776407f2017-12-20 11:17:58 +01002001call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002002{
Marcel Plch776407f2017-12-20 11:17:58 +01002003 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002004 return;
2005
Marcel Plch776407f2017-12-20 11:17:58 +01002006 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002007 PyErr_Clear();
2008}
2009
2010/* Wait until threading._shutdown completes, provided
2011 the threading module was imported in the first place.
2012 The shutdown routine will wait until all non-daemon
2013 "threading" threads have completed. */
2014static void
2015wait_for_thread_shutdown(void)
2016{
Nick Coghland6009512014-11-20 21:39:37 +10002017 _Py_IDENTIFIER(_shutdown);
2018 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002019 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002020 if (threading == NULL) {
2021 /* threading not imported */
2022 PyErr_Clear();
2023 return;
2024 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002025 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002026 if (result == NULL) {
2027 PyErr_WriteUnraisable(threading);
2028 }
2029 else {
2030 Py_DECREF(result);
2031 }
2032 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002033}
2034
2035#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002036int Py_AtExit(void (*func)(void))
2037{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002038 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002039 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002040 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002041 return 0;
2042}
2043
2044static void
2045call_ll_exitfuncs(void)
2046{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002047 while (_PyRuntime.nexitfuncs > 0)
2048 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002049
2050 fflush(stdout);
2051 fflush(stderr);
2052}
2053
Victor Stinnercfc88312018-08-01 16:41:25 +02002054void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002055Py_Exit(int sts)
2056{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002057 if (Py_FinalizeEx() < 0) {
2058 sts = 120;
2059 }
Nick Coghland6009512014-11-20 21:39:37 +10002060
2061 exit(sts);
2062}
2063
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002064static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002065initsigs(void)
2066{
2067#ifdef SIGPIPE
2068 PyOS_setsig(SIGPIPE, SIG_IGN);
2069#endif
2070#ifdef SIGXFZ
2071 PyOS_setsig(SIGXFZ, SIG_IGN);
2072#endif
2073#ifdef SIGXFSZ
2074 PyOS_setsig(SIGXFSZ, SIG_IGN);
2075#endif
2076 PyOS_InitInterrupts(); /* May imply initsignal() */
2077 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002078 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002079 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002080 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002081}
2082
2083
2084/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2085 *
2086 * All of the code in this function must only use async-signal-safe functions,
2087 * listed at `man 7 signal` or
2088 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2089 */
2090void
2091_Py_RestoreSignals(void)
2092{
2093#ifdef SIGPIPE
2094 PyOS_setsig(SIGPIPE, SIG_DFL);
2095#endif
2096#ifdef SIGXFZ
2097 PyOS_setsig(SIGXFZ, SIG_DFL);
2098#endif
2099#ifdef SIGXFSZ
2100 PyOS_setsig(SIGXFSZ, SIG_DFL);
2101#endif
2102}
2103
2104
2105/*
2106 * The file descriptor fd is considered ``interactive'' if either
2107 * a) isatty(fd) is TRUE, or
2108 * b) the -i flag was given, and the filename associated with
2109 * the descriptor is NULL or "<stdin>" or "???".
2110 */
2111int
2112Py_FdIsInteractive(FILE *fp, const char *filename)
2113{
2114 if (isatty((int)fileno(fp)))
2115 return 1;
2116 if (!Py_InteractiveFlag)
2117 return 0;
2118 return (filename == NULL) ||
2119 (strcmp(filename, "<stdin>") == 0) ||
2120 (strcmp(filename, "???") == 0);
2121}
2122
2123
Nick Coghland6009512014-11-20 21:39:37 +10002124/* Wrappers around sigaction() or signal(). */
2125
2126PyOS_sighandler_t
2127PyOS_getsig(int sig)
2128{
2129#ifdef HAVE_SIGACTION
2130 struct sigaction context;
2131 if (sigaction(sig, NULL, &context) == -1)
2132 return SIG_ERR;
2133 return context.sa_handler;
2134#else
2135 PyOS_sighandler_t handler;
2136/* Special signal handling for the secure CRT in Visual Studio 2005 */
2137#if defined(_MSC_VER) && _MSC_VER >= 1400
2138 switch (sig) {
2139 /* Only these signals are valid */
2140 case SIGINT:
2141 case SIGILL:
2142 case SIGFPE:
2143 case SIGSEGV:
2144 case SIGTERM:
2145 case SIGBREAK:
2146 case SIGABRT:
2147 break;
2148 /* Don't call signal() with other values or it will assert */
2149 default:
2150 return SIG_ERR;
2151 }
2152#endif /* _MSC_VER && _MSC_VER >= 1400 */
2153 handler = signal(sig, SIG_IGN);
2154 if (handler != SIG_ERR)
2155 signal(sig, handler);
2156 return handler;
2157#endif
2158}
2159
2160/*
2161 * All of the code in this function must only use async-signal-safe functions,
2162 * listed at `man 7 signal` or
2163 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2164 */
2165PyOS_sighandler_t
2166PyOS_setsig(int sig, PyOS_sighandler_t handler)
2167{
2168#ifdef HAVE_SIGACTION
2169 /* Some code in Modules/signalmodule.c depends on sigaction() being
2170 * used here if HAVE_SIGACTION is defined. Fix that if this code
2171 * changes to invalidate that assumption.
2172 */
2173 struct sigaction context, ocontext;
2174 context.sa_handler = handler;
2175 sigemptyset(&context.sa_mask);
2176 context.sa_flags = 0;
2177 if (sigaction(sig, &context, &ocontext) == -1)
2178 return SIG_ERR;
2179 return ocontext.sa_handler;
2180#else
2181 PyOS_sighandler_t oldhandler;
2182 oldhandler = signal(sig, handler);
2183#ifdef HAVE_SIGINTERRUPT
2184 siginterrupt(sig, 1);
2185#endif
2186 return oldhandler;
2187#endif
2188}
2189
2190#ifdef __cplusplus
2191}
2192#endif