blob: 8c77859209ab2ca2ea618fc57ff0ee5544f83e87 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
Yury Selivanovf23746a2018-01-22 19:11:18 -05007#include "internal/context.h"
8#include "internal/hamt.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06009#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100010#include "grammar.h"
11#include "node.h"
12#include "token.h"
13#include "parsetok.h"
14#include "errcode.h"
15#include "code.h"
16#include "symtable.h"
17#include "ast.h"
18#include "marshal.h"
19#include "osdefs.h"
20#include <locale.h>
21
22#ifdef HAVE_SIGNAL_H
23#include <signal.h>
24#endif
25
26#ifdef MS_WINDOWS
27#include "malloc.h" /* for alloca */
28#endif
29
30#ifdef HAVE_LANGINFO_H
31#include <langinfo.h>
32#endif
33
34#ifdef MS_WINDOWS
35#undef BYTE
36#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070037
38extern PyTypeObject PyWindowsConsoleIO_Type;
39#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100040#endif
41
42_Py_IDENTIFIER(flush);
43_Py_IDENTIFIER(name);
44_Py_IDENTIFIER(stdin);
45_Py_IDENTIFIER(stdout);
46_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060047_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100048
49#ifdef __cplusplus
50extern "C" {
51#endif
52
Nick Coghland6009512014-11-20 21:39:37 +100053extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056static _PyInitError add_main_module(PyInterpreterState *interp);
57static _PyInitError initfsencoding(PyInterpreterState *interp);
58static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010059static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010061static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100062static void wait_for_thread_shutdown(void);
63static void call_ll_exitfuncs(void);
64extern int _PyUnicode_Init(void);
65extern int _PyStructSequence_Init(void);
66extern void _PyUnicode_Fini(void);
67extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080069extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100070extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080072extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100073extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070074extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100075
Nick Coghland6009512014-11-20 21:39:37 +100076extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082_PyRuntime_Initialize(void)
83{
84 /* XXX We only initialize once in the process, which aligns with
85 the static initialization of the former globals now found in
86 _PyRuntime. However, _PyRuntime *should* be initialized with
87 every Py_Initialize() call, but doing so breaks the runtime.
88 This is because the runtime state is not properly finalized
89 currently. */
90 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091 if (initialized) {
92 return _Py_INIT_OK();
93 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095
96 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99void
100_PyRuntime_Finalize(void)
101{
102 _PyRuntimeState_Fini(&_PyRuntime);
103}
104
105int
106_Py_IsFinalizing(void)
107{
108 return _PyRuntime.finalizing != NULL;
109}
110
Nick Coghland6009512014-11-20 21:39:37 +1000111/* Hack to force loading of object files */
112int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
113 PyOS_mystrnicmp; /* Python/pystrcmp.o */
114
115/* PyModule_GetWarningsModule is no longer necessary as of 2.6
116since _warnings is builtin. This API should not be used. */
117PyObject *
118PyModule_GetWarningsModule(void)
119{
120 return PyImport_ImportModule("warnings");
121}
122
Eric Snowc7ec9982017-05-23 23:00:52 -0700123
Eric Snow1abcf672017-05-23 21:46:51 -0700124/* APIs to access the initialization flags
125 *
126 * Can be called prior to Py_Initialize.
127 */
Nick Coghland6009512014-11-20 21:39:37 +1000128
Eric Snow1abcf672017-05-23 21:46:51 -0700129int
130_Py_IsCoreInitialized(void)
131{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600132 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700133}
Nick Coghland6009512014-11-20 21:39:37 +1000134
135int
136Py_IsInitialized(void)
137{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600138 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000139}
140
Nick Coghlan6ea41862017-06-11 13:16:15 +1000141
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000142/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
143 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000144 initializations fail, a fatal error is issued and the function does
145 not return. On return, the first thread and interpreter state have
146 been created.
147
148 Locking: you must hold the interpreter lock while calling this.
149 (If the lock has not yet been initialized, that's equivalent to
150 having the lock, but you cannot use multiple threads.)
151
152*/
153
Nick Coghland6009512014-11-20 21:39:37 +1000154static char*
155get_codec_name(const char *encoding)
156{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200157 const char *name_utf8;
158 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000159 PyObject *codec, *name = NULL;
160
161 codec = _PyCodec_Lookup(encoding);
162 if (!codec)
163 goto error;
164
165 name = _PyObject_GetAttrId(codec, &PyId_name);
166 Py_CLEAR(codec);
167 if (!name)
168 goto error;
169
Serhiy Storchaka06515832016-11-20 09:13:07 +0200170 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000171 if (name_utf8 == NULL)
172 goto error;
173 name_str = _PyMem_RawStrdup(name_utf8);
174 Py_DECREF(name);
175 if (name_str == NULL) {
176 PyErr_NoMemory();
177 return NULL;
178 }
179 return name_str;
180
181error:
182 Py_XDECREF(codec);
183 Py_XDECREF(name);
184 return NULL;
185}
186
Victor Stinner9e4994d2018-08-28 23:26:33 +0200187static _PyInitError
188get_locale_encoding(char **locale_encoding)
Nick Coghland6009512014-11-20 21:39:37 +1000189{
Victor Stinner9e4994d2018-08-28 23:26:33 +0200190#ifdef MS_WINDOWS
191 char encoding[20];
192 PyOS_snprintf(encoding, sizeof(encoding), "cp%d", GetACP());
Stefan Krah144da4e2016-04-26 01:56:50 +0200193#elif defined(__ANDROID__)
Victor Stinner9e4994d2018-08-28 23:26:33 +0200194 const char *encoding = "UTF-8";
Nick Coghland6009512014-11-20 21:39:37 +1000195#else
Victor Stinner9e4994d2018-08-28 23:26:33 +0200196 const char *encoding = nl_langinfo(CODESET);
197 if (!encoding || encoding[0] == '\0') {
198 return _Py_INIT_USER_ERR("failed to get the locale encoding: "
199 "nl_langinfo(CODESET) failed");
200 }
Nick Coghland6009512014-11-20 21:39:37 +1000201#endif
Victor Stinner9e4994d2018-08-28 23:26:33 +0200202 *locale_encoding = _PyMem_RawStrdup(encoding);
203 if (*locale_encoding == NULL) {
204 return _Py_INIT_NO_MEMORY();
205 }
206 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000207}
208
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800209static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700210initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000211{
212 PyObject *importlib;
213 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000214 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800215 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000216
217 /* Import _importlib through its frozen version, _frozen_importlib. */
218 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800219 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000220 }
221 else if (Py_VerboseFlag) {
222 PySys_FormatStderr("import _frozen_importlib # frozen\n");
223 }
224 importlib = PyImport_AddModule("_frozen_importlib");
225 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800226 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000227 }
228 interp->importlib = importlib;
229 Py_INCREF(interp->importlib);
230
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300231 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
232 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800233 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300234 Py_INCREF(interp->import_func);
235
Victor Stinnercd6e6942015-09-18 09:11:57 +0200236 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800237 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000238 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800239 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000240 }
241 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200242 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000243 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600244 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800245 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000246 }
247
Victor Stinnercd6e6942015-09-18 09:11:57 +0200248 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000249 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
250 if (value == NULL) {
251 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800252 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000253 }
254 Py_DECREF(value);
255 Py_DECREF(impmod);
256
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800257 err = _PyImportZip_Init();
258 if (_Py_INIT_FAILED(err)) {
259 return err;
260 }
261
262 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000263}
264
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800265static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700266initexternalimport(PyInterpreterState *interp)
267{
268 PyObject *value;
269 value = PyObject_CallMethod(interp->importlib,
270 "_install_external_importers", "");
271 if (value == NULL) {
272 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800273 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700274 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200275 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800276 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700277}
Nick Coghland6009512014-11-20 21:39:37 +1000278
Nick Coghlan6ea41862017-06-11 13:16:15 +1000279/* Helper functions to better handle the legacy C locale
280 *
281 * The legacy C locale assumes ASCII as the default text encoding, which
282 * causes problems not only for the CPython runtime, but also other
283 * components like GNU readline.
284 *
285 * Accordingly, when the CLI detects it, it attempts to coerce it to a
286 * more capable UTF-8 based alternative as follows:
287 *
288 * if (_Py_LegacyLocaleDetected()) {
289 * _Py_CoerceLegacyLocale();
290 * }
291 *
292 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
293 *
294 * Locale coercion also impacts the default error handler for the standard
295 * streams: while the usual default is "strict", the default for the legacy
296 * C locale and for any of the coercion target locales is "surrogateescape".
297 */
298
299int
300_Py_LegacyLocaleDetected(void)
301{
302#ifndef MS_WINDOWS
303 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000304 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
305 * the POSIX locale as a simple alias for the C locale, so
306 * we may also want to check for that explicitly.
307 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000308 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
309 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
310#else
311 /* Windows uses code pages instead of locales, so no locale is legacy */
312 return 0;
313#endif
314}
315
Nick Coghlaneb817952017-06-18 12:29:42 +1000316static const char *_C_LOCALE_WARNING =
317 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
318 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
319 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
320 "locales is recommended.\n";
321
Nick Coghlaneb817952017-06-18 12:29:42 +1000322static void
Victor Stinner94540602017-12-16 04:54:22 +0100323_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000324{
Victor Stinner94540602017-12-16 04:54:22 +0100325 if (core_config->coerce_c_locale_warn) {
Nick Coghlaneb817952017-06-18 12:29:42 +1000326 if (_Py_LegacyLocaleDetected()) {
327 fprintf(stderr, "%s", _C_LOCALE_WARNING);
328 }
329 }
330}
331
Nick Coghlan6ea41862017-06-11 13:16:15 +1000332typedef struct _CandidateLocale {
333 const char *locale_name; /* The locale to try as a coercion target */
334} _LocaleCoercionTarget;
335
336static _LocaleCoercionTarget _TARGET_LOCALES[] = {
337 {"C.UTF-8"},
338 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000339 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000340 {NULL}
341};
342
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200343static const char *
Victor Stinner9e4994d2018-08-28 23:26:33 +0200344get_stdio_errors(void)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000345{
346 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
347 if (ctype_loc != NULL) {
348 /* "surrogateescape" is the default in the legacy C locale */
349 if (strcmp(ctype_loc, "C") == 0) {
350 return "surrogateescape";
351 }
352
353#ifdef PY_COERCE_C_LOCALE
354 /* "surrogateescape" is the default in locale coercion target locales */
355 const _LocaleCoercionTarget *target = NULL;
356 for (target = _TARGET_LOCALES; target->locale_name; target++) {
357 if (strcmp(ctype_loc, target->locale_name) == 0) {
358 return "surrogateescape";
359 }
360 }
361#endif
Victor Stinner124b9eb2018-08-29 01:29:06 +0200362 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000363
Victor Stinner124b9eb2018-08-29 01:29:06 +0200364 return "strict";
Nick Coghlan6ea41862017-06-11 13:16:15 +1000365}
366
367#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100368static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000369 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
370 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
371
372static void
Victor Stinner94540602017-12-16 04:54:22 +0100373_coerce_default_locale_settings(const _PyCoreConfig *config, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000374{
375 const char *newloc = target->locale_name;
376
377 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100378 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000379
380 /* Set the relevant locale environment variable */
381 if (setenv("LC_CTYPE", newloc, 1)) {
382 fprintf(stderr,
383 "Error setting LC_CTYPE, skipping C locale coercion\n");
384 return;
385 }
Victor Stinner94540602017-12-16 04:54:22 +0100386 if (config->coerce_c_locale_warn) {
387 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000388 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000389
390 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100391 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000392}
393#endif
394
395void
Victor Stinner94540602017-12-16 04:54:22 +0100396_Py_CoerceLegacyLocale(const _PyCoreConfig *config)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000397{
398#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100399 const char *locale_override = getenv("LC_ALL");
400 if (locale_override == NULL || *locale_override == '\0') {
401 /* LC_ALL is also not set (or is set to an empty string) */
402 const _LocaleCoercionTarget *target = NULL;
403 for (target = _TARGET_LOCALES; target->locale_name; target++) {
404 const char *new_locale = setlocale(LC_CTYPE,
405 target->locale_name);
406 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100407#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100408defined(HAVE_LANGINFO_H) && defined(CODESET)
409 /* Also ensure that nl_langinfo works in this locale */
410 char *codeset = nl_langinfo(CODESET);
411 if (!codeset || *codeset == '\0') {
412 /* CODESET is not set or empty, so skip coercion */
413 new_locale = NULL;
414 _Py_SetLocaleFromEnv(LC_CTYPE);
415 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000416 }
Victor Stinner94540602017-12-16 04:54:22 +0100417#endif
418 /* Successfully configured locale, so make it the default */
419 _coerce_default_locale_settings(config, target);
420 return;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000421 }
422 }
423 }
424 /* No C locale warning here, as Py_Initialize will emit one later */
425#endif
426}
427
xdegaye1588be62017-11-12 12:45:59 +0100428/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
429 * isolate the idiosyncrasies of different libc implementations. It reads the
430 * appropriate environment variable and uses its value to select the locale for
431 * 'category'. */
432char *
433_Py_SetLocaleFromEnv(int category)
434{
435#ifdef __ANDROID__
436 const char *locale;
437 const char **pvar;
438#ifdef PY_COERCE_C_LOCALE
439 const char *coerce_c_locale;
440#endif
441 const char *utf8_locale = "C.UTF-8";
442 const char *env_var_set[] = {
443 "LC_ALL",
444 "LC_CTYPE",
445 "LANG",
446 NULL,
447 };
448
449 /* Android setlocale(category, "") doesn't check the environment variables
450 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
451 * check the environment variables listed in env_var_set. */
452 for (pvar=env_var_set; *pvar; pvar++) {
453 locale = getenv(*pvar);
454 if (locale != NULL && *locale != '\0') {
455 if (strcmp(locale, utf8_locale) == 0 ||
456 strcmp(locale, "en_US.UTF-8") == 0) {
457 return setlocale(category, utf8_locale);
458 }
459 return setlocale(category, "C");
460 }
461 }
462
463 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
464 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
465 * Quote from POSIX section "8.2 Internationalization Variables":
466 * "4. If the LANG environment variable is not set or is set to the empty
467 * string, the implementation-defined default locale shall be used." */
468
469#ifdef PY_COERCE_C_LOCALE
470 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
471 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
472 /* Some other ported code may check the environment variables (e.g. in
473 * extension modules), so we make sure that they match the locale
474 * configuration */
475 if (setenv("LC_CTYPE", utf8_locale, 1)) {
476 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
477 "environment variable to %s\n", utf8_locale);
478 }
479 }
480#endif
481 return setlocale(category, utf8_locale);
482#else /* __ANDROID__ */
483 return setlocale(category, "");
484#endif /* __ANDROID__ */
485}
486
Nick Coghlan6ea41862017-06-11 13:16:15 +1000487
Eric Snow1abcf672017-05-23 21:46:51 -0700488/* Global initializations. Can be undone by Py_Finalize(). Don't
489 call this twice without an intervening Py_Finalize() call.
490
Victor Stinner1dc6e392018-07-25 02:49:17 +0200491 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700492 must have a corresponding call to Py_Finalize.
493
494 Locking: you must hold the interpreter lock while calling these APIs.
495 (If the lock has not yet been initialized, that's equivalent to
496 having the lock, but you cannot use multiple threads.)
497
498*/
499
Victor Stinner1dc6e392018-07-25 02:49:17 +0200500static _PyInitError
501_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
502 const _PyCoreConfig *core_config)
503{
504 if (core_config->allocator != NULL) {
505 const char *allocator = _PyMem_GetAllocatorsName();
506 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
507 return _Py_INIT_USER_ERR("cannot modify memory allocator "
508 "after first Py_Initialize()");
509 }
510 }
511
512 _PyCoreConfig_SetGlobalConfig(core_config);
513
514 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
515 return _Py_INIT_ERR("failed to copy core config");
516 }
517 core_config = &interp->core_config;
518
519 if (core_config->_install_importlib) {
520 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
521 if (_Py_INIT_FAILED(err)) {
522 return err;
523 }
524 }
525 return _Py_INIT_OK();
526}
527
528
Eric Snow1abcf672017-05-23 21:46:51 -0700529/* Begin interpreter initialization
530 *
531 * On return, the first thread and interpreter state have been created,
532 * but the compiler, signal handling, multithreading and
533 * multiple interpreter support, and codec infrastructure are not yet
534 * available.
535 *
536 * The import system will support builtin and frozen modules only.
537 * The only supported io is writing to sys.stderr
538 *
539 * If any operation invoked by this function fails, a fatal error is
540 * issued and the function does not return.
541 *
542 * Any code invoked from this function should *not* assume it has access
543 * to the Python C API (unless the API is explicitly listed as being
544 * safe to call without calling Py_Initialize first)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200545 *
546 * The caller is responsible to call _PyCoreConfig_Read().
Eric Snow1abcf672017-05-23 21:46:51 -0700547 */
548
Victor Stinner1dc6e392018-07-25 02:49:17 +0200549static _PyInitError
550_Py_InitializeCore_impl(PyInterpreterState **interp_p,
551 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000552{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200553 PyInterpreterState *interp;
554 _PyInitError err;
555
556 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
557 Py_Initialize() ignores the new configuration. */
558 if (_PyRuntime.core_initialized) {
559 PyThreadState *tstate = PyThreadState_GET();
560 if (!tstate) {
561 return _Py_INIT_ERR("failed to read thread state");
562 }
563
564 interp = tstate->interp;
565 if (interp == NULL) {
566 return _Py_INIT_ERR("can't make main interpreter");
567 }
568 *interp_p = interp;
569
570 return _Py_Initialize_ReconfigureCore(interp, core_config);
571 }
572
573 if (_PyRuntime.initialized) {
574 return _Py_INIT_ERR("main interpreter already initialized");
575 }
Victor Stinnerda273412017-12-15 01:46:02 +0100576
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200577 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000578
Victor Stinner1dc6e392018-07-25 02:49:17 +0200579 err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800580 if (_Py_INIT_FAILED(err)) {
581 return err;
582 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600583
Victor Stinner31e99082017-12-20 23:41:38 +0100584 if (core_config->allocator != NULL) {
585 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
586 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
587 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800588 }
589
Eric Snow1abcf672017-05-23 21:46:51 -0700590 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
591 * threads behave a little more gracefully at interpreter shutdown.
592 * We clobber it here so the new interpreter can start with a clean
593 * slate.
594 *
595 * However, this may still lead to misbehaviour if there are daemon
596 * threads still hanging around from a previous Py_Initialize/Finalize
597 * pair :(
598 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600599 _PyRuntime.finalizing = NULL;
600
Nick Coghlan6ea41862017-06-11 13:16:15 +1000601#ifndef MS_WINDOWS
Victor Stinner94540602017-12-16 04:54:22 +0100602 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000603#endif
Nick Coghland6009512014-11-20 21:39:37 +1000604
Victor Stinnerda273412017-12-15 01:46:02 +0100605 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800606 if (_Py_INIT_FAILED(err)) {
607 return err;
608 }
609
Victor Stinnera7368ac2017-11-15 18:11:45 -0800610 err = _PyInterpreterState_Enable(&_PyRuntime);
611 if (_Py_INIT_FAILED(err)) {
612 return err;
613 }
614
Victor Stinner1dc6e392018-07-25 02:49:17 +0200615 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100616 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800617 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100618 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200619 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100620
621 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
622 return _Py_INIT_ERR("failed to copy core config");
623 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200624 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000625
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200626 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000627 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800628 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000629 (void) PyThreadState_Swap(tstate);
630
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000631 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000632 destroying the GIL might fail when it is being referenced from
633 another running thread (see issue #9901).
634 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000635 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000636 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100637
Nick Coghland6009512014-11-20 21:39:37 +1000638 /* Auto-thread-state API */
639 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000640
Victor Stinner2914bb32018-01-29 11:57:45 +0100641 /* Create the GIL */
642 PyEval_InitThreads();
643
Nick Coghland6009512014-11-20 21:39:37 +1000644 _Py_ReadyTypes();
645
Nick Coghland6009512014-11-20 21:39:37 +1000646 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800647 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000648
649 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800650 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000651
652 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800653 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000654
Eric Snowd393c1b2017-09-14 12:18:12 -0600655 PyObject *modules = PyDict_New();
656 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800657 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600658 interp->modules = modules;
659
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200660 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800661 err = _PySys_BeginInit(&sysmod);
662 if (_Py_INIT_FAILED(err)) {
663 return err;
664 }
665
Eric Snowd393c1b2017-09-14 12:18:12 -0600666 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800667 if (interp->sysdict == NULL) {
668 return _Py_INIT_ERR("can't initialize sys dict");
669 }
670
Eric Snowd393c1b2017-09-14 12:18:12 -0600671 Py_INCREF(interp->sysdict);
672 PyDict_SetItemString(interp->sysdict, "modules", modules);
673 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000674
675 /* Init Unicode implementation; relies on the codec registry */
676 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800677 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700678
Nick Coghland6009512014-11-20 21:39:37 +1000679 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800680 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000681
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200682 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000683 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800684 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600685 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000686 interp->builtins = PyModule_GetDict(bimod);
687 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800688 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000689 Py_INCREF(interp->builtins);
690
691 /* initialize builtin exceptions */
692 _PyExc_Init(bimod);
693
Nick Coghland6009512014-11-20 21:39:37 +1000694 /* Set up a preliminary stderr printer until we have enough
695 infrastructure for the io module in place. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200696 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000697 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800698 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000699 _PySys_SetObjectId(&PyId_stderr, pstderr);
700 PySys_SetObject("__stderr__", pstderr);
701 Py_DECREF(pstderr);
702
Victor Stinner672b6ba2017-12-06 17:25:50 +0100703 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800704 if (_Py_INIT_FAILED(err)) {
705 return err;
706 }
Nick Coghland6009512014-11-20 21:39:37 +1000707
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800708 err = _PyImportHooks_Init();
709 if (_Py_INIT_FAILED(err)) {
710 return err;
711 }
Nick Coghland6009512014-11-20 21:39:37 +1000712
713 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100714 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100715 return _Py_INIT_ERR("can't initialize warnings");
716 }
Nick Coghland6009512014-11-20 21:39:37 +1000717
Yury Selivanovf23746a2018-01-22 19:11:18 -0500718 if (!_PyContext_Init())
719 return _Py_INIT_ERR("can't init context");
720
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200721 if (core_config->_install_importlib) {
Victor Stinnerb1147e42018-07-21 02:06:16 +0200722 err = _PyCoreConfig_SetPathConfig(core_config);
723 if (_Py_INIT_FAILED(err)) {
724 return err;
725 }
726 }
727
Eric Snow1abcf672017-05-23 21:46:51 -0700728 /* This call sets up builtin and frozen import support */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200729 if (core_config->_install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800730 err = initimport(interp, sysmod);
731 if (_Py_INIT_FAILED(err)) {
732 return err;
733 }
Eric Snow1abcf672017-05-23 21:46:51 -0700734 }
735
736 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600737 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800738 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700739}
740
Victor Stinner1dc6e392018-07-25 02:49:17 +0200741_PyInitError
742_Py_InitializeCore(PyInterpreterState **interp_p,
743 const _PyCoreConfig *src_config)
744{
745 assert(src_config != NULL);
746
Victor Stinner1dc6e392018-07-25 02:49:17 +0200747 PyMemAllocatorEx old_alloc;
748 _PyInitError err;
749
750 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
751 (and the input configuration is read only). */
752 _PyCoreConfig config = _PyCoreConfig_INIT;
753
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200754#ifndef MS_WINDOWS
755 /* Set up the LC_CTYPE locale, so we can obtain the locale's charset
756 without having to switch locales. */
757 _Py_SetLocaleFromEnv(LC_CTYPE);
758#endif
759
Victor Stinner1dc6e392018-07-25 02:49:17 +0200760 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
761 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
762 err = _PyCoreConfig_Read(&config);
763 }
764 else {
765 err = _Py_INIT_ERR("failed to copy core config");
766 }
767 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
768
769 if (_Py_INIT_FAILED(err)) {
770 goto done;
771 }
772
773 err = _Py_InitializeCore_impl(interp_p, &config);
774
775done:
776 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
777 _PyCoreConfig_Clear(&config);
778 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
779
780 return err;
781}
782
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200783/* Py_Initialize() has already been called: update the main interpreter
784 configuration. Example of bpo-34008: Py_Main() called after
785 Py_Initialize(). */
786static _PyInitError
787_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
788 const _PyMainInterpreterConfig *config)
789{
790 if (config->argv != NULL) {
791 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
792 if (res < 0) {
793 return _Py_INIT_ERR("fail to set sys.argv");
794 }
795 }
796 return _Py_INIT_OK();
797}
798
Eric Snowc7ec9982017-05-23 23:00:52 -0700799/* Update interpreter state based on supplied configuration settings
800 *
801 * After calling this function, most of the restrictions on the interpreter
802 * are lifted. The only remaining incomplete settings are those related
803 * to the main module (sys.argv[0], __main__ metadata)
804 *
805 * Calling this when the interpreter is not initializing, is already
806 * initialized or without a valid current thread state is a fatal error.
807 * Other errors should be reported as normal Python exceptions with a
808 * non-zero return code.
809 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800810_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200811_Py_InitializeMainInterpreter(PyInterpreterState *interp,
812 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700813{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600814 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800815 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700816 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700817
Victor Stinner1dc6e392018-07-25 02:49:17 +0200818 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100819 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
820 return _Py_INIT_ERR("failed to copy main interpreter config");
821 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200822 config = &interp->config;
823 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700824
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200825 if (_PyRuntime.initialized) {
826 return _Py_ReconfigureMainInterpreter(interp, config);
827 }
828
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200829 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700830 /* Special mode for freeze_importlib: run with no import system
831 *
832 * This means anything which needs support from extension modules
833 * or pure Python code in the standard library won't work.
834 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600835 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800836 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700837 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100838
Victor Stinner33c377e2017-12-05 15:12:41 +0100839 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800840 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100841 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200842
Victor Stinner41264f12017-12-15 02:05:29 +0100843 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800844 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100845 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800846
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200847 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800848 if (_Py_INIT_FAILED(err)) {
849 return err;
850 }
Nick Coghland6009512014-11-20 21:39:37 +1000851
852 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200853 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800854 if (_Py_INIT_FAILED(err)) {
855 return err;
856 }
Nick Coghland6009512014-11-20 21:39:37 +1000857
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800858 err = initfsencoding(interp);
859 if (_Py_INIT_FAILED(err)) {
860 return err;
861 }
Nick Coghland6009512014-11-20 21:39:37 +1000862
Victor Stinner1f151112017-11-23 10:43:14 +0100863 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800864 err = initsigs(); /* Signal handling stuff, including initintr() */
865 if (_Py_INIT_FAILED(err)) {
866 return err;
867 }
868 }
Nick Coghland6009512014-11-20 21:39:37 +1000869
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200870 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800871 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200872 }
Nick Coghland6009512014-11-20 21:39:37 +1000873
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800874 err = add_main_module(interp);
875 if (_Py_INIT_FAILED(err)) {
876 return err;
877 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800878
Victor Stinner91106cd2017-12-13 12:29:09 +0100879 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800880 if (_Py_INIT_FAILED(err)) {
881 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800882 }
Nick Coghland6009512014-11-20 21:39:37 +1000883
884 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100885 if (interp->config.warnoptions != NULL &&
886 PyList_Size(interp->config.warnoptions) > 0)
887 {
Nick Coghland6009512014-11-20 21:39:37 +1000888 PyObject *warnings_module = PyImport_ImportModule("warnings");
889 if (warnings_module == NULL) {
890 fprintf(stderr, "'import warnings' failed; traceback:\n");
891 PyErr_Print();
892 }
893 Py_XDECREF(warnings_module);
894 }
895
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600896 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700897
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200898 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800899 err = initsite(); /* Module site */
900 if (_Py_INIT_FAILED(err)) {
901 return err;
902 }
903 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800904 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000905}
906
Eric Snowc7ec9982017-05-23 23:00:52 -0700907#undef _INIT_DEBUG_PRINT
908
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800909_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200910_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700911{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200912 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200914 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800915 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200916 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800917 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200918 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100919
Victor Stinner9cfc0022017-12-20 19:36:46 +0100920 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200921 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100922 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200923 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800924 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100925 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800926 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200927 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800928 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200929 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700930}
931
932
933void
Nick Coghland6009512014-11-20 21:39:37 +1000934Py_InitializeEx(int install_sigs)
935{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200936 if (_PyRuntime.initialized) {
937 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
938 return;
939 }
940
941 _PyInitError err;
942 _PyCoreConfig config = _PyCoreConfig_INIT;
943 config.install_signal_handlers = install_sigs;
944
945 err = _Py_InitializeFromConfig(&config);
946 _PyCoreConfig_Clear(&config);
947
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800948 if (_Py_INIT_FAILED(err)) {
949 _Py_FatalInitError(err);
950 }
Nick Coghland6009512014-11-20 21:39:37 +1000951}
952
953void
954Py_Initialize(void)
955{
956 Py_InitializeEx(1);
957}
958
959
960#ifdef COUNT_ALLOCS
961extern void dump_counts(FILE*);
962#endif
963
964/* Flush stdout and stderr */
965
966static int
967file_is_closed(PyObject *fobj)
968{
969 int r;
970 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
971 if (tmp == NULL) {
972 PyErr_Clear();
973 return 0;
974 }
975 r = PyObject_IsTrue(tmp);
976 Py_DECREF(tmp);
977 if (r < 0)
978 PyErr_Clear();
979 return r > 0;
980}
981
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000982static int
Nick Coghland6009512014-11-20 21:39:37 +1000983flush_std_files(void)
984{
985 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
986 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
987 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000988 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000989
990 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700991 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000992 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000993 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000994 status = -1;
995 }
Nick Coghland6009512014-11-20 21:39:37 +1000996 else
997 Py_DECREF(tmp);
998 }
999
1000 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001001 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001002 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001003 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001004 status = -1;
1005 }
Nick Coghland6009512014-11-20 21:39:37 +10001006 else
1007 Py_DECREF(tmp);
1008 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001009
1010 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001011}
1012
1013/* Undo the effect of Py_Initialize().
1014
1015 Beware: if multiple interpreter and/or thread states exist, these
1016 are not wiped out; only the current thread and interpreter state
1017 are deleted. But since everything else is deleted, those other
1018 interpreter and thread states should no longer be used.
1019
1020 (XXX We should do better, e.g. wipe out all interpreters and
1021 threads.)
1022
1023 Locking: as above.
1024
1025*/
1026
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001027int
1028Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001029{
1030 PyInterpreterState *interp;
1031 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001032 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001033
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001034 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001035 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001036
1037 wait_for_thread_shutdown();
1038
Marcel Plch776407f2017-12-20 11:17:58 +01001039 /* Get current thread state and interpreter pointer */
1040 tstate = PyThreadState_GET();
1041 interp = tstate->interp;
1042
Nick Coghland6009512014-11-20 21:39:37 +10001043 /* The interpreter is still entirely intact at this point, and the
1044 * exit funcs may be relying on that. In particular, if some thread
1045 * or exit func is still waiting to do an import, the import machinery
1046 * expects Py_IsInitialized() to return true. So don't say the
1047 * interpreter is uninitialized until after the exit funcs have run.
1048 * Note that Threading.py uses an exit func to do a join on all the
1049 * threads created thru it, so this also protects pending imports in
1050 * the threads created via Threading.
1051 */
Nick Coghland6009512014-11-20 21:39:37 +10001052
Marcel Plch776407f2017-12-20 11:17:58 +01001053 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001054
Victor Stinnerda273412017-12-15 01:46:02 +01001055 /* Copy the core config, PyInterpreterState_Delete() free
1056 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001057#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001058 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001059#endif
1060#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001061 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001062#endif
1063#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001064 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001065#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001066
Nick Coghland6009512014-11-20 21:39:37 +10001067 /* Remaining threads (e.g. daemon threads) will automatically exit
1068 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001069 _PyRuntime.finalizing = tstate;
1070 _PyRuntime.initialized = 0;
1071 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001072
Victor Stinnere0deff32015-03-24 13:46:18 +01001073 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001074 if (flush_std_files() < 0) {
1075 status = -1;
1076 }
Nick Coghland6009512014-11-20 21:39:37 +10001077
1078 /* Disable signal handling */
1079 PyOS_FiniInterrupts();
1080
1081 /* Collect garbage. This may call finalizers; it's nice to call these
1082 * before all modules are destroyed.
1083 * XXX If a __del__ or weakref callback is triggered here, and tries to
1084 * XXX import a module, bad things can happen, because Python no
1085 * XXX longer believes it's initialized.
1086 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1087 * XXX is easy to provoke that way. I've also seen, e.g.,
1088 * XXX Exception exceptions.ImportError: 'No module named sha'
1089 * XXX in <function callback at 0x008F5718> ignored
1090 * XXX but I'm unclear on exactly how that one happens. In any case,
1091 * XXX I haven't seen a real-life report of either of these.
1092 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001093 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001094#ifdef COUNT_ALLOCS
1095 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1096 each collection might release some types from the type
1097 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001098 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001099 /* nothing */;
1100#endif
Eric Snowdae02762017-09-14 00:35:58 -07001101
Nick Coghland6009512014-11-20 21:39:37 +10001102 /* Destroy all modules */
1103 PyImport_Cleanup();
1104
Victor Stinnere0deff32015-03-24 13:46:18 +01001105 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001106 if (flush_std_files() < 0) {
1107 status = -1;
1108 }
Nick Coghland6009512014-11-20 21:39:37 +10001109
1110 /* Collect final garbage. This disposes of cycles created by
1111 * class definitions, for example.
1112 * XXX This is disabled because it caused too many problems. If
1113 * XXX a __del__ or weakref callback triggers here, Python code has
1114 * XXX a hard time running, because even the sys module has been
1115 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1116 * XXX One symptom is a sequence of information-free messages
1117 * XXX coming from threads (if a __del__ or callback is invoked,
1118 * XXX other threads can execute too, and any exception they encounter
1119 * XXX triggers a comedy of errors as subsystem after subsystem
1120 * XXX fails to find what it *expects* to find in sys to help report
1121 * XXX the exception and consequent unexpected failures). I've also
1122 * XXX seen segfaults then, after adding print statements to the
1123 * XXX Python code getting called.
1124 */
1125#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001126 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001127#endif
1128
1129 /* Disable tracemalloc after all Python objects have been destroyed,
1130 so it is possible to use tracemalloc in objects destructor. */
1131 _PyTraceMalloc_Fini();
1132
1133 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1134 _PyImport_Fini();
1135
1136 /* Cleanup typeobject.c's internal caches. */
1137 _PyType_Fini();
1138
1139 /* unload faulthandler module */
1140 _PyFaulthandler_Fini();
1141
1142 /* Debugging stuff */
1143#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001144 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001145#endif
1146 /* dump hash stats */
1147 _PyHash_Fini();
1148
Eric Snowdae02762017-09-14 00:35:58 -07001149#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001150 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001151 _PyDebug_PrintTotalRefs();
1152 }
Eric Snowdae02762017-09-14 00:35:58 -07001153#endif
Nick Coghland6009512014-11-20 21:39:37 +10001154
1155#ifdef Py_TRACE_REFS
1156 /* Display all objects still alive -- this can invoke arbitrary
1157 * __repr__ overrides, so requires a mostly-intact interpreter.
1158 * Alas, a lot of stuff may still be alive now that will be cleaned
1159 * up later.
1160 */
Victor Stinnerda273412017-12-15 01:46:02 +01001161 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001162 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001163 }
Nick Coghland6009512014-11-20 21:39:37 +10001164#endif /* Py_TRACE_REFS */
1165
1166 /* Clear interpreter state and all thread states. */
1167 PyInterpreterState_Clear(interp);
1168
1169 /* Now we decref the exception classes. After this point nothing
1170 can raise an exception. That's okay, because each Fini() method
1171 below has been checked to make sure no exceptions are ever
1172 raised.
1173 */
1174
1175 _PyExc_Fini();
1176
1177 /* Sundry finalizers */
1178 PyMethod_Fini();
1179 PyFrame_Fini();
1180 PyCFunction_Fini();
1181 PyTuple_Fini();
1182 PyList_Fini();
1183 PySet_Fini();
1184 PyBytes_Fini();
1185 PyByteArray_Fini();
1186 PyLong_Fini();
1187 PyFloat_Fini();
1188 PyDict_Fini();
1189 PySlice_Fini();
1190 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001191 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001192 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001193 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001194 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001195
1196 /* Cleanup Unicode implementation */
1197 _PyUnicode_Fini();
1198
1199 /* reset file system default encoding */
1200 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1201 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1202 Py_FileSystemDefaultEncoding = NULL;
1203 }
1204
1205 /* XXX Still allocated:
1206 - various static ad-hoc pointers to interned strings
1207 - int and float free list blocks
1208 - whatever various modules and libraries allocate
1209 */
1210
1211 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1212
1213 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001214 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001215
1216 /* Delete current thread. After this, many C API calls become crashy. */
1217 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001218
Nick Coghland6009512014-11-20 21:39:37 +10001219 PyInterpreterState_Delete(interp);
1220
1221#ifdef Py_TRACE_REFS
1222 /* Display addresses (& refcnts) of all objects still alive.
1223 * An address can be used to find the repr of the object, printed
1224 * above by _Py_PrintReferences.
1225 */
Victor Stinnerda273412017-12-15 01:46:02 +01001226 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001227 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001228 }
Nick Coghland6009512014-11-20 21:39:37 +10001229#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001230#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001231 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001232 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001233 }
Nick Coghland6009512014-11-20 21:39:37 +10001234#endif
1235
1236 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001237
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001238 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001239 return status;
1240}
1241
1242void
1243Py_Finalize(void)
1244{
1245 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001246}
1247
1248/* Create and initialize a new interpreter and thread, and return the
1249 new thread. This requires that Py_Initialize() has been called
1250 first.
1251
1252 Unsuccessful initialization yields a NULL pointer. Note that *no*
1253 exception information is available even in this case -- the
1254 exception information is held in the thread, and there is no
1255 thread.
1256
1257 Locking: as above.
1258
1259*/
1260
Victor Stinnera7368ac2017-11-15 18:11:45 -08001261static _PyInitError
1262new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001263{
1264 PyInterpreterState *interp;
1265 PyThreadState *tstate, *save_tstate;
1266 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001267 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001268
Victor Stinnera7368ac2017-11-15 18:11:45 -08001269 if (!_PyRuntime.initialized) {
1270 return _Py_INIT_ERR("Py_Initialize must be called first");
1271 }
Nick Coghland6009512014-11-20 21:39:37 +10001272
Victor Stinner8a1be612016-03-14 22:07:55 +01001273 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1274 interpreters: disable PyGILState_Check(). */
1275 _PyGILState_check_enabled = 0;
1276
Nick Coghland6009512014-11-20 21:39:37 +10001277 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001278 if (interp == NULL) {
1279 *tstate_p = NULL;
1280 return _Py_INIT_OK();
1281 }
Nick Coghland6009512014-11-20 21:39:37 +10001282
1283 tstate = PyThreadState_New(interp);
1284 if (tstate == NULL) {
1285 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001286 *tstate_p = NULL;
1287 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001288 }
1289
1290 save_tstate = PyThreadState_Swap(tstate);
1291
Eric Snow1abcf672017-05-23 21:46:51 -07001292 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001293 _PyCoreConfig *core_config;
1294 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001295 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001296 core_config = &save_tstate->interp->core_config;
1297 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001298 } else {
1299 /* No current thread state, copy from the main interpreter */
1300 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001301 core_config = &main_interp->core_config;
1302 config = &main_interp->config;
1303 }
1304
1305 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1306 return _Py_INIT_ERR("failed to copy core config");
1307 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001308 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001309 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1310 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001311 }
1312
Nick Coghland6009512014-11-20 21:39:37 +10001313 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001314 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001315 if (modules == NULL) {
1316 return _Py_INIT_ERR("can't make modules dictionary");
1317 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001318 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001319
Eric Snowd393c1b2017-09-14 12:18:12 -06001320 sysmod = _PyImport_FindBuiltin("sys", modules);
1321 if (sysmod != NULL) {
1322 interp->sysdict = PyModule_GetDict(sysmod);
1323 if (interp->sysdict == NULL)
1324 goto handle_error;
1325 Py_INCREF(interp->sysdict);
1326 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001327 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001328 }
1329
1330 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001331 if (bimod != NULL) {
1332 interp->builtins = PyModule_GetDict(bimod);
1333 if (interp->builtins == NULL)
1334 goto handle_error;
1335 Py_INCREF(interp->builtins);
1336 }
1337
1338 /* initialize builtin exceptions */
1339 _PyExc_Init(bimod);
1340
Nick Coghland6009512014-11-20 21:39:37 +10001341 if (bimod != NULL && sysmod != NULL) {
1342 PyObject *pstderr;
1343
Nick Coghland6009512014-11-20 21:39:37 +10001344 /* Set up a preliminary stderr printer until we have enough
1345 infrastructure for the io module in place. */
1346 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001347 if (pstderr == NULL) {
1348 return _Py_INIT_ERR("can't set preliminary stderr");
1349 }
Nick Coghland6009512014-11-20 21:39:37 +10001350 _PySys_SetObjectId(&PyId_stderr, pstderr);
1351 PySys_SetObject("__stderr__", pstderr);
1352 Py_DECREF(pstderr);
1353
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001354 err = _PyImportHooks_Init();
1355 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001356 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001357 }
Nick Coghland6009512014-11-20 21:39:37 +10001358
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001359 err = initimport(interp, sysmod);
1360 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001361 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001362 }
Nick Coghland6009512014-11-20 21:39:37 +10001363
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001364 err = initexternalimport(interp);
1365 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001366 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001367 }
Nick Coghland6009512014-11-20 21:39:37 +10001368
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001369 err = initfsencoding(interp);
1370 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001371 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001372 }
1373
Victor Stinner91106cd2017-12-13 12:29:09 +01001374 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001375 if (_Py_INIT_FAILED(err)) {
1376 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001377 }
1378
1379 err = add_main_module(interp);
1380 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001381 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001382 }
1383
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001384 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001385 err = initsite();
1386 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001387 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001388 }
1389 }
Nick Coghland6009512014-11-20 21:39:37 +10001390 }
1391
Victor Stinnera7368ac2017-11-15 18:11:45 -08001392 if (PyErr_Occurred()) {
1393 goto handle_error;
1394 }
Nick Coghland6009512014-11-20 21:39:37 +10001395
Victor Stinnera7368ac2017-11-15 18:11:45 -08001396 *tstate_p = tstate;
1397 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001398
Nick Coghland6009512014-11-20 21:39:37 +10001399handle_error:
1400 /* Oops, it didn't work. Undo it all. */
1401
1402 PyErr_PrintEx(0);
1403 PyThreadState_Clear(tstate);
1404 PyThreadState_Swap(save_tstate);
1405 PyThreadState_Delete(tstate);
1406 PyInterpreterState_Delete(interp);
1407
Victor Stinnera7368ac2017-11-15 18:11:45 -08001408 *tstate_p = NULL;
1409 return _Py_INIT_OK();
1410}
1411
1412PyThreadState *
1413Py_NewInterpreter(void)
1414{
1415 PyThreadState *tstate;
1416 _PyInitError err = new_interpreter(&tstate);
1417 if (_Py_INIT_FAILED(err)) {
1418 _Py_FatalInitError(err);
1419 }
1420 return tstate;
1421
Nick Coghland6009512014-11-20 21:39:37 +10001422}
1423
1424/* Delete an interpreter and its last thread. This requires that the
1425 given thread state is current, that the thread has no remaining
1426 frames, and that it is its interpreter's only remaining thread.
1427 It is a fatal error to violate these constraints.
1428
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001429 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001430 everything, regardless.)
1431
1432 Locking: as above.
1433
1434*/
1435
1436void
1437Py_EndInterpreter(PyThreadState *tstate)
1438{
1439 PyInterpreterState *interp = tstate->interp;
1440
1441 if (tstate != PyThreadState_GET())
1442 Py_FatalError("Py_EndInterpreter: thread is not current");
1443 if (tstate->frame != NULL)
1444 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1445
1446 wait_for_thread_shutdown();
1447
Marcel Plch776407f2017-12-20 11:17:58 +01001448 call_py_exitfuncs(interp);
1449
Nick Coghland6009512014-11-20 21:39:37 +10001450 if (tstate != interp->tstate_head || tstate->next != NULL)
1451 Py_FatalError("Py_EndInterpreter: not the last thread");
1452
1453 PyImport_Cleanup();
1454 PyInterpreterState_Clear(interp);
1455 PyThreadState_Swap(NULL);
1456 PyInterpreterState_Delete(interp);
1457}
1458
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001459/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001460
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001461static _PyInitError
1462add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001463{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001464 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001465 m = PyImport_AddModule("__main__");
1466 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001467 return _Py_INIT_ERR("can't create __main__ module");
1468
Nick Coghland6009512014-11-20 21:39:37 +10001469 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001470 ann_dict = PyDict_New();
1471 if ((ann_dict == NULL) ||
1472 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001473 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001474 }
1475 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001476
Nick Coghland6009512014-11-20 21:39:37 +10001477 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1478 PyObject *bimod = PyImport_ImportModule("builtins");
1479 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001480 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001481 }
1482 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001483 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001484 }
1485 Py_DECREF(bimod);
1486 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001487
Nick Coghland6009512014-11-20 21:39:37 +10001488 /* Main is a little special - imp.is_builtin("__main__") will return
1489 * False, but BuiltinImporter is still the most appropriate initial
1490 * setting for its __loader__ attribute. A more suitable value will
1491 * be set if __main__ gets further initialized later in the startup
1492 * process.
1493 */
1494 loader = PyDict_GetItemString(d, "__loader__");
1495 if (loader == NULL || loader == Py_None) {
1496 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1497 "BuiltinImporter");
1498 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001499 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001500 }
1501 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001502 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001503 }
1504 Py_DECREF(loader);
1505 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001506 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001507}
1508
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001509static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001510initfsencoding(PyInterpreterState *interp)
1511{
1512 PyObject *codec;
1513
Steve Dowercc16be82016-09-08 10:35:16 -07001514#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001516 Py_FileSystemDefaultEncoding = "mbcs";
1517 Py_FileSystemDefaultEncodeErrors = "replace";
1518 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001519 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001520 Py_FileSystemDefaultEncoding = "utf-8";
1521 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1522 }
1523#else
Victor Stinnerd500e532018-08-28 17:27:36 +02001524 if (Py_FileSystemDefaultEncoding == NULL) {
1525 if (interp->core_config.utf8_mode) {
1526 Py_FileSystemDefaultEncoding = "utf-8";
1527 Py_HasFileSystemDefaultEncoding = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001528 }
Victor Stinnerd500e532018-08-28 17:27:36 +02001529 else if (_Py_GetForceASCII()) {
1530 Py_FileSystemDefaultEncoding = "ascii";
1531 Py_HasFileSystemDefaultEncoding = 1;
1532 }
1533 else {
Victor Stinner9e4994d2018-08-28 23:26:33 +02001534 char *locale_encoding;
1535 _PyInitError err = get_locale_encoding(&locale_encoding);
1536 if (_Py_INIT_FAILED(err)) {
1537 return err;
1538 }
1539
1540 Py_FileSystemDefaultEncoding = get_codec_name(locale_encoding);
1541 PyMem_RawFree(locale_encoding);
Victor Stinnerd500e532018-08-28 17:27:36 +02001542 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner9e4994d2018-08-28 23:26:33 +02001543 return _Py_INIT_ERR("failed to get the Python codec "
1544 "of the locale encoding");
Victor Stinnerd500e532018-08-28 17:27:36 +02001545 }
Nick Coghland6009512014-11-20 21:39:37 +10001546
Victor Stinnerd500e532018-08-28 17:27:36 +02001547 Py_HasFileSystemDefaultEncoding = 0;
1548 interp->fscodec_initialized = 1;
1549 return _Py_INIT_OK();
1550 }
Nick Coghland6009512014-11-20 21:39:37 +10001551 }
Steve Dowercc16be82016-09-08 10:35:16 -07001552#endif
Nick Coghland6009512014-11-20 21:39:37 +10001553
1554 /* the encoding is mbcs, utf-8 or ascii */
1555 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1556 if (!codec) {
1557 /* Such error can only occurs in critical situations: no more
1558 * memory, import a module of the standard library failed,
1559 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001560 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001561 }
1562 Py_DECREF(codec);
1563 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001564 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001565}
1566
1567/* Import the site module (not into __main__ though) */
1568
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001569static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001570initsite(void)
1571{
1572 PyObject *m;
1573 m = PyImport_ImportModule("site");
1574 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001575 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001576 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001577 Py_DECREF(m);
1578 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001579}
1580
Victor Stinner874dbe82015-09-04 17:29:57 +02001581/* Check if a file descriptor is valid or not.
1582 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1583static int
1584is_valid_fd(int fd)
1585{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001586#ifdef __APPLE__
1587 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1588 and the other side of the pipe is closed, dup(1) succeed, whereas
1589 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1590 such error. */
1591 struct stat st;
1592 return (fstat(fd, &st) == 0);
1593#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001594 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001595 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001596 return 0;
1597 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001598 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1599 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1600 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001601 fd2 = dup(fd);
1602 if (fd2 >= 0)
1603 close(fd2);
1604 _Py_END_SUPPRESS_IPH
1605 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001606#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001607}
1608
1609/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001610static PyObject*
1611create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001612 int fd, int write_mode, const char* name,
1613 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001614{
1615 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1616 const char* mode;
1617 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001618 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001619 int buffering, isatty;
1620 _Py_IDENTIFIER(open);
1621 _Py_IDENTIFIER(isatty);
1622 _Py_IDENTIFIER(TextIOWrapper);
1623 _Py_IDENTIFIER(mode);
1624
Victor Stinner874dbe82015-09-04 17:29:57 +02001625 if (!is_valid_fd(fd))
1626 Py_RETURN_NONE;
1627
Nick Coghland6009512014-11-20 21:39:37 +10001628 /* stdin is always opened in buffered mode, first because it shouldn't
1629 make a difference in common use cases, second because TextIOWrapper
1630 depends on the presence of a read1() method which only exists on
1631 buffered streams.
1632 */
1633 if (Py_UnbufferedStdioFlag && write_mode)
1634 buffering = 0;
1635 else
1636 buffering = -1;
1637 if (write_mode)
1638 mode = "wb";
1639 else
1640 mode = "rb";
1641 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1642 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001643 Py_None, Py_None, /* encoding, errors */
1644 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001645 if (buf == NULL)
1646 goto error;
1647
1648 if (buffering) {
1649 _Py_IDENTIFIER(raw);
1650 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1651 if (raw == NULL)
1652 goto error;
1653 }
1654 else {
1655 raw = buf;
1656 Py_INCREF(raw);
1657 }
1658
Steve Dower39294992016-08-30 21:22:36 -07001659#ifdef MS_WINDOWS
1660 /* Windows console IO is always UTF-8 encoded */
1661 if (PyWindowsConsoleIO_Check(raw))
1662 encoding = "utf-8";
1663#endif
1664
Nick Coghland6009512014-11-20 21:39:37 +10001665 text = PyUnicode_FromString(name);
1666 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1667 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001668 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001669 if (res == NULL)
1670 goto error;
1671 isatty = PyObject_IsTrue(res);
1672 Py_DECREF(res);
1673 if (isatty == -1)
1674 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001675 if (Py_UnbufferedStdioFlag)
1676 write_through = Py_True;
1677 else
1678 write_through = Py_False;
1679 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001680 line_buffering = Py_True;
1681 else
1682 line_buffering = Py_False;
1683
1684 Py_CLEAR(raw);
1685 Py_CLEAR(text);
1686
1687#ifdef MS_WINDOWS
1688 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1689 newlines to "\n".
1690 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1691 newline = NULL;
1692#else
1693 /* sys.stdin: split lines at "\n".
1694 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1695 newline = "\n";
1696#endif
1697
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001698 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001699 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001700 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001701 Py_CLEAR(buf);
1702 if (stream == NULL)
1703 goto error;
1704
1705 if (write_mode)
1706 mode = "w";
1707 else
1708 mode = "r";
1709 text = PyUnicode_FromString(mode);
1710 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1711 goto error;
1712 Py_CLEAR(text);
1713 return stream;
1714
1715error:
1716 Py_XDECREF(buf);
1717 Py_XDECREF(stream);
1718 Py_XDECREF(text);
1719 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001720
Victor Stinner874dbe82015-09-04 17:29:57 +02001721 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1722 /* Issue #24891: the file descriptor was closed after the first
1723 is_valid_fd() check was called. Ignore the OSError and set the
1724 stream to None. */
1725 PyErr_Clear();
1726 Py_RETURN_NONE;
1727 }
1728 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001729}
1730
1731/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001732static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001733init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001734{
1735 PyObject *iomod = NULL, *wrapper;
1736 PyObject *bimod = NULL;
1737 PyObject *m;
1738 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001739 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001740 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001741 char *pythonioencoding = NULL;
1742 const char *encoding, *errors;
Victor Stinner9e4994d2018-08-28 23:26:33 +02001743 char *locale_encoding = NULL;
1744 char *codec_name = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001745 _PyInitError res = _Py_INIT_OK();
Victor Stinner124b9eb2018-08-29 01:29:06 +02001746 extern char *_Py_StandardStreamEncoding;
1747 extern char *_Py_StandardStreamErrors;
Nick Coghland6009512014-11-20 21:39:37 +10001748
1749 /* Hack to avoid a nasty recursion issue when Python is invoked
1750 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1751 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1752 goto error;
1753 }
1754 Py_DECREF(m);
1755
1756 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1757 goto error;
1758 }
1759 Py_DECREF(m);
1760
1761 if (!(bimod = PyImport_ImportModule("builtins"))) {
1762 goto error;
1763 }
1764
1765 if (!(iomod = PyImport_ImportModule("io"))) {
1766 goto error;
1767 }
1768 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1769 goto error;
1770 }
1771
1772 /* Set builtins.open */
1773 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1774 Py_DECREF(wrapper);
1775 goto error;
1776 }
1777 Py_DECREF(wrapper);
1778
1779 encoding = _Py_StandardStreamEncoding;
1780 errors = _Py_StandardStreamErrors;
1781 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001782 char *opt = Py_GETENV("PYTHONIOENCODING");
1783 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001784 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001785 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001786 if (pythonioencoding == NULL) {
1787 PyErr_NoMemory();
1788 goto error;
1789 }
1790 err = strchr(pythonioencoding, ':');
1791 if (err) {
1792 *err = '\0';
1793 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001794 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001795 errors = err;
1796 }
1797 }
Victor Stinner9e4994d2018-08-28 23:26:33 +02001798 if (!encoding && *pythonioencoding) {
Nick Coghland6009512014-11-20 21:39:37 +10001799 encoding = pythonioencoding;
Victor Stinner9e4994d2018-08-28 23:26:33 +02001800 if (!errors) {
1801 errors = "strict";
1802 }
Nick Coghland6009512014-11-20 21:39:37 +10001803 }
1804 }
Victor Stinner9e4994d2018-08-28 23:26:33 +02001805
1806 if (interp->core_config.utf8_mode) {
1807 if (!encoding) {
1808 encoding = "utf-8";
1809 }
1810 if (!errors) {
1811 errors = "surrogateescape";
1812 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001813 }
1814
Victor Stinner9e4994d2018-08-28 23:26:33 +02001815 if (!errors) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001816 /* Choose the default error handler based on the current locale */
Victor Stinner9e4994d2018-08-28 23:26:33 +02001817 errors = get_stdio_errors();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001818 }
Nick Coghland6009512014-11-20 21:39:37 +10001819 }
1820
Victor Stinner9e4994d2018-08-28 23:26:33 +02001821 if (encoding == NULL) {
1822 _PyInitError err = get_locale_encoding(&locale_encoding);
1823 if (_Py_INIT_FAILED(err)) {
1824 return err;
1825 }
1826 encoding = locale_encoding;
1827 }
1828
1829 codec_name = get_codec_name(encoding);
1830 if (codec_name == NULL) {
1831 PyErr_SetString(PyExc_RuntimeError,
1832 "failed to get the Python codec name "
1833 "of stdio encoding");
1834 goto error;
1835 }
1836 encoding = codec_name;
1837
Nick Coghland6009512014-11-20 21:39:37 +10001838 /* Set sys.stdin */
1839 fd = fileno(stdin);
1840 /* Under some conditions stdin, stdout and stderr may not be connected
1841 * and fileno() may point to an invalid file descriptor. For example
1842 * GUI apps don't have valid standard streams by default.
1843 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001844 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1845 if (std == NULL)
1846 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001847 PySys_SetObject("__stdin__", std);
1848 _PySys_SetObjectId(&PyId_stdin, std);
1849 Py_DECREF(std);
1850
1851 /* Set sys.stdout */
1852 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001853 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1854 if (std == NULL)
1855 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001856 PySys_SetObject("__stdout__", std);
1857 _PySys_SetObjectId(&PyId_stdout, std);
1858 Py_DECREF(std);
1859
1860#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1861 /* Set sys.stderr, replaces the preliminary stderr */
1862 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001863 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1864 if (std == NULL)
1865 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001866
1867 /* Same as hack above, pre-import stderr's codec to avoid recursion
1868 when import.c tries to write to stderr in verbose mode. */
1869 encoding_attr = PyObject_GetAttrString(std, "encoding");
1870 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001871 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001872 if (std_encoding != NULL) {
1873 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1874 Py_XDECREF(codec_info);
1875 }
1876 Py_DECREF(encoding_attr);
1877 }
1878 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1879
1880 if (PySys_SetObject("__stderr__", std) < 0) {
1881 Py_DECREF(std);
1882 goto error;
1883 }
1884 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1885 Py_DECREF(std);
1886 goto error;
1887 }
1888 Py_DECREF(std);
1889#endif
1890
Victor Stinnera7368ac2017-11-15 18:11:45 -08001891 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001892
Victor Stinnera7368ac2017-11-15 18:11:45 -08001893error:
1894 res = _Py_INIT_ERR("can't initialize sys standard streams");
1895
1896done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001897 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001898
Victor Stinner9e4994d2018-08-28 23:26:33 +02001899 PyMem_RawFree(locale_encoding);
1900 PyMem_RawFree(codec_name);
Nick Coghland6009512014-11-20 21:39:37 +10001901 PyMem_Free(pythonioencoding);
1902 Py_XDECREF(bimod);
1903 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001904 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001905}
1906
1907
Victor Stinner10dc4842015-03-24 12:01:30 +01001908static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001909_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001910{
Victor Stinner10dc4842015-03-24 12:01:30 +01001911 fputc('\n', stderr);
1912 fflush(stderr);
1913
1914 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001915 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001916}
Victor Stinner791da1c2016-03-14 16:53:12 +01001917
1918/* Print the current exception (if an exception is set) with its traceback,
1919 or display the current Python stack.
1920
1921 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1922 called on catastrophic cases.
1923
1924 Return 1 if the traceback was displayed, 0 otherwise. */
1925
1926static int
1927_Py_FatalError_PrintExc(int fd)
1928{
1929 PyObject *ferr, *res;
1930 PyObject *exception, *v, *tb;
1931 int has_tb;
1932
1933 if (PyThreadState_GET() == NULL) {
1934 /* The GIL is released: trying to acquire it is likely to deadlock,
1935 just give up. */
1936 return 0;
1937 }
1938
1939 PyErr_Fetch(&exception, &v, &tb);
1940 if (exception == NULL) {
1941 /* No current exception */
1942 return 0;
1943 }
1944
1945 ferr = _PySys_GetObjectId(&PyId_stderr);
1946 if (ferr == NULL || ferr == Py_None) {
1947 /* sys.stderr is not set yet or set to None,
1948 no need to try to display the exception */
1949 return 0;
1950 }
1951
1952 PyErr_NormalizeException(&exception, &v, &tb);
1953 if (tb == NULL) {
1954 tb = Py_None;
1955 Py_INCREF(tb);
1956 }
1957 PyException_SetTraceback(v, tb);
1958 if (exception == NULL) {
1959 /* PyErr_NormalizeException() failed */
1960 return 0;
1961 }
1962
1963 has_tb = (tb != Py_None);
1964 PyErr_Display(exception, v, tb);
1965 Py_XDECREF(exception);
1966 Py_XDECREF(v);
1967 Py_XDECREF(tb);
1968
1969 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001970 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001971 if (res == NULL)
1972 PyErr_Clear();
1973 else
1974 Py_DECREF(res);
1975
1976 return has_tb;
1977}
1978
Nick Coghland6009512014-11-20 21:39:37 +10001979/* Print fatal error message and abort */
1980
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001981#ifdef MS_WINDOWS
1982static void
1983fatal_output_debug(const char *msg)
1984{
1985 /* buffer of 256 bytes allocated on the stack */
1986 WCHAR buffer[256 / sizeof(WCHAR)];
1987 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1988 size_t msglen;
1989
1990 OutputDebugStringW(L"Fatal Python error: ");
1991
1992 msglen = strlen(msg);
1993 while (msglen) {
1994 size_t i;
1995
1996 if (buflen > msglen) {
1997 buflen = msglen;
1998 }
1999
2000 /* Convert the message to wchar_t. This uses a simple one-to-one
2001 conversion, assuming that the this error message actually uses
2002 ASCII only. If this ceases to be true, we will have to convert. */
2003 for (i=0; i < buflen; ++i) {
2004 buffer[i] = msg[i];
2005 }
2006 buffer[i] = L'\0';
2007 OutputDebugStringW(buffer);
2008
2009 msg += buflen;
2010 msglen -= buflen;
2011 }
2012 OutputDebugStringW(L"\n");
2013}
2014#endif
2015
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002016static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002017fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002018{
2019 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002020 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002021
2022 if (reentrant) {
2023 /* Py_FatalError() caused a second fatal error.
2024 Example: flush_std_files() raises a recursion error. */
2025 goto exit;
2026 }
2027 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002028
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002029 fprintf(stderr, "Fatal Python error: ");
2030 if (prefix) {
2031 fputs(prefix, stderr);
2032 fputs(": ", stderr);
2033 }
2034 if (msg) {
2035 fputs(msg, stderr);
2036 }
2037 else {
2038 fprintf(stderr, "<message not set>");
2039 }
2040 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002041 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002042
Victor Stinnere0deff32015-03-24 13:46:18 +01002043 /* Print the exception (if an exception is set) with its traceback,
2044 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002045 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002046 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002047 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002048
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002049 /* The main purpose of faulthandler is to display the traceback.
2050 This function already did its best to display a traceback.
2051 Disable faulthandler to prevent writing a second traceback
2052 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002053 _PyFaulthandler_Fini();
2054
Victor Stinner791da1c2016-03-14 16:53:12 +01002055 /* Check if the current Python thread hold the GIL */
2056 if (PyThreadState_GET() != NULL) {
2057 /* Flush sys.stdout and sys.stderr */
2058 flush_std_files();
2059 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002060
Nick Coghland6009512014-11-20 21:39:37 +10002061#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002062 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002063#endif /* MS_WINDOWS */
2064
2065exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002066 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002067#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002068 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002069#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002070 abort();
2071 }
2072 else {
2073 exit(status);
2074 }
2075}
2076
Victor Stinner19760862017-12-20 01:41:59 +01002077void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002078Py_FatalError(const char *msg)
2079{
2080 fatal_error(NULL, msg, -1);
2081}
2082
Victor Stinner19760862017-12-20 01:41:59 +01002083void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002084_Py_FatalInitError(_PyInitError err)
2085{
2086 /* On "user" error: exit with status 1.
2087 For all other errors, call abort(). */
2088 int status = err.user_err ? 1 : -1;
2089 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002090}
2091
2092/* Clean up and exit */
2093
Victor Stinnerd7292b52016-06-17 12:29:00 +02002094# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002095
Nick Coghland6009512014-11-20 21:39:37 +10002096/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002097void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002098{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002099 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002100
Antoine Pitroufc5db952017-12-13 02:29:07 +01002101 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002102 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2103
2104 is->pyexitfunc = func;
2105 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002106}
2107
2108static void
Marcel Plch776407f2017-12-20 11:17:58 +01002109call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002110{
Marcel Plch776407f2017-12-20 11:17:58 +01002111 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002112 return;
2113
Marcel Plch776407f2017-12-20 11:17:58 +01002114 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002115 PyErr_Clear();
2116}
2117
2118/* Wait until threading._shutdown completes, provided
2119 the threading module was imported in the first place.
2120 The shutdown routine will wait until all non-daemon
2121 "threading" threads have completed. */
2122static void
2123wait_for_thread_shutdown(void)
2124{
Nick Coghland6009512014-11-20 21:39:37 +10002125 _Py_IDENTIFIER(_shutdown);
2126 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002127 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002128 if (threading == NULL) {
2129 /* threading not imported */
2130 PyErr_Clear();
2131 return;
2132 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002133 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002134 if (result == NULL) {
2135 PyErr_WriteUnraisable(threading);
2136 }
2137 else {
2138 Py_DECREF(result);
2139 }
2140 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002141}
2142
2143#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002144int Py_AtExit(void (*func)(void))
2145{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002146 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002147 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002148 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002149 return 0;
2150}
2151
2152static void
2153call_ll_exitfuncs(void)
2154{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002155 while (_PyRuntime.nexitfuncs > 0)
2156 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002157
2158 fflush(stdout);
2159 fflush(stderr);
2160}
2161
Victor Stinnercfc88312018-08-01 16:41:25 +02002162void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002163Py_Exit(int sts)
2164{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002165 if (Py_FinalizeEx() < 0) {
2166 sts = 120;
2167 }
Nick Coghland6009512014-11-20 21:39:37 +10002168
2169 exit(sts);
2170}
2171
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002172static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002173initsigs(void)
2174{
2175#ifdef SIGPIPE
2176 PyOS_setsig(SIGPIPE, SIG_IGN);
2177#endif
2178#ifdef SIGXFZ
2179 PyOS_setsig(SIGXFZ, SIG_IGN);
2180#endif
2181#ifdef SIGXFSZ
2182 PyOS_setsig(SIGXFSZ, SIG_IGN);
2183#endif
2184 PyOS_InitInterrupts(); /* May imply initsignal() */
2185 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002186 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002187 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002188 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002189}
2190
2191
2192/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2193 *
2194 * All of the code in this function must only use async-signal-safe functions,
2195 * listed at `man 7 signal` or
2196 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2197 */
2198void
2199_Py_RestoreSignals(void)
2200{
2201#ifdef SIGPIPE
2202 PyOS_setsig(SIGPIPE, SIG_DFL);
2203#endif
2204#ifdef SIGXFZ
2205 PyOS_setsig(SIGXFZ, SIG_DFL);
2206#endif
2207#ifdef SIGXFSZ
2208 PyOS_setsig(SIGXFSZ, SIG_DFL);
2209#endif
2210}
2211
2212
2213/*
2214 * The file descriptor fd is considered ``interactive'' if either
2215 * a) isatty(fd) is TRUE, or
2216 * b) the -i flag was given, and the filename associated with
2217 * the descriptor is NULL or "<stdin>" or "???".
2218 */
2219int
2220Py_FdIsInteractive(FILE *fp, const char *filename)
2221{
2222 if (isatty((int)fileno(fp)))
2223 return 1;
2224 if (!Py_InteractiveFlag)
2225 return 0;
2226 return (filename == NULL) ||
2227 (strcmp(filename, "<stdin>") == 0) ||
2228 (strcmp(filename, "???") == 0);
2229}
2230
2231
Nick Coghland6009512014-11-20 21:39:37 +10002232/* Wrappers around sigaction() or signal(). */
2233
2234PyOS_sighandler_t
2235PyOS_getsig(int sig)
2236{
2237#ifdef HAVE_SIGACTION
2238 struct sigaction context;
2239 if (sigaction(sig, NULL, &context) == -1)
2240 return SIG_ERR;
2241 return context.sa_handler;
2242#else
2243 PyOS_sighandler_t handler;
2244/* Special signal handling for the secure CRT in Visual Studio 2005 */
2245#if defined(_MSC_VER) && _MSC_VER >= 1400
2246 switch (sig) {
2247 /* Only these signals are valid */
2248 case SIGINT:
2249 case SIGILL:
2250 case SIGFPE:
2251 case SIGSEGV:
2252 case SIGTERM:
2253 case SIGBREAK:
2254 case SIGABRT:
2255 break;
2256 /* Don't call signal() with other values or it will assert */
2257 default:
2258 return SIG_ERR;
2259 }
2260#endif /* _MSC_VER && _MSC_VER >= 1400 */
2261 handler = signal(sig, SIG_IGN);
2262 if (handler != SIG_ERR)
2263 signal(sig, handler);
2264 return handler;
2265#endif
2266}
2267
2268/*
2269 * All of the code in this function must only use async-signal-safe functions,
2270 * listed at `man 7 signal` or
2271 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2272 */
2273PyOS_sighandler_t
2274PyOS_setsig(int sig, PyOS_sighandler_t handler)
2275{
2276#ifdef HAVE_SIGACTION
2277 /* Some code in Modules/signalmodule.c depends on sigaction() being
2278 * used here if HAVE_SIGACTION is defined. Fix that if this code
2279 * changes to invalidate that assumption.
2280 */
2281 struct sigaction context, ocontext;
2282 context.sa_handler = handler;
2283 sigemptyset(&context.sa_mask);
2284 context.sa_flags = 0;
2285 if (sigaction(sig, &context, &ocontext) == -1)
2286 return SIG_ERR;
2287 return ocontext.sa_handler;
2288#else
2289 PyOS_sighandler_t oldhandler;
2290 oldhandler = signal(sig, handler);
2291#ifdef HAVE_SIGINTERRUPT
2292 siginterrupt(sig, 1);
2293#endif
2294 return oldhandler;
2295#endif
2296}
2297
2298#ifdef __cplusplus
2299}
2300#endif