blob: 560d0e36d49fec495ec6929e79dd571f8a5d8152 [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 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06007#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +10008#include "grammar.h"
9#include "node.h"
10#include "token.h"
11#include "parsetok.h"
12#include "errcode.h"
13#include "code.h"
14#include "symtable.h"
15#include "ast.h"
16#include "marshal.h"
17#include "osdefs.h"
18#include <locale.h>
19
20#ifdef HAVE_SIGNAL_H
21#include <signal.h>
22#endif
23
24#ifdef MS_WINDOWS
25#include "malloc.h" /* for alloca */
26#endif
27
28#ifdef HAVE_LANGINFO_H
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTE
34#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
36extern PyTypeObject PyWindowsConsoleIO_Type;
37#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
40_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
Nick Coghland6009512014-11-20 21:39:37 +100051extern grammar _PyParser_Grammar; /* From graminit.c */
52
53/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054static _PyInitError add_main_module(PyInterpreterState *interp);
55static _PyInitError initfsencoding(PyInterpreterState *interp);
56static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010057static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080058static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010059static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100060static void wait_for_thread_shutdown(void);
61static void call_ll_exitfuncs(void);
62extern int _PyUnicode_Init(void);
63extern int _PyStructSequence_Init(void);
64extern void _PyUnicode_Fini(void);
65extern int _PyLong_Init(void);
66extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080067extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100068extern void _PyFaulthandler_Fini(void);
69extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080070extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100071extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070072extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100073
Nick Coghland6009512014-11-20 21:39:37 +100074extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
75extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100076
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080_PyRuntime_Initialize(void)
81{
82 /* XXX We only initialize once in the process, which aligns with
83 the static initialization of the former globals now found in
84 _PyRuntime. However, _PyRuntime *should* be initialized with
85 every Py_Initialize() call, but doing so breaks the runtime.
86 This is because the runtime state is not properly finalized
87 currently. */
88 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080089 if (initialized) {
90 return _Py_INIT_OK();
91 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080093
94 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095}
96
97void
98_PyRuntime_Finalize(void)
99{
100 _PyRuntimeState_Fini(&_PyRuntime);
101}
102
103int
104_Py_IsFinalizing(void)
105{
106 return _PyRuntime.finalizing != NULL;
107}
108
Nick Coghland6009512014-11-20 21:39:37 +1000109/* Global configuration variable declarations are in pydebug.h */
110/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
111int Py_DebugFlag; /* Needed by parser.c */
112int Py_VerboseFlag; /* Needed by import.c */
113int Py_QuietFlag; /* Needed by sysmodule.c */
114int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
115int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
116int Py_OptimizeFlag = 0; /* Needed by compile.c */
117int Py_NoSiteFlag; /* Suppress 'import site' */
118int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Nick Coghland6009512014-11-20 21:39:37 +1000119int Py_FrozenFlag; /* Needed by getpath.c */
120int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800121int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000122int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
123int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
124int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
125int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700126#ifdef MS_WINDOWS
127int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700128int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700129#endif
Nick Coghland6009512014-11-20 21:39:37 +1000130
Nick Coghland6009512014-11-20 21:39:37 +1000131/* Hack to force loading of object files */
132int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
133 PyOS_mystrnicmp; /* Python/pystrcmp.o */
134
135/* PyModule_GetWarningsModule is no longer necessary as of 2.6
136since _warnings is builtin. This API should not be used. */
137PyObject *
138PyModule_GetWarningsModule(void)
139{
140 return PyImport_ImportModule("warnings");
141}
142
Eric Snowc7ec9982017-05-23 23:00:52 -0700143
Eric Snow1abcf672017-05-23 21:46:51 -0700144/* APIs to access the initialization flags
145 *
146 * Can be called prior to Py_Initialize.
147 */
Nick Coghland6009512014-11-20 21:39:37 +1000148
Eric Snow1abcf672017-05-23 21:46:51 -0700149int
150_Py_IsCoreInitialized(void)
151{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600152 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700153}
Nick Coghland6009512014-11-20 21:39:37 +1000154
155int
156Py_IsInitialized(void)
157{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600158 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000159}
160
161/* Helper to allow an embedding application to override the normal
162 * mechanism that attempts to figure out an appropriate IO encoding
163 */
164
165static char *_Py_StandardStreamEncoding = NULL;
166static char *_Py_StandardStreamErrors = NULL;
167
168int
169Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
170{
171 if (Py_IsInitialized()) {
172 /* This is too late to have any effect */
173 return -1;
174 }
Victor Stinner31e99082017-12-20 23:41:38 +0100175
176 int res = 0;
177
178 /* Py_SetStandardStreamEncoding() can be called before Py_Initialize(),
179 but Py_Initialize() can change the allocator. Use a known allocator
180 to be able to release the memory later. */
181 PyMemAllocatorEx old_alloc;
182 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
183
Nick Coghland6009512014-11-20 21:39:37 +1000184 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
185 * initialised yet.
186 *
187 * However, the raw memory allocators are initialised appropriately
188 * as C static variables, so _PyMem_RawStrdup is OK even though
189 * Py_Initialize hasn't been called yet.
190 */
191 if (encoding) {
192 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
193 if (!_Py_StandardStreamEncoding) {
Victor Stinner31e99082017-12-20 23:41:38 +0100194 res = -2;
195 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000196 }
197 }
198 if (errors) {
199 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
200 if (!_Py_StandardStreamErrors) {
201 if (_Py_StandardStreamEncoding) {
202 PyMem_RawFree(_Py_StandardStreamEncoding);
203 }
Victor Stinner31e99082017-12-20 23:41:38 +0100204 res = -3;
205 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000206 }
207 }
Steve Dower39294992016-08-30 21:22:36 -0700208#ifdef MS_WINDOWS
209 if (_Py_StandardStreamEncoding) {
210 /* Overriding the stream encoding implies legacy streams */
211 Py_LegacyWindowsStdioFlag = 1;
212 }
213#endif
Victor Stinner31e99082017-12-20 23:41:38 +0100214
215done:
216 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
217
218 return res;
Nick Coghland6009512014-11-20 21:39:37 +1000219}
220
Nick Coghlan6ea41862017-06-11 13:16:15 +1000221
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000222/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
223 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000224 initializations fail, a fatal error is issued and the function does
225 not return. On return, the first thread and interpreter state have
226 been created.
227
228 Locking: you must hold the interpreter lock while calling this.
229 (If the lock has not yet been initialized, that's equivalent to
230 having the lock, but you cannot use multiple threads.)
231
232*/
233
Nick Coghland6009512014-11-20 21:39:37 +1000234static char*
235get_codec_name(const char *encoding)
236{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200237 const char *name_utf8;
238 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000239 PyObject *codec, *name = NULL;
240
241 codec = _PyCodec_Lookup(encoding);
242 if (!codec)
243 goto error;
244
245 name = _PyObject_GetAttrId(codec, &PyId_name);
246 Py_CLEAR(codec);
247 if (!name)
248 goto error;
249
Serhiy Storchaka06515832016-11-20 09:13:07 +0200250 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000251 if (name_utf8 == NULL)
252 goto error;
253 name_str = _PyMem_RawStrdup(name_utf8);
254 Py_DECREF(name);
255 if (name_str == NULL) {
256 PyErr_NoMemory();
257 return NULL;
258 }
259 return name_str;
260
261error:
262 Py_XDECREF(codec);
263 Py_XDECREF(name);
264 return NULL;
265}
266
267static char*
268get_locale_encoding(void)
269{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700270#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000271 char* codeset = nl_langinfo(CODESET);
272 if (!codeset || codeset[0] == '\0') {
273 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
274 return NULL;
275 }
276 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200277#elif defined(__ANDROID__)
278 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000279#else
280 PyErr_SetNone(PyExc_NotImplementedError);
281 return NULL;
282#endif
283}
284
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800285static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700286initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000287{
288 PyObject *importlib;
289 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000290 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800291 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000292
293 /* Import _importlib through its frozen version, _frozen_importlib. */
294 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800295 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000296 }
297 else if (Py_VerboseFlag) {
298 PySys_FormatStderr("import _frozen_importlib # frozen\n");
299 }
300 importlib = PyImport_AddModule("_frozen_importlib");
301 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800302 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000303 }
304 interp->importlib = importlib;
305 Py_INCREF(interp->importlib);
306
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300307 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
308 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800309 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300310 Py_INCREF(interp->import_func);
311
Victor Stinnercd6e6942015-09-18 09:11:57 +0200312 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000313 impmod = PyInit_imp();
314 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800315 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000316 }
317 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200318 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000319 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600320 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800321 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000322 }
323
Victor Stinnercd6e6942015-09-18 09:11:57 +0200324 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000325 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200326 if (value != NULL) {
327 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700328 value = PyObject_CallMethod(importlib,
329 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200330 }
Nick Coghland6009512014-11-20 21:39:37 +1000331 if (value == NULL) {
332 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800333 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000334 }
335 Py_DECREF(value);
336 Py_DECREF(impmod);
337
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800338 err = _PyImportZip_Init();
339 if (_Py_INIT_FAILED(err)) {
340 return err;
341 }
342
343 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000344}
345
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800346static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700347initexternalimport(PyInterpreterState *interp)
348{
349 PyObject *value;
350 value = PyObject_CallMethod(interp->importlib,
351 "_install_external_importers", "");
352 if (value == NULL) {
353 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800354 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700355 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200356 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800357 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700358}
Nick Coghland6009512014-11-20 21:39:37 +1000359
Nick Coghlan6ea41862017-06-11 13:16:15 +1000360/* Helper functions to better handle the legacy C locale
361 *
362 * The legacy C locale assumes ASCII as the default text encoding, which
363 * causes problems not only for the CPython runtime, but also other
364 * components like GNU readline.
365 *
366 * Accordingly, when the CLI detects it, it attempts to coerce it to a
367 * more capable UTF-8 based alternative as follows:
368 *
369 * if (_Py_LegacyLocaleDetected()) {
370 * _Py_CoerceLegacyLocale();
371 * }
372 *
373 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
374 *
375 * Locale coercion also impacts the default error handler for the standard
376 * streams: while the usual default is "strict", the default for the legacy
377 * C locale and for any of the coercion target locales is "surrogateescape".
378 */
379
380int
381_Py_LegacyLocaleDetected(void)
382{
383#ifndef MS_WINDOWS
384 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000385 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
386 * the POSIX locale as a simple alias for the C locale, so
387 * we may also want to check for that explicitly.
388 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000389 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
390 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
391#else
392 /* Windows uses code pages instead of locales, so no locale is legacy */
393 return 0;
394#endif
395}
396
Nick Coghlaneb817952017-06-18 12:29:42 +1000397static const char *_C_LOCALE_WARNING =
398 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
399 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
400 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
401 "locales is recommended.\n";
402
Nick Coghlaneb817952017-06-18 12:29:42 +1000403static void
Victor Stinner94540602017-12-16 04:54:22 +0100404_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000405{
Victor Stinner94540602017-12-16 04:54:22 +0100406 if (core_config->coerce_c_locale_warn) {
Nick Coghlaneb817952017-06-18 12:29:42 +1000407 if (_Py_LegacyLocaleDetected()) {
408 fprintf(stderr, "%s", _C_LOCALE_WARNING);
409 }
410 }
411}
412
Nick Coghlan6ea41862017-06-11 13:16:15 +1000413typedef struct _CandidateLocale {
414 const char *locale_name; /* The locale to try as a coercion target */
415} _LocaleCoercionTarget;
416
417static _LocaleCoercionTarget _TARGET_LOCALES[] = {
418 {"C.UTF-8"},
419 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000420 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000421 {NULL}
422};
423
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200424static const char *
Nick Coghlan6ea41862017-06-11 13:16:15 +1000425get_default_standard_stream_error_handler(void)
426{
427 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
428 if (ctype_loc != NULL) {
429 /* "surrogateescape" is the default in the legacy C locale */
430 if (strcmp(ctype_loc, "C") == 0) {
431 return "surrogateescape";
432 }
433
434#ifdef PY_COERCE_C_LOCALE
435 /* "surrogateescape" is the default in locale coercion target locales */
436 const _LocaleCoercionTarget *target = NULL;
437 for (target = _TARGET_LOCALES; target->locale_name; target++) {
438 if (strcmp(ctype_loc, target->locale_name) == 0) {
439 return "surrogateescape";
440 }
441 }
442#endif
443 }
444
445 /* Otherwise return NULL to request the typical default error handler */
446 return NULL;
447}
448
449#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100450static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000451 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
452 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
453
454static void
Victor Stinner94540602017-12-16 04:54:22 +0100455_coerce_default_locale_settings(const _PyCoreConfig *config, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000456{
457 const char *newloc = target->locale_name;
458
459 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100460 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000461
462 /* Set the relevant locale environment variable */
463 if (setenv("LC_CTYPE", newloc, 1)) {
464 fprintf(stderr,
465 "Error setting LC_CTYPE, skipping C locale coercion\n");
466 return;
467 }
Victor Stinner94540602017-12-16 04:54:22 +0100468 if (config->coerce_c_locale_warn) {
469 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000470 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000471
472 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100473 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000474}
475#endif
476
477void
Victor Stinner94540602017-12-16 04:54:22 +0100478_Py_CoerceLegacyLocale(const _PyCoreConfig *config)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000479{
480#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100481 const char *locale_override = getenv("LC_ALL");
482 if (locale_override == NULL || *locale_override == '\0') {
483 /* LC_ALL is also not set (or is set to an empty string) */
484 const _LocaleCoercionTarget *target = NULL;
485 for (target = _TARGET_LOCALES; target->locale_name; target++) {
486 const char *new_locale = setlocale(LC_CTYPE,
487 target->locale_name);
488 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100489#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100490defined(HAVE_LANGINFO_H) && defined(CODESET)
491 /* Also ensure that nl_langinfo works in this locale */
492 char *codeset = nl_langinfo(CODESET);
493 if (!codeset || *codeset == '\0') {
494 /* CODESET is not set or empty, so skip coercion */
495 new_locale = NULL;
496 _Py_SetLocaleFromEnv(LC_CTYPE);
497 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000498 }
Victor Stinner94540602017-12-16 04:54:22 +0100499#endif
500 /* Successfully configured locale, so make it the default */
501 _coerce_default_locale_settings(config, target);
502 return;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000503 }
504 }
505 }
506 /* No C locale warning here, as Py_Initialize will emit one later */
507#endif
508}
509
xdegaye1588be62017-11-12 12:45:59 +0100510/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
511 * isolate the idiosyncrasies of different libc implementations. It reads the
512 * appropriate environment variable and uses its value to select the locale for
513 * 'category'. */
514char *
515_Py_SetLocaleFromEnv(int category)
516{
517#ifdef __ANDROID__
518 const char *locale;
519 const char **pvar;
520#ifdef PY_COERCE_C_LOCALE
521 const char *coerce_c_locale;
522#endif
523 const char *utf8_locale = "C.UTF-8";
524 const char *env_var_set[] = {
525 "LC_ALL",
526 "LC_CTYPE",
527 "LANG",
528 NULL,
529 };
530
531 /* Android setlocale(category, "") doesn't check the environment variables
532 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
533 * check the environment variables listed in env_var_set. */
534 for (pvar=env_var_set; *pvar; pvar++) {
535 locale = getenv(*pvar);
536 if (locale != NULL && *locale != '\0') {
537 if (strcmp(locale, utf8_locale) == 0 ||
538 strcmp(locale, "en_US.UTF-8") == 0) {
539 return setlocale(category, utf8_locale);
540 }
541 return setlocale(category, "C");
542 }
543 }
544
545 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
546 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
547 * Quote from POSIX section "8.2 Internationalization Variables":
548 * "4. If the LANG environment variable is not set or is set to the empty
549 * string, the implementation-defined default locale shall be used." */
550
551#ifdef PY_COERCE_C_LOCALE
552 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
553 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
554 /* Some other ported code may check the environment variables (e.g. in
555 * extension modules), so we make sure that they match the locale
556 * configuration */
557 if (setenv("LC_CTYPE", utf8_locale, 1)) {
558 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
559 "environment variable to %s\n", utf8_locale);
560 }
561 }
562#endif
563 return setlocale(category, utf8_locale);
564#else /* __ANDROID__ */
565 return setlocale(category, "");
566#endif /* __ANDROID__ */
567}
568
Nick Coghlan6ea41862017-06-11 13:16:15 +1000569
Eric Snow1abcf672017-05-23 21:46:51 -0700570/* Global initializations. Can be undone by Py_Finalize(). Don't
571 call this twice without an intervening Py_Finalize() call.
572
573 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
574 must have a corresponding call to Py_Finalize.
575
576 Locking: you must hold the interpreter lock while calling these APIs.
577 (If the lock has not yet been initialized, that's equivalent to
578 having the lock, but you cannot use multiple threads.)
579
580*/
581
582/* Begin interpreter initialization
583 *
584 * On return, the first thread and interpreter state have been created,
585 * but the compiler, signal handling, multithreading and
586 * multiple interpreter support, and codec infrastructure are not yet
587 * available.
588 *
589 * The import system will support builtin and frozen modules only.
590 * The only supported io is writing to sys.stderr
591 *
592 * If any operation invoked by this function fails, a fatal error is
593 * issued and the function does not return.
594 *
595 * Any code invoked from this function should *not* assume it has access
596 * to the Python C API (unless the API is explicitly listed as being
597 * safe to call without calling Py_Initialize first)
598 */
599
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800600_PyInitError
Victor Stinnerda273412017-12-15 01:46:02 +0100601_Py_InitializeCore(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000602{
Victor Stinnerda273412017-12-15 01:46:02 +0100603 assert(core_config != NULL);
604
Nick Coghland6009512014-11-20 21:39:37 +1000605 PyInterpreterState *interp;
606 PyThreadState *tstate;
607 PyObject *bimod, *sysmod, *pstderr;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800608 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000609
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800610 err = _PyRuntime_Initialize();
611 if (_Py_INIT_FAILED(err)) {
612 return err;
613 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600614
Victor Stinner31e99082017-12-20 23:41:38 +0100615 if (core_config->allocator != NULL) {
616 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
617 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
618 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800619 }
620
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600621 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800622 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700623 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600624 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800625 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700626 }
627
628 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
629 * threads behave a little more gracefully at interpreter shutdown.
630 * We clobber it here so the new interpreter can start with a clean
631 * slate.
632 *
633 * However, this may still lead to misbehaviour if there are daemon
634 * threads still hanging around from a previous Py_Initialize/Finalize
635 * pair :(
636 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600637 _PyRuntime.finalizing = NULL;
638
Nick Coghlan6ea41862017-06-11 13:16:15 +1000639#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000640 /* Set up the LC_CTYPE locale, so we can obtain
641 the locale's charset without having to switch
642 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100643 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner94540602017-12-16 04:54:22 +0100644 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000645#endif
Nick Coghland6009512014-11-20 21:39:37 +1000646
Victor Stinnerda273412017-12-15 01:46:02 +0100647 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800648 if (_Py_INIT_FAILED(err)) {
649 return err;
650 }
651
Victor Stinnerda273412017-12-15 01:46:02 +0100652 if (!core_config->use_hash_seed || core_config->hash_seed) {
Eric Snow1abcf672017-05-23 21:46:51 -0700653 /* Random or non-zero hash seed */
654 Py_HashRandomizationFlag = 1;
655 }
Nick Coghland6009512014-11-20 21:39:37 +1000656
Victor Stinnera7368ac2017-11-15 18:11:45 -0800657 err = _PyInterpreterState_Enable(&_PyRuntime);
658 if (_Py_INIT_FAILED(err)) {
659 return err;
660 }
661
Nick Coghland6009512014-11-20 21:39:37 +1000662 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100663 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800664 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100665 }
666
667 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
668 return _Py_INIT_ERR("failed to copy core config");
669 }
Nick Coghland6009512014-11-20 21:39:37 +1000670
671 tstate = PyThreadState_New(interp);
672 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800673 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000674 (void) PyThreadState_Swap(tstate);
675
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000676 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000677 destroying the GIL might fail when it is being referenced from
678 another running thread (see issue #9901).
679 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000680 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000681 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000682 /* Auto-thread-state API */
683 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000684
685 _Py_ReadyTypes();
686
687 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800688 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000689
690 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800691 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000692
693 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800694 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000695
696 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800697 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000698
Eric Snowd393c1b2017-09-14 12:18:12 -0600699 PyObject *modules = PyDict_New();
700 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800701 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600702 interp->modules = modules;
703
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800704 err = _PySys_BeginInit(&sysmod);
705 if (_Py_INIT_FAILED(err)) {
706 return err;
707 }
708
Eric Snowd393c1b2017-09-14 12:18:12 -0600709 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800710 if (interp->sysdict == NULL) {
711 return _Py_INIT_ERR("can't initialize sys dict");
712 }
713
Eric Snowd393c1b2017-09-14 12:18:12 -0600714 Py_INCREF(interp->sysdict);
715 PyDict_SetItemString(interp->sysdict, "modules", modules);
716 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000717
718 /* Init Unicode implementation; relies on the codec registry */
719 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800720 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700721
Nick Coghland6009512014-11-20 21:39:37 +1000722 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800723 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000724
725 bimod = _PyBuiltin_Init();
726 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800727 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600728 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000729 interp->builtins = PyModule_GetDict(bimod);
730 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800731 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000732 Py_INCREF(interp->builtins);
733
734 /* initialize builtin exceptions */
735 _PyExc_Init(bimod);
736
Nick Coghland6009512014-11-20 21:39:37 +1000737 /* Set up a preliminary stderr printer until we have enough
738 infrastructure for the io module in place. */
739 pstderr = PyFile_NewStdPrinter(fileno(stderr));
740 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800741 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000742 _PySys_SetObjectId(&PyId_stderr, pstderr);
743 PySys_SetObject("__stderr__", pstderr);
744 Py_DECREF(pstderr);
745
Victor Stinner672b6ba2017-12-06 17:25:50 +0100746 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800747 if (_Py_INIT_FAILED(err)) {
748 return err;
749 }
Nick Coghland6009512014-11-20 21:39:37 +1000750
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800751 err = _PyImportHooks_Init();
752 if (_Py_INIT_FAILED(err)) {
753 return err;
754 }
Nick Coghland6009512014-11-20 21:39:37 +1000755
756 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100757 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100758 return _Py_INIT_ERR("can't initialize warnings");
759 }
Nick Coghland6009512014-11-20 21:39:37 +1000760
Eric Snow1abcf672017-05-23 21:46:51 -0700761 /* This call sets up builtin and frozen import support */
762 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800763 err = initimport(interp, sysmod);
764 if (_Py_INIT_FAILED(err)) {
765 return err;
766 }
Eric Snow1abcf672017-05-23 21:46:51 -0700767 }
768
769 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600770 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800771 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700772}
773
Eric Snowc7ec9982017-05-23 23:00:52 -0700774/* Update interpreter state based on supplied configuration settings
775 *
776 * After calling this function, most of the restrictions on the interpreter
777 * are lifted. The only remaining incomplete settings are those related
778 * to the main module (sys.argv[0], __main__ metadata)
779 *
780 * Calling this when the interpreter is not initializing, is already
781 * initialized or without a valid current thread state is a fatal error.
782 * Other errors should be reported as normal Python exceptions with a
783 * non-zero return code.
784 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800785_PyInitError
786_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700787{
788 PyInterpreterState *interp;
789 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800790 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700791
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600792 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800793 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700794 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600795 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800796 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700797 }
798
Eric Snow1abcf672017-05-23 21:46:51 -0700799 /* Get current thread state and interpreter pointer */
800 tstate = PyThreadState_GET();
801 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800802 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700803 interp = tstate->interp;
804 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800805 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700806
807 /* Now finish configuring the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100808 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
809 return _Py_INIT_ERR("failed to copy main interpreter config");
810 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700811
Eric Snow1abcf672017-05-23 21:46:51 -0700812 if (interp->core_config._disable_importlib) {
813 /* Special mode for freeze_importlib: run with no import system
814 *
815 * This means anything which needs support from extension modules
816 * or pure Python code in the standard library won't work.
817 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600818 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800819 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700820 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100821
Victor Stinner33c377e2017-12-05 15:12:41 +0100822 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800823 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100824 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200825
Victor Stinner41264f12017-12-15 02:05:29 +0100826 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800827 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100828 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800829
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800830 err = initexternalimport(interp);
831 if (_Py_INIT_FAILED(err)) {
832 return err;
833 }
Nick Coghland6009512014-11-20 21:39:37 +1000834
835 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800836 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800837 if (_Py_INIT_FAILED(err)) {
838 return err;
839 }
Nick Coghland6009512014-11-20 21:39:37 +1000840
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800841 err = initfsencoding(interp);
842 if (_Py_INIT_FAILED(err)) {
843 return err;
844 }
Nick Coghland6009512014-11-20 21:39:37 +1000845
Victor Stinner1f151112017-11-23 10:43:14 +0100846 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800847 err = initsigs(); /* Signal handling stuff, including initintr() */
848 if (_Py_INIT_FAILED(err)) {
849 return err;
850 }
851 }
Nick Coghland6009512014-11-20 21:39:37 +1000852
Victor Stinnera7368ac2017-11-15 18:11:45 -0800853 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800854 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000855
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800856 err = add_main_module(interp);
857 if (_Py_INIT_FAILED(err)) {
858 return err;
859 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800860
Victor Stinner91106cd2017-12-13 12:29:09 +0100861 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800862 if (_Py_INIT_FAILED(err)) {
863 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800864 }
Nick Coghland6009512014-11-20 21:39:37 +1000865
866 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100867 if (interp->config.warnoptions != NULL &&
868 PyList_Size(interp->config.warnoptions) > 0)
869 {
Nick Coghland6009512014-11-20 21:39:37 +1000870 PyObject *warnings_module = PyImport_ImportModule("warnings");
871 if (warnings_module == NULL) {
872 fprintf(stderr, "'import warnings' failed; traceback:\n");
873 PyErr_Print();
874 }
875 Py_XDECREF(warnings_module);
876 }
877
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600878 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700879
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800880 if (!Py_NoSiteFlag) {
881 err = initsite(); /* Module site */
882 if (_Py_INIT_FAILED(err)) {
883 return err;
884 }
885 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800886 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000887}
888
Eric Snowc7ec9982017-05-23 23:00:52 -0700889#undef _INIT_DEBUG_PRINT
890
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800891_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700892_Py_InitializeEx_Private(int install_sigs, int install_importlib)
893{
Victor Stinner9cfc0022017-12-20 19:36:46 +0100894 _PyCoreConfig config = _PyCoreConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800895 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700896
Victor Stinner9cfc0022017-12-20 19:36:46 +0100897 config.ignore_environment = Py_IgnoreEnvironmentFlag;
898 config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700899 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800900
Victor Stinner9cfc0022017-12-20 19:36:46 +0100901 err = _PyCoreConfig_Read(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800902 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100903 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800904 }
905
Victor Stinner9cfc0022017-12-20 19:36:46 +0100906 err = _Py_InitializeCore(&config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100907 if (_Py_INIT_FAILED(err)) {
908 goto done;
909 }
910
Victor Stinner9cfc0022017-12-20 19:36:46 +0100911 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
912 err = _PyMainInterpreterConfig_Read(&main_config, &config);
913 if (!_Py_INIT_FAILED(err)) {
914 err = _Py_InitializeMainInterpreter(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800915 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100916 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800917 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100918 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800919 }
920
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100921 err = _Py_INIT_OK();
922
923done:
Victor Stinner9cfc0022017-12-20 19:36:46 +0100924 _PyCoreConfig_Clear(&config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100925 return err;
Eric Snow1abcf672017-05-23 21:46:51 -0700926}
927
928
929void
Nick Coghland6009512014-11-20 21:39:37 +1000930Py_InitializeEx(int install_sigs)
931{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800932 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
933 if (_Py_INIT_FAILED(err)) {
934 _Py_FatalInitError(err);
935 }
Nick Coghland6009512014-11-20 21:39:37 +1000936}
937
938void
939Py_Initialize(void)
940{
941 Py_InitializeEx(1);
942}
943
944
945#ifdef COUNT_ALLOCS
946extern void dump_counts(FILE*);
947#endif
948
949/* Flush stdout and stderr */
950
951static int
952file_is_closed(PyObject *fobj)
953{
954 int r;
955 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
956 if (tmp == NULL) {
957 PyErr_Clear();
958 return 0;
959 }
960 r = PyObject_IsTrue(tmp);
961 Py_DECREF(tmp);
962 if (r < 0)
963 PyErr_Clear();
964 return r > 0;
965}
966
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000967static int
Nick Coghland6009512014-11-20 21:39:37 +1000968flush_std_files(void)
969{
970 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
971 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
972 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000973 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000974
975 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700976 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000977 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000978 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000979 status = -1;
980 }
Nick Coghland6009512014-11-20 21:39:37 +1000981 else
982 Py_DECREF(tmp);
983 }
984
985 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700986 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000987 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000988 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000989 status = -1;
990 }
Nick Coghland6009512014-11-20 21:39:37 +1000991 else
992 Py_DECREF(tmp);
993 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000994
995 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000996}
997
998/* Undo the effect of Py_Initialize().
999
1000 Beware: if multiple interpreter and/or thread states exist, these
1001 are not wiped out; only the current thread and interpreter state
1002 are deleted. But since everything else is deleted, those other
1003 interpreter and thread states should no longer be used.
1004
1005 (XXX We should do better, e.g. wipe out all interpreters and
1006 threads.)
1007
1008 Locking: as above.
1009
1010*/
1011
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001012int
1013Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001014{
1015 PyInterpreterState *interp;
1016 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001017 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001018
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001019 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001020 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001021
1022 wait_for_thread_shutdown();
1023
Marcel Plch776407f2017-12-20 11:17:58 +01001024 /* Get current thread state and interpreter pointer */
1025 tstate = PyThreadState_GET();
1026 interp = tstate->interp;
1027
Nick Coghland6009512014-11-20 21:39:37 +10001028 /* The interpreter is still entirely intact at this point, and the
1029 * exit funcs may be relying on that. In particular, if some thread
1030 * or exit func is still waiting to do an import, the import machinery
1031 * expects Py_IsInitialized() to return true. So don't say the
1032 * interpreter is uninitialized until after the exit funcs have run.
1033 * Note that Threading.py uses an exit func to do a join on all the
1034 * threads created thru it, so this also protects pending imports in
1035 * the threads created via Threading.
1036 */
Nick Coghland6009512014-11-20 21:39:37 +10001037
Marcel Plch776407f2017-12-20 11:17:58 +01001038 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001039
Victor Stinnerda273412017-12-15 01:46:02 +01001040 /* Copy the core config, PyInterpreterState_Delete() free
1041 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001042#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001043 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001044#endif
1045#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001046 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001047#endif
1048#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001049 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001050#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001051
Nick Coghland6009512014-11-20 21:39:37 +10001052 /* Remaining threads (e.g. daemon threads) will automatically exit
1053 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001054 _PyRuntime.finalizing = tstate;
1055 _PyRuntime.initialized = 0;
1056 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001057
Victor Stinnere0deff32015-03-24 13:46:18 +01001058 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001059 if (flush_std_files() < 0) {
1060 status = -1;
1061 }
Nick Coghland6009512014-11-20 21:39:37 +10001062
1063 /* Disable signal handling */
1064 PyOS_FiniInterrupts();
1065
1066 /* Collect garbage. This may call finalizers; it's nice to call these
1067 * before all modules are destroyed.
1068 * XXX If a __del__ or weakref callback is triggered here, and tries to
1069 * XXX import a module, bad things can happen, because Python no
1070 * XXX longer believes it's initialized.
1071 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1072 * XXX is easy to provoke that way. I've also seen, e.g.,
1073 * XXX Exception exceptions.ImportError: 'No module named sha'
1074 * XXX in <function callback at 0x008F5718> ignored
1075 * XXX but I'm unclear on exactly how that one happens. In any case,
1076 * XXX I haven't seen a real-life report of either of these.
1077 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001078 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001079#ifdef COUNT_ALLOCS
1080 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1081 each collection might release some types from the type
1082 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001083 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001084 /* nothing */;
1085#endif
Eric Snowdae02762017-09-14 00:35:58 -07001086
Nick Coghland6009512014-11-20 21:39:37 +10001087 /* Destroy all modules */
1088 PyImport_Cleanup();
1089
Victor Stinnere0deff32015-03-24 13:46:18 +01001090 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001091 if (flush_std_files() < 0) {
1092 status = -1;
1093 }
Nick Coghland6009512014-11-20 21:39:37 +10001094
1095 /* Collect final garbage. This disposes of cycles created by
1096 * class definitions, for example.
1097 * XXX This is disabled because it caused too many problems. If
1098 * XXX a __del__ or weakref callback triggers here, Python code has
1099 * XXX a hard time running, because even the sys module has been
1100 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1101 * XXX One symptom is a sequence of information-free messages
1102 * XXX coming from threads (if a __del__ or callback is invoked,
1103 * XXX other threads can execute too, and any exception they encounter
1104 * XXX triggers a comedy of errors as subsystem after subsystem
1105 * XXX fails to find what it *expects* to find in sys to help report
1106 * XXX the exception and consequent unexpected failures). I've also
1107 * XXX seen segfaults then, after adding print statements to the
1108 * XXX Python code getting called.
1109 */
1110#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001111 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001112#endif
1113
1114 /* Disable tracemalloc after all Python objects have been destroyed,
1115 so it is possible to use tracemalloc in objects destructor. */
1116 _PyTraceMalloc_Fini();
1117
1118 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1119 _PyImport_Fini();
1120
1121 /* Cleanup typeobject.c's internal caches. */
1122 _PyType_Fini();
1123
1124 /* unload faulthandler module */
1125 _PyFaulthandler_Fini();
1126
1127 /* Debugging stuff */
1128#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001129 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001130#endif
1131 /* dump hash stats */
1132 _PyHash_Fini();
1133
Eric Snowdae02762017-09-14 00:35:58 -07001134#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001135 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001136 _PyDebug_PrintTotalRefs();
1137 }
Eric Snowdae02762017-09-14 00:35:58 -07001138#endif
Nick Coghland6009512014-11-20 21:39:37 +10001139
1140#ifdef Py_TRACE_REFS
1141 /* Display all objects still alive -- this can invoke arbitrary
1142 * __repr__ overrides, so requires a mostly-intact interpreter.
1143 * Alas, a lot of stuff may still be alive now that will be cleaned
1144 * up later.
1145 */
Victor Stinnerda273412017-12-15 01:46:02 +01001146 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001147 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001148 }
Nick Coghland6009512014-11-20 21:39:37 +10001149#endif /* Py_TRACE_REFS */
1150
1151 /* Clear interpreter state and all thread states. */
1152 PyInterpreterState_Clear(interp);
1153
1154 /* Now we decref the exception classes. After this point nothing
1155 can raise an exception. That's okay, because each Fini() method
1156 below has been checked to make sure no exceptions are ever
1157 raised.
1158 */
1159
1160 _PyExc_Fini();
1161
1162 /* Sundry finalizers */
1163 PyMethod_Fini();
1164 PyFrame_Fini();
1165 PyCFunction_Fini();
1166 PyTuple_Fini();
1167 PyList_Fini();
1168 PySet_Fini();
1169 PyBytes_Fini();
1170 PyByteArray_Fini();
1171 PyLong_Fini();
1172 PyFloat_Fini();
1173 PyDict_Fini();
1174 PySlice_Fini();
1175 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001176 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001177 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001178 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001179
1180 /* Cleanup Unicode implementation */
1181 _PyUnicode_Fini();
1182
1183 /* reset file system default encoding */
1184 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1185 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1186 Py_FileSystemDefaultEncoding = NULL;
1187 }
1188
1189 /* XXX Still allocated:
1190 - various static ad-hoc pointers to interned strings
1191 - int and float free list blocks
1192 - whatever various modules and libraries allocate
1193 */
1194
1195 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1196
1197 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001198 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001199
1200 /* Delete current thread. After this, many C API calls become crashy. */
1201 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001202
Nick Coghland6009512014-11-20 21:39:37 +10001203 PyInterpreterState_Delete(interp);
1204
1205#ifdef Py_TRACE_REFS
1206 /* Display addresses (& refcnts) of all objects still alive.
1207 * An address can be used to find the repr of the object, printed
1208 * above by _Py_PrintReferences.
1209 */
Victor Stinnerda273412017-12-15 01:46:02 +01001210 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001211 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001212 }
Nick Coghland6009512014-11-20 21:39:37 +10001213#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001214#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001215 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001216 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001217 }
Nick Coghland6009512014-11-20 21:39:37 +10001218#endif
1219
1220 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001221
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001222 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001223 return status;
1224}
1225
1226void
1227Py_Finalize(void)
1228{
1229 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001230}
1231
1232/* Create and initialize a new interpreter and thread, and return the
1233 new thread. This requires that Py_Initialize() has been called
1234 first.
1235
1236 Unsuccessful initialization yields a NULL pointer. Note that *no*
1237 exception information is available even in this case -- the
1238 exception information is held in the thread, and there is no
1239 thread.
1240
1241 Locking: as above.
1242
1243*/
1244
Victor Stinnera7368ac2017-11-15 18:11:45 -08001245static _PyInitError
1246new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001247{
1248 PyInterpreterState *interp;
1249 PyThreadState *tstate, *save_tstate;
1250 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001251 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001252
Victor Stinnera7368ac2017-11-15 18:11:45 -08001253 if (!_PyRuntime.initialized) {
1254 return _Py_INIT_ERR("Py_Initialize must be called first");
1255 }
Nick Coghland6009512014-11-20 21:39:37 +10001256
Victor Stinner8a1be612016-03-14 22:07:55 +01001257 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1258 interpreters: disable PyGILState_Check(). */
1259 _PyGILState_check_enabled = 0;
1260
Nick Coghland6009512014-11-20 21:39:37 +10001261 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001262 if (interp == NULL) {
1263 *tstate_p = NULL;
1264 return _Py_INIT_OK();
1265 }
Nick Coghland6009512014-11-20 21:39:37 +10001266
1267 tstate = PyThreadState_New(interp);
1268 if (tstate == NULL) {
1269 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001270 *tstate_p = NULL;
1271 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001272 }
1273
1274 save_tstate = PyThreadState_Swap(tstate);
1275
Eric Snow1abcf672017-05-23 21:46:51 -07001276 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001277 _PyCoreConfig *core_config;
1278 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001279 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001280 core_config = &save_tstate->interp->core_config;
1281 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001282 } else {
1283 /* No current thread state, copy from the main interpreter */
1284 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001285 core_config = &main_interp->core_config;
1286 config = &main_interp->config;
1287 }
1288
1289 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1290 return _Py_INIT_ERR("failed to copy core config");
1291 }
1292 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1293 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001294 }
1295
Nick Coghland6009512014-11-20 21:39:37 +10001296 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001297 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001298 if (modules == NULL) {
1299 return _Py_INIT_ERR("can't make modules dictionary");
1300 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001301 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001302
Eric Snowd393c1b2017-09-14 12:18:12 -06001303 sysmod = _PyImport_FindBuiltin("sys", modules);
1304 if (sysmod != NULL) {
1305 interp->sysdict = PyModule_GetDict(sysmod);
1306 if (interp->sysdict == NULL)
1307 goto handle_error;
1308 Py_INCREF(interp->sysdict);
1309 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001310 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001311 }
1312
1313 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001314 if (bimod != NULL) {
1315 interp->builtins = PyModule_GetDict(bimod);
1316 if (interp->builtins == NULL)
1317 goto handle_error;
1318 Py_INCREF(interp->builtins);
1319 }
1320
1321 /* initialize builtin exceptions */
1322 _PyExc_Init(bimod);
1323
Nick Coghland6009512014-11-20 21:39:37 +10001324 if (bimod != NULL && sysmod != NULL) {
1325 PyObject *pstderr;
1326
Nick Coghland6009512014-11-20 21:39:37 +10001327 /* Set up a preliminary stderr printer until we have enough
1328 infrastructure for the io module in place. */
1329 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001330 if (pstderr == NULL) {
1331 return _Py_INIT_ERR("can't set preliminary stderr");
1332 }
Nick Coghland6009512014-11-20 21:39:37 +10001333 _PySys_SetObjectId(&PyId_stderr, pstderr);
1334 PySys_SetObject("__stderr__", pstderr);
1335 Py_DECREF(pstderr);
1336
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001337 err = _PyImportHooks_Init();
1338 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001339 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001340 }
Nick Coghland6009512014-11-20 21:39:37 +10001341
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001342 err = initimport(interp, sysmod);
1343 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001344 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001345 }
Nick Coghland6009512014-11-20 21:39:37 +10001346
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001347 err = initexternalimport(interp);
1348 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001349 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001350 }
Nick Coghland6009512014-11-20 21:39:37 +10001351
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001352 err = initfsencoding(interp);
1353 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001354 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001355 }
1356
Victor Stinner91106cd2017-12-13 12:29:09 +01001357 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001358 if (_Py_INIT_FAILED(err)) {
1359 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001360 }
1361
1362 err = add_main_module(interp);
1363 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001364 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001365 }
1366
1367 if (!Py_NoSiteFlag) {
1368 err = initsite();
1369 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001370 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001371 }
1372 }
Nick Coghland6009512014-11-20 21:39:37 +10001373 }
1374
Victor Stinnera7368ac2017-11-15 18:11:45 -08001375 if (PyErr_Occurred()) {
1376 goto handle_error;
1377 }
Nick Coghland6009512014-11-20 21:39:37 +10001378
Victor Stinnera7368ac2017-11-15 18:11:45 -08001379 *tstate_p = tstate;
1380 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001381
Nick Coghland6009512014-11-20 21:39:37 +10001382handle_error:
1383 /* Oops, it didn't work. Undo it all. */
1384
1385 PyErr_PrintEx(0);
1386 PyThreadState_Clear(tstate);
1387 PyThreadState_Swap(save_tstate);
1388 PyThreadState_Delete(tstate);
1389 PyInterpreterState_Delete(interp);
1390
Victor Stinnera7368ac2017-11-15 18:11:45 -08001391 *tstate_p = NULL;
1392 return _Py_INIT_OK();
1393}
1394
1395PyThreadState *
1396Py_NewInterpreter(void)
1397{
1398 PyThreadState *tstate;
1399 _PyInitError err = new_interpreter(&tstate);
1400 if (_Py_INIT_FAILED(err)) {
1401 _Py_FatalInitError(err);
1402 }
1403 return tstate;
1404
Nick Coghland6009512014-11-20 21:39:37 +10001405}
1406
1407/* Delete an interpreter and its last thread. This requires that the
1408 given thread state is current, that the thread has no remaining
1409 frames, and that it is its interpreter's only remaining thread.
1410 It is a fatal error to violate these constraints.
1411
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001412 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001413 everything, regardless.)
1414
1415 Locking: as above.
1416
1417*/
1418
1419void
1420Py_EndInterpreter(PyThreadState *tstate)
1421{
1422 PyInterpreterState *interp = tstate->interp;
1423
1424 if (tstate != PyThreadState_GET())
1425 Py_FatalError("Py_EndInterpreter: thread is not current");
1426 if (tstate->frame != NULL)
1427 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1428
1429 wait_for_thread_shutdown();
1430
Marcel Plch776407f2017-12-20 11:17:58 +01001431 call_py_exitfuncs(interp);
1432
Nick Coghland6009512014-11-20 21:39:37 +10001433 if (tstate != interp->tstate_head || tstate->next != NULL)
1434 Py_FatalError("Py_EndInterpreter: not the last thread");
1435
1436 PyImport_Cleanup();
1437 PyInterpreterState_Clear(interp);
1438 PyThreadState_Swap(NULL);
1439 PyInterpreterState_Delete(interp);
1440}
1441
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001442/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001443
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001444static _PyInitError
1445add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001446{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001447 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001448 m = PyImport_AddModule("__main__");
1449 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001450 return _Py_INIT_ERR("can't create __main__ module");
1451
Nick Coghland6009512014-11-20 21:39:37 +10001452 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001453 ann_dict = PyDict_New();
1454 if ((ann_dict == NULL) ||
1455 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001456 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001457 }
1458 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001459
Nick Coghland6009512014-11-20 21:39:37 +10001460 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1461 PyObject *bimod = PyImport_ImportModule("builtins");
1462 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001463 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001464 }
1465 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001466 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001467 }
1468 Py_DECREF(bimod);
1469 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001470
Nick Coghland6009512014-11-20 21:39:37 +10001471 /* Main is a little special - imp.is_builtin("__main__") will return
1472 * False, but BuiltinImporter is still the most appropriate initial
1473 * setting for its __loader__ attribute. A more suitable value will
1474 * be set if __main__ gets further initialized later in the startup
1475 * process.
1476 */
1477 loader = PyDict_GetItemString(d, "__loader__");
1478 if (loader == NULL || loader == Py_None) {
1479 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1480 "BuiltinImporter");
1481 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001482 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001483 }
1484 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001485 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001486 }
1487 Py_DECREF(loader);
1488 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001489 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001490}
1491
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001492static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001493initfsencoding(PyInterpreterState *interp)
1494{
1495 PyObject *codec;
1496
Steve Dowercc16be82016-09-08 10:35:16 -07001497#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001499 Py_FileSystemDefaultEncoding = "mbcs";
1500 Py_FileSystemDefaultEncodeErrors = "replace";
1501 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001502 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001503 Py_FileSystemDefaultEncoding = "utf-8";
1504 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1505 }
1506#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001507 if (Py_FileSystemDefaultEncoding == NULL &&
1508 interp->core_config.utf8_mode)
1509 {
1510 Py_FileSystemDefaultEncoding = "utf-8";
1511 Py_HasFileSystemDefaultEncoding = 1;
1512 }
1513 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001514 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515 if (Py_FileSystemDefaultEncoding == NULL) {
1516 return _Py_INIT_ERR("Unable to get the locale encoding");
1517 }
Nick Coghland6009512014-11-20 21:39:37 +10001518
1519 Py_HasFileSystemDefaultEncoding = 0;
1520 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001521 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001522 }
Steve Dowercc16be82016-09-08 10:35:16 -07001523#endif
Nick Coghland6009512014-11-20 21:39:37 +10001524
1525 /* the encoding is mbcs, utf-8 or ascii */
1526 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1527 if (!codec) {
1528 /* Such error can only occurs in critical situations: no more
1529 * memory, import a module of the standard library failed,
1530 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001531 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001532 }
1533 Py_DECREF(codec);
1534 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001535 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001536}
1537
1538/* Import the site module (not into __main__ though) */
1539
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001540static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001541initsite(void)
1542{
1543 PyObject *m;
1544 m = PyImport_ImportModule("site");
1545 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001546 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001547 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001548 Py_DECREF(m);
1549 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001550}
1551
Victor Stinner874dbe82015-09-04 17:29:57 +02001552/* Check if a file descriptor is valid or not.
1553 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1554static int
1555is_valid_fd(int fd)
1556{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001557#ifdef __APPLE__
1558 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1559 and the other side of the pipe is closed, dup(1) succeed, whereas
1560 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1561 such error. */
1562 struct stat st;
1563 return (fstat(fd, &st) == 0);
1564#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001565 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001566 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001567 return 0;
1568 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001569 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1570 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1571 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001572 fd2 = dup(fd);
1573 if (fd2 >= 0)
1574 close(fd2);
1575 _Py_END_SUPPRESS_IPH
1576 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001577#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001578}
1579
1580/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001581static PyObject*
1582create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001583 int fd, int write_mode, const char* name,
1584 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001585{
1586 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1587 const char* mode;
1588 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001589 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001590 int buffering, isatty;
1591 _Py_IDENTIFIER(open);
1592 _Py_IDENTIFIER(isatty);
1593 _Py_IDENTIFIER(TextIOWrapper);
1594 _Py_IDENTIFIER(mode);
1595
Victor Stinner874dbe82015-09-04 17:29:57 +02001596 if (!is_valid_fd(fd))
1597 Py_RETURN_NONE;
1598
Nick Coghland6009512014-11-20 21:39:37 +10001599 /* stdin is always opened in buffered mode, first because it shouldn't
1600 make a difference in common use cases, second because TextIOWrapper
1601 depends on the presence of a read1() method which only exists on
1602 buffered streams.
1603 */
1604 if (Py_UnbufferedStdioFlag && write_mode)
1605 buffering = 0;
1606 else
1607 buffering = -1;
1608 if (write_mode)
1609 mode = "wb";
1610 else
1611 mode = "rb";
1612 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1613 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001614 Py_None, Py_None, /* encoding, errors */
1615 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001616 if (buf == NULL)
1617 goto error;
1618
1619 if (buffering) {
1620 _Py_IDENTIFIER(raw);
1621 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1622 if (raw == NULL)
1623 goto error;
1624 }
1625 else {
1626 raw = buf;
1627 Py_INCREF(raw);
1628 }
1629
Steve Dower39294992016-08-30 21:22:36 -07001630#ifdef MS_WINDOWS
1631 /* Windows console IO is always UTF-8 encoded */
1632 if (PyWindowsConsoleIO_Check(raw))
1633 encoding = "utf-8";
1634#endif
1635
Nick Coghland6009512014-11-20 21:39:37 +10001636 text = PyUnicode_FromString(name);
1637 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1638 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001639 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001640 if (res == NULL)
1641 goto error;
1642 isatty = PyObject_IsTrue(res);
1643 Py_DECREF(res);
1644 if (isatty == -1)
1645 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001646 if (Py_UnbufferedStdioFlag)
1647 write_through = Py_True;
1648 else
1649 write_through = Py_False;
1650 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001651 line_buffering = Py_True;
1652 else
1653 line_buffering = Py_False;
1654
1655 Py_CLEAR(raw);
1656 Py_CLEAR(text);
1657
1658#ifdef MS_WINDOWS
1659 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1660 newlines to "\n".
1661 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1662 newline = NULL;
1663#else
1664 /* sys.stdin: split lines at "\n".
1665 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1666 newline = "\n";
1667#endif
1668
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001669 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001670 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001671 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001672 Py_CLEAR(buf);
1673 if (stream == NULL)
1674 goto error;
1675
1676 if (write_mode)
1677 mode = "w";
1678 else
1679 mode = "r";
1680 text = PyUnicode_FromString(mode);
1681 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1682 goto error;
1683 Py_CLEAR(text);
1684 return stream;
1685
1686error:
1687 Py_XDECREF(buf);
1688 Py_XDECREF(stream);
1689 Py_XDECREF(text);
1690 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001691
Victor Stinner874dbe82015-09-04 17:29:57 +02001692 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1693 /* Issue #24891: the file descriptor was closed after the first
1694 is_valid_fd() check was called. Ignore the OSError and set the
1695 stream to None. */
1696 PyErr_Clear();
1697 Py_RETURN_NONE;
1698 }
1699 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001700}
1701
1702/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001703static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001704init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001705{
1706 PyObject *iomod = NULL, *wrapper;
1707 PyObject *bimod = NULL;
1708 PyObject *m;
1709 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001710 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001711 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001712 char *pythonioencoding = NULL;
1713 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001714 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001715
1716 /* Hack to avoid a nasty recursion issue when Python is invoked
1717 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1718 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1719 goto error;
1720 }
1721 Py_DECREF(m);
1722
1723 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1724 goto error;
1725 }
1726 Py_DECREF(m);
1727
1728 if (!(bimod = PyImport_ImportModule("builtins"))) {
1729 goto error;
1730 }
1731
1732 if (!(iomod = PyImport_ImportModule("io"))) {
1733 goto error;
1734 }
1735 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1736 goto error;
1737 }
1738
1739 /* Set builtins.open */
1740 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1741 Py_DECREF(wrapper);
1742 goto error;
1743 }
1744 Py_DECREF(wrapper);
1745
1746 encoding = _Py_StandardStreamEncoding;
1747 errors = _Py_StandardStreamErrors;
1748 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001749 char *opt = Py_GETENV("PYTHONIOENCODING");
1750 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001751 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001752 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001753 if (pythonioencoding == NULL) {
1754 PyErr_NoMemory();
1755 goto error;
1756 }
1757 err = strchr(pythonioencoding, ':');
1758 if (err) {
1759 *err = '\0';
1760 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001761 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001762 errors = err;
1763 }
1764 }
1765 if (*pythonioencoding && !encoding) {
1766 encoding = pythonioencoding;
1767 }
1768 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001769 else if (interp->core_config.utf8_mode) {
1770 encoding = "utf-8";
1771 errors = "surrogateescape";
1772 }
1773
1774 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001775 /* Choose the default error handler based on the current locale */
1776 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001777 }
Nick Coghland6009512014-11-20 21:39:37 +10001778 }
1779
1780 /* Set sys.stdin */
1781 fd = fileno(stdin);
1782 /* Under some conditions stdin, stdout and stderr may not be connected
1783 * and fileno() may point to an invalid file descriptor. For example
1784 * GUI apps don't have valid standard streams by default.
1785 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001786 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1787 if (std == NULL)
1788 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001789 PySys_SetObject("__stdin__", std);
1790 _PySys_SetObjectId(&PyId_stdin, std);
1791 Py_DECREF(std);
1792
1793 /* Set sys.stdout */
1794 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001795 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1796 if (std == NULL)
1797 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001798 PySys_SetObject("__stdout__", std);
1799 _PySys_SetObjectId(&PyId_stdout, std);
1800 Py_DECREF(std);
1801
1802#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1803 /* Set sys.stderr, replaces the preliminary stderr */
1804 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001805 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1806 if (std == NULL)
1807 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001808
1809 /* Same as hack above, pre-import stderr's codec to avoid recursion
1810 when import.c tries to write to stderr in verbose mode. */
1811 encoding_attr = PyObject_GetAttrString(std, "encoding");
1812 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001813 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001814 if (std_encoding != NULL) {
1815 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1816 Py_XDECREF(codec_info);
1817 }
1818 Py_DECREF(encoding_attr);
1819 }
1820 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1821
1822 if (PySys_SetObject("__stderr__", std) < 0) {
1823 Py_DECREF(std);
1824 goto error;
1825 }
1826 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1827 Py_DECREF(std);
1828 goto error;
1829 }
1830 Py_DECREF(std);
1831#endif
1832
Victor Stinnera7368ac2017-11-15 18:11:45 -08001833 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001834
Victor Stinnera7368ac2017-11-15 18:11:45 -08001835error:
1836 res = _Py_INIT_ERR("can't initialize sys standard streams");
1837
Victor Stinner31e99082017-12-20 23:41:38 +01001838 /* Use the same allocator than Py_SetStandardStreamEncoding() */
1839 PyMemAllocatorEx old_alloc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001840done:
Victor Stinner31e99082017-12-20 23:41:38 +01001841 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1842
Nick Coghland6009512014-11-20 21:39:37 +10001843 /* We won't need them anymore. */
1844 if (_Py_StandardStreamEncoding) {
1845 PyMem_RawFree(_Py_StandardStreamEncoding);
1846 _Py_StandardStreamEncoding = NULL;
1847 }
1848 if (_Py_StandardStreamErrors) {
1849 PyMem_RawFree(_Py_StandardStreamErrors);
1850 _Py_StandardStreamErrors = NULL;
1851 }
Victor Stinner31e99082017-12-20 23:41:38 +01001852
1853 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1854
Nick Coghland6009512014-11-20 21:39:37 +10001855 PyMem_Free(pythonioencoding);
1856 Py_XDECREF(bimod);
1857 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001858 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001859}
1860
1861
Victor Stinner10dc4842015-03-24 12:01:30 +01001862static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001863_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001864{
Victor Stinner10dc4842015-03-24 12:01:30 +01001865 fputc('\n', stderr);
1866 fflush(stderr);
1867
1868 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001869 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001870}
Victor Stinner791da1c2016-03-14 16:53:12 +01001871
1872/* Print the current exception (if an exception is set) with its traceback,
1873 or display the current Python stack.
1874
1875 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1876 called on catastrophic cases.
1877
1878 Return 1 if the traceback was displayed, 0 otherwise. */
1879
1880static int
1881_Py_FatalError_PrintExc(int fd)
1882{
1883 PyObject *ferr, *res;
1884 PyObject *exception, *v, *tb;
1885 int has_tb;
1886
1887 if (PyThreadState_GET() == NULL) {
1888 /* The GIL is released: trying to acquire it is likely to deadlock,
1889 just give up. */
1890 return 0;
1891 }
1892
1893 PyErr_Fetch(&exception, &v, &tb);
1894 if (exception == NULL) {
1895 /* No current exception */
1896 return 0;
1897 }
1898
1899 ferr = _PySys_GetObjectId(&PyId_stderr);
1900 if (ferr == NULL || ferr == Py_None) {
1901 /* sys.stderr is not set yet or set to None,
1902 no need to try to display the exception */
1903 return 0;
1904 }
1905
1906 PyErr_NormalizeException(&exception, &v, &tb);
1907 if (tb == NULL) {
1908 tb = Py_None;
1909 Py_INCREF(tb);
1910 }
1911 PyException_SetTraceback(v, tb);
1912 if (exception == NULL) {
1913 /* PyErr_NormalizeException() failed */
1914 return 0;
1915 }
1916
1917 has_tb = (tb != Py_None);
1918 PyErr_Display(exception, v, tb);
1919 Py_XDECREF(exception);
1920 Py_XDECREF(v);
1921 Py_XDECREF(tb);
1922
1923 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001924 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001925 if (res == NULL)
1926 PyErr_Clear();
1927 else
1928 Py_DECREF(res);
1929
1930 return has_tb;
1931}
1932
Nick Coghland6009512014-11-20 21:39:37 +10001933/* Print fatal error message and abort */
1934
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001935#ifdef MS_WINDOWS
1936static void
1937fatal_output_debug(const char *msg)
1938{
1939 /* buffer of 256 bytes allocated on the stack */
1940 WCHAR buffer[256 / sizeof(WCHAR)];
1941 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1942 size_t msglen;
1943
1944 OutputDebugStringW(L"Fatal Python error: ");
1945
1946 msglen = strlen(msg);
1947 while (msglen) {
1948 size_t i;
1949
1950 if (buflen > msglen) {
1951 buflen = msglen;
1952 }
1953
1954 /* Convert the message to wchar_t. This uses a simple one-to-one
1955 conversion, assuming that the this error message actually uses
1956 ASCII only. If this ceases to be true, we will have to convert. */
1957 for (i=0; i < buflen; ++i) {
1958 buffer[i] = msg[i];
1959 }
1960 buffer[i] = L'\0';
1961 OutputDebugStringW(buffer);
1962
1963 msg += buflen;
1964 msglen -= buflen;
1965 }
1966 OutputDebugStringW(L"\n");
1967}
1968#endif
1969
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001970static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001971fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001972{
1973 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001974 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001975
1976 if (reentrant) {
1977 /* Py_FatalError() caused a second fatal error.
1978 Example: flush_std_files() raises a recursion error. */
1979 goto exit;
1980 }
1981 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001982
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001983 fprintf(stderr, "Fatal Python error: ");
1984 if (prefix) {
1985 fputs(prefix, stderr);
1986 fputs(": ", stderr);
1987 }
1988 if (msg) {
1989 fputs(msg, stderr);
1990 }
1991 else {
1992 fprintf(stderr, "<message not set>");
1993 }
1994 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001995 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001996
Victor Stinnere0deff32015-03-24 13:46:18 +01001997 /* Print the exception (if an exception is set) with its traceback,
1998 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001999 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002000 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002001 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002002
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002003 /* The main purpose of faulthandler is to display the traceback.
2004 This function already did its best to display a traceback.
2005 Disable faulthandler to prevent writing a second traceback
2006 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002007 _PyFaulthandler_Fini();
2008
Victor Stinner791da1c2016-03-14 16:53:12 +01002009 /* Check if the current Python thread hold the GIL */
2010 if (PyThreadState_GET() != NULL) {
2011 /* Flush sys.stdout and sys.stderr */
2012 flush_std_files();
2013 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002014
Nick Coghland6009512014-11-20 21:39:37 +10002015#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002016 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002017#endif /* MS_WINDOWS */
2018
2019exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002020 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002021#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002022 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002023#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002024 abort();
2025 }
2026 else {
2027 exit(status);
2028 }
2029}
2030
Victor Stinner19760862017-12-20 01:41:59 +01002031void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002032Py_FatalError(const char *msg)
2033{
2034 fatal_error(NULL, msg, -1);
2035}
2036
Victor Stinner19760862017-12-20 01:41:59 +01002037void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002038_Py_FatalInitError(_PyInitError err)
2039{
2040 /* On "user" error: exit with status 1.
2041 For all other errors, call abort(). */
2042 int status = err.user_err ? 1 : -1;
2043 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002044}
2045
2046/* Clean up and exit */
2047
Victor Stinnerd7292b52016-06-17 12:29:00 +02002048# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002049
Nick Coghland6009512014-11-20 21:39:37 +10002050/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002051void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002052{
Marcel Plch776407f2017-12-20 11:17:58 +01002053 PyThreadState *ts;
2054 PyInterpreterState *is;
Victor Stinnerca719ac2017-12-20 18:00:19 +01002055
Marcel Plch776407f2017-12-20 11:17:58 +01002056 ts = PyThreadState_GET();
2057 is = ts->interp;
2058
Antoine Pitroufc5db952017-12-13 02:29:07 +01002059 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002060 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2061
2062 is->pyexitfunc = func;
2063 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002064}
2065
2066static void
Marcel Plch776407f2017-12-20 11:17:58 +01002067call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002068{
Marcel Plch776407f2017-12-20 11:17:58 +01002069 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002070 return;
2071
Marcel Plch776407f2017-12-20 11:17:58 +01002072 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002073 PyErr_Clear();
2074}
2075
2076/* Wait until threading._shutdown completes, provided
2077 the threading module was imported in the first place.
2078 The shutdown routine will wait until all non-daemon
2079 "threading" threads have completed. */
2080static void
2081wait_for_thread_shutdown(void)
2082{
Nick Coghland6009512014-11-20 21:39:37 +10002083 _Py_IDENTIFIER(_shutdown);
2084 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002085 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002086 if (threading == NULL) {
2087 /* threading not imported */
2088 PyErr_Clear();
2089 return;
2090 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002091 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002092 if (result == NULL) {
2093 PyErr_WriteUnraisable(threading);
2094 }
2095 else {
2096 Py_DECREF(result);
2097 }
2098 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002099}
2100
2101#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002102int Py_AtExit(void (*func)(void))
2103{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002104 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002105 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002106 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002107 return 0;
2108}
2109
2110static void
2111call_ll_exitfuncs(void)
2112{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002113 while (_PyRuntime.nexitfuncs > 0)
2114 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002115
2116 fflush(stdout);
2117 fflush(stderr);
2118}
2119
2120void
2121Py_Exit(int sts)
2122{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002123 if (Py_FinalizeEx() < 0) {
2124 sts = 120;
2125 }
Nick Coghland6009512014-11-20 21:39:37 +10002126
2127 exit(sts);
2128}
2129
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002130static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002131initsigs(void)
2132{
2133#ifdef SIGPIPE
2134 PyOS_setsig(SIGPIPE, SIG_IGN);
2135#endif
2136#ifdef SIGXFZ
2137 PyOS_setsig(SIGXFZ, SIG_IGN);
2138#endif
2139#ifdef SIGXFSZ
2140 PyOS_setsig(SIGXFSZ, SIG_IGN);
2141#endif
2142 PyOS_InitInterrupts(); /* May imply initsignal() */
2143 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002144 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002145 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002146 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002147}
2148
2149
2150/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2151 *
2152 * All of the code in this function must only use async-signal-safe functions,
2153 * listed at `man 7 signal` or
2154 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2155 */
2156void
2157_Py_RestoreSignals(void)
2158{
2159#ifdef SIGPIPE
2160 PyOS_setsig(SIGPIPE, SIG_DFL);
2161#endif
2162#ifdef SIGXFZ
2163 PyOS_setsig(SIGXFZ, SIG_DFL);
2164#endif
2165#ifdef SIGXFSZ
2166 PyOS_setsig(SIGXFSZ, SIG_DFL);
2167#endif
2168}
2169
2170
2171/*
2172 * The file descriptor fd is considered ``interactive'' if either
2173 * a) isatty(fd) is TRUE, or
2174 * b) the -i flag was given, and the filename associated with
2175 * the descriptor is NULL or "<stdin>" or "???".
2176 */
2177int
2178Py_FdIsInteractive(FILE *fp, const char *filename)
2179{
2180 if (isatty((int)fileno(fp)))
2181 return 1;
2182 if (!Py_InteractiveFlag)
2183 return 0;
2184 return (filename == NULL) ||
2185 (strcmp(filename, "<stdin>") == 0) ||
2186 (strcmp(filename, "???") == 0);
2187}
2188
2189
Nick Coghland6009512014-11-20 21:39:37 +10002190/* Wrappers around sigaction() or signal(). */
2191
2192PyOS_sighandler_t
2193PyOS_getsig(int sig)
2194{
2195#ifdef HAVE_SIGACTION
2196 struct sigaction context;
2197 if (sigaction(sig, NULL, &context) == -1)
2198 return SIG_ERR;
2199 return context.sa_handler;
2200#else
2201 PyOS_sighandler_t handler;
2202/* Special signal handling for the secure CRT in Visual Studio 2005 */
2203#if defined(_MSC_VER) && _MSC_VER >= 1400
2204 switch (sig) {
2205 /* Only these signals are valid */
2206 case SIGINT:
2207 case SIGILL:
2208 case SIGFPE:
2209 case SIGSEGV:
2210 case SIGTERM:
2211 case SIGBREAK:
2212 case SIGABRT:
2213 break;
2214 /* Don't call signal() with other values or it will assert */
2215 default:
2216 return SIG_ERR;
2217 }
2218#endif /* _MSC_VER && _MSC_VER >= 1400 */
2219 handler = signal(sig, SIG_IGN);
2220 if (handler != SIG_ERR)
2221 signal(sig, handler);
2222 return handler;
2223#endif
2224}
2225
2226/*
2227 * All of the code in this function must only use async-signal-safe functions,
2228 * listed at `man 7 signal` or
2229 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2230 */
2231PyOS_sighandler_t
2232PyOS_setsig(int sig, PyOS_sighandler_t handler)
2233{
2234#ifdef HAVE_SIGACTION
2235 /* Some code in Modules/signalmodule.c depends on sigaction() being
2236 * used here if HAVE_SIGACTION is defined. Fix that if this code
2237 * changes to invalidate that assumption.
2238 */
2239 struct sigaction context, ocontext;
2240 context.sa_handler = handler;
2241 sigemptyset(&context.sa_mask);
2242 context.sa_flags = 0;
2243 if (sigaction(sig, &context, &ocontext) == -1)
2244 return SIG_ERR;
2245 return ocontext.sa_handler;
2246#else
2247 PyOS_sighandler_t oldhandler;
2248 oldhandler = signal(sig, handler);
2249#ifdef HAVE_SIGINTERRUPT
2250 siginterrupt(sig, 1);
2251#endif
2252 return oldhandler;
2253#endif
2254}
2255
2256#ifdef __cplusplus
2257}
2258#endif