blob: 2ef96f8d99ef2a60a50cfadc52d86dac47fcf217 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
Yury Selivanovf23746a2018-01-22 19:11:18 -05007#include "internal/context.h"
8#include "internal/hamt.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06009#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100010#include "grammar.h"
11#include "node.h"
12#include "token.h"
13#include "parsetok.h"
14#include "errcode.h"
15#include "code.h"
16#include "symtable.h"
17#include "ast.h"
18#include "marshal.h"
19#include "osdefs.h"
20#include <locale.h>
21
22#ifdef HAVE_SIGNAL_H
23#include <signal.h>
24#endif
25
26#ifdef MS_WINDOWS
27#include "malloc.h" /* for alloca */
28#endif
29
30#ifdef HAVE_LANGINFO_H
31#include <langinfo.h>
32#endif
33
34#ifdef MS_WINDOWS
35#undef BYTE
36#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070037
38extern PyTypeObject PyWindowsConsoleIO_Type;
39#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100040#endif
41
42_Py_IDENTIFIER(flush);
43_Py_IDENTIFIER(name);
44_Py_IDENTIFIER(stdin);
45_Py_IDENTIFIER(stdout);
46_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060047_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100048
49#ifdef __cplusplus
50extern "C" {
51#endif
52
Nick Coghland6009512014-11-20 21:39:37 +100053extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056static _PyInitError add_main_module(PyInterpreterState *interp);
57static _PyInitError initfsencoding(PyInterpreterState *interp);
58static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010059static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010061static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100062static void wait_for_thread_shutdown(void);
63static void call_ll_exitfuncs(void);
64extern int _PyUnicode_Init(void);
65extern int _PyStructSequence_Init(void);
66extern void _PyUnicode_Fini(void);
67extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080069extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100070extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080072extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100073extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070074extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100075
Nick Coghland6009512014-11-20 21:39:37 +100076extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082_PyRuntime_Initialize(void)
83{
84 /* XXX We only initialize once in the process, which aligns with
85 the static initialization of the former globals now found in
86 _PyRuntime. However, _PyRuntime *should* be initialized with
87 every Py_Initialize() call, but doing so breaks the runtime.
88 This is because the runtime state is not properly finalized
89 currently. */
90 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091 if (initialized) {
92 return _Py_INIT_OK();
93 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095
96 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99void
100_PyRuntime_Finalize(void)
101{
102 _PyRuntimeState_Fini(&_PyRuntime);
103}
104
105int
106_Py_IsFinalizing(void)
107{
108 return _PyRuntime.finalizing != NULL;
109}
110
Nick Coghland6009512014-11-20 21:39:37 +1000111/* Global configuration variable declarations are in pydebug.h */
112/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
Benjamin Peterson0a37a302017-12-31 10:04:13 -0800113int Py_DebugFlag = 0; /* Needed by parser.c */
114int Py_VerboseFlag = 0; /* Needed by import.c */
115int Py_QuietFlag = 0; /* Needed by sysmodule.c */
116int Py_InteractiveFlag = 0; /* Needed by Py_FdIsInteractive() below */
117int Py_InspectFlag = 0; /* Needed to determine whether to exit at SystemExit */
Nick Coghland6009512014-11-20 21:39:37 +1000118int Py_OptimizeFlag = 0; /* Needed by compile.c */
Benjamin Peterson0a37a302017-12-31 10:04:13 -0800119int Py_NoSiteFlag = 0; /* Suppress 'import site' */
120int Py_BytesWarningFlag = 0; /* Warn on str(bytes) and str(buffer) */
121int Py_FrozenFlag = 0; /* Needed by getpath.c */
122int Py_IgnoreEnvironmentFlag = 0; /* e.g. PYTHONPATH, PYTHONHOME */
123int Py_DontWriteBytecodeFlag = 0; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000124int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
125int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
126int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
127int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700128#ifdef MS_WINDOWS
129int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700130int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700131#endif
Nick Coghland6009512014-11-20 21:39:37 +1000132
Nick Coghland6009512014-11-20 21:39:37 +1000133/* Hack to force loading of object files */
134int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
135 PyOS_mystrnicmp; /* Python/pystrcmp.o */
136
137/* PyModule_GetWarningsModule is no longer necessary as of 2.6
138since _warnings is builtin. This API should not be used. */
139PyObject *
140PyModule_GetWarningsModule(void)
141{
142 return PyImport_ImportModule("warnings");
143}
144
Eric Snowc7ec9982017-05-23 23:00:52 -0700145
Eric Snow1abcf672017-05-23 21:46:51 -0700146/* APIs to access the initialization flags
147 *
148 * Can be called prior to Py_Initialize.
149 */
Nick Coghland6009512014-11-20 21:39:37 +1000150
Eric Snow1abcf672017-05-23 21:46:51 -0700151int
152_Py_IsCoreInitialized(void)
153{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600154 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700155}
Nick Coghland6009512014-11-20 21:39:37 +1000156
157int
158Py_IsInitialized(void)
159{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600160 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000161}
162
163/* Helper to allow an embedding application to override the normal
164 * mechanism that attempts to figure out an appropriate IO encoding
165 */
166
167static char *_Py_StandardStreamEncoding = NULL;
168static char *_Py_StandardStreamErrors = NULL;
169
170int
171Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
172{
173 if (Py_IsInitialized()) {
174 /* This is too late to have any effect */
175 return -1;
176 }
Victor Stinner31e99082017-12-20 23:41:38 +0100177
178 int res = 0;
179
180 /* Py_SetStandardStreamEncoding() can be called before Py_Initialize(),
181 but Py_Initialize() can change the allocator. Use a known allocator
182 to be able to release the memory later. */
183 PyMemAllocatorEx old_alloc;
184 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
185
Nick Coghland6009512014-11-20 21:39:37 +1000186 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
187 * initialised yet.
188 *
189 * However, the raw memory allocators are initialised appropriately
190 * as C static variables, so _PyMem_RawStrdup is OK even though
191 * Py_Initialize hasn't been called yet.
192 */
193 if (encoding) {
194 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
195 if (!_Py_StandardStreamEncoding) {
Victor Stinner31e99082017-12-20 23:41:38 +0100196 res = -2;
197 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000198 }
199 }
200 if (errors) {
201 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
202 if (!_Py_StandardStreamErrors) {
203 if (_Py_StandardStreamEncoding) {
204 PyMem_RawFree(_Py_StandardStreamEncoding);
205 }
Victor Stinner31e99082017-12-20 23:41:38 +0100206 res = -3;
207 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000208 }
209 }
Steve Dower39294992016-08-30 21:22:36 -0700210#ifdef MS_WINDOWS
211 if (_Py_StandardStreamEncoding) {
212 /* Overriding the stream encoding implies legacy streams */
213 Py_LegacyWindowsStdioFlag = 1;
214 }
215#endif
Victor Stinner31e99082017-12-20 23:41:38 +0100216
217done:
218 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
219
220 return res;
Nick Coghland6009512014-11-20 21:39:37 +1000221}
222
Nick Coghlan6ea41862017-06-11 13:16:15 +1000223
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000224/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
225 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000226 initializations fail, a fatal error is issued and the function does
227 not return. On return, the first thread and interpreter state have
228 been created.
229
230 Locking: you must hold the interpreter lock while calling this.
231 (If the lock has not yet been initialized, that's equivalent to
232 having the lock, but you cannot use multiple threads.)
233
234*/
235
Nick Coghland6009512014-11-20 21:39:37 +1000236static char*
237get_codec_name(const char *encoding)
238{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200239 const char *name_utf8;
240 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000241 PyObject *codec, *name = NULL;
242
243 codec = _PyCodec_Lookup(encoding);
244 if (!codec)
245 goto error;
246
247 name = _PyObject_GetAttrId(codec, &PyId_name);
248 Py_CLEAR(codec);
249 if (!name)
250 goto error;
251
Serhiy Storchaka06515832016-11-20 09:13:07 +0200252 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000253 if (name_utf8 == NULL)
254 goto error;
255 name_str = _PyMem_RawStrdup(name_utf8);
256 Py_DECREF(name);
257 if (name_str == NULL) {
258 PyErr_NoMemory();
259 return NULL;
260 }
261 return name_str;
262
263error:
264 Py_XDECREF(codec);
265 Py_XDECREF(name);
266 return NULL;
267}
268
269static char*
270get_locale_encoding(void)
271{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700272#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000273 char* codeset = nl_langinfo(CODESET);
274 if (!codeset || codeset[0] == '\0') {
275 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
276 return NULL;
277 }
278 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200279#elif defined(__ANDROID__)
280 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000281#else
282 PyErr_SetNone(PyExc_NotImplementedError);
283 return NULL;
284#endif
285}
286
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800287static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700288initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000289{
290 PyObject *importlib;
291 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000292 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800293 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000294
295 /* Import _importlib through its frozen version, _frozen_importlib. */
296 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800297 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000298 }
299 else if (Py_VerboseFlag) {
300 PySys_FormatStderr("import _frozen_importlib # frozen\n");
301 }
302 importlib = PyImport_AddModule("_frozen_importlib");
303 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800304 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000305 }
306 interp->importlib = importlib;
307 Py_INCREF(interp->importlib);
308
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300309 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
310 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800311 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300312 Py_INCREF(interp->import_func);
313
Victor Stinnercd6e6942015-09-18 09:11:57 +0200314 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800315 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000316 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800317 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000318 }
319 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200320 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000321 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600322 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800323 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000324 }
325
Victor Stinnercd6e6942015-09-18 09:11:57 +0200326 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000327 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
328 if (value == NULL) {
329 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800330 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000331 }
332 Py_DECREF(value);
333 Py_DECREF(impmod);
334
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800335 err = _PyImportZip_Init();
336 if (_Py_INIT_FAILED(err)) {
337 return err;
338 }
339
340 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000341}
342
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800343static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700344initexternalimport(PyInterpreterState *interp)
345{
346 PyObject *value;
347 value = PyObject_CallMethod(interp->importlib,
348 "_install_external_importers", "");
349 if (value == NULL) {
350 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800351 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700352 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200353 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800354 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700355}
Nick Coghland6009512014-11-20 21:39:37 +1000356
Nick Coghlan6ea41862017-06-11 13:16:15 +1000357/* Helper functions to better handle the legacy C locale
358 *
359 * The legacy C locale assumes ASCII as the default text encoding, which
360 * causes problems not only for the CPython runtime, but also other
361 * components like GNU readline.
362 *
363 * Accordingly, when the CLI detects it, it attempts to coerce it to a
364 * more capable UTF-8 based alternative as follows:
365 *
366 * if (_Py_LegacyLocaleDetected()) {
367 * _Py_CoerceLegacyLocale();
368 * }
369 *
370 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
371 *
372 * Locale coercion also impacts the default error handler for the standard
373 * streams: while the usual default is "strict", the default for the legacy
374 * C locale and for any of the coercion target locales is "surrogateescape".
375 */
376
377int
378_Py_LegacyLocaleDetected(void)
379{
380#ifndef MS_WINDOWS
381 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000382 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
383 * the POSIX locale as a simple alias for the C locale, so
384 * we may also want to check for that explicitly.
385 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000386 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
387 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
388#else
389 /* Windows uses code pages instead of locales, so no locale is legacy */
390 return 0;
391#endif
392}
393
Nick Coghlaneb817952017-06-18 12:29:42 +1000394static const char *_C_LOCALE_WARNING =
395 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
396 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
397 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
398 "locales is recommended.\n";
399
Nick Coghlaneb817952017-06-18 12:29:42 +1000400static void
Victor Stinner94540602017-12-16 04:54:22 +0100401_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000402{
Victor Stinner94540602017-12-16 04:54:22 +0100403 if (core_config->coerce_c_locale_warn) {
Nick Coghlaneb817952017-06-18 12:29:42 +1000404 if (_Py_LegacyLocaleDetected()) {
405 fprintf(stderr, "%s", _C_LOCALE_WARNING);
406 }
407 }
408}
409
Nick Coghlan6ea41862017-06-11 13:16:15 +1000410typedef struct _CandidateLocale {
411 const char *locale_name; /* The locale to try as a coercion target */
412} _LocaleCoercionTarget;
413
414static _LocaleCoercionTarget _TARGET_LOCALES[] = {
415 {"C.UTF-8"},
416 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000417 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000418 {NULL}
419};
420
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200421static const char *
Nick Coghlan6ea41862017-06-11 13:16:15 +1000422get_default_standard_stream_error_handler(void)
423{
424 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
425 if (ctype_loc != NULL) {
426 /* "surrogateescape" is the default in the legacy C locale */
427 if (strcmp(ctype_loc, "C") == 0) {
428 return "surrogateescape";
429 }
430
431#ifdef PY_COERCE_C_LOCALE
432 /* "surrogateescape" is the default in locale coercion target locales */
433 const _LocaleCoercionTarget *target = NULL;
434 for (target = _TARGET_LOCALES; target->locale_name; target++) {
435 if (strcmp(ctype_loc, target->locale_name) == 0) {
436 return "surrogateescape";
437 }
438 }
439#endif
440 }
441
442 /* Otherwise return NULL to request the typical default error handler */
443 return NULL;
444}
445
446#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100447static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000448 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
449 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
450
451static void
Victor Stinner94540602017-12-16 04:54:22 +0100452_coerce_default_locale_settings(const _PyCoreConfig *config, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000453{
454 const char *newloc = target->locale_name;
455
456 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100457 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000458
459 /* Set the relevant locale environment variable */
460 if (setenv("LC_CTYPE", newloc, 1)) {
461 fprintf(stderr,
462 "Error setting LC_CTYPE, skipping C locale coercion\n");
463 return;
464 }
Victor Stinner94540602017-12-16 04:54:22 +0100465 if (config->coerce_c_locale_warn) {
466 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000467 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000468
469 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100470 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000471}
472#endif
473
474void
Victor Stinner94540602017-12-16 04:54:22 +0100475_Py_CoerceLegacyLocale(const _PyCoreConfig *config)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000476{
477#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100478 const char *locale_override = getenv("LC_ALL");
479 if (locale_override == NULL || *locale_override == '\0') {
480 /* LC_ALL is also not set (or is set to an empty string) */
481 const _LocaleCoercionTarget *target = NULL;
482 for (target = _TARGET_LOCALES; target->locale_name; target++) {
483 const char *new_locale = setlocale(LC_CTYPE,
484 target->locale_name);
485 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100486#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100487defined(HAVE_LANGINFO_H) && defined(CODESET)
488 /* Also ensure that nl_langinfo works in this locale */
489 char *codeset = nl_langinfo(CODESET);
490 if (!codeset || *codeset == '\0') {
491 /* CODESET is not set or empty, so skip coercion */
492 new_locale = NULL;
493 _Py_SetLocaleFromEnv(LC_CTYPE);
494 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000495 }
Victor Stinner94540602017-12-16 04:54:22 +0100496#endif
497 /* Successfully configured locale, so make it the default */
498 _coerce_default_locale_settings(config, target);
499 return;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000500 }
501 }
502 }
503 /* No C locale warning here, as Py_Initialize will emit one later */
504#endif
505}
506
xdegaye1588be62017-11-12 12:45:59 +0100507/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
508 * isolate the idiosyncrasies of different libc implementations. It reads the
509 * appropriate environment variable and uses its value to select the locale for
510 * 'category'. */
511char *
512_Py_SetLocaleFromEnv(int category)
513{
514#ifdef __ANDROID__
515 const char *locale;
516 const char **pvar;
517#ifdef PY_COERCE_C_LOCALE
518 const char *coerce_c_locale;
519#endif
520 const char *utf8_locale = "C.UTF-8";
521 const char *env_var_set[] = {
522 "LC_ALL",
523 "LC_CTYPE",
524 "LANG",
525 NULL,
526 };
527
528 /* Android setlocale(category, "") doesn't check the environment variables
529 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
530 * check the environment variables listed in env_var_set. */
531 for (pvar=env_var_set; *pvar; pvar++) {
532 locale = getenv(*pvar);
533 if (locale != NULL && *locale != '\0') {
534 if (strcmp(locale, utf8_locale) == 0 ||
535 strcmp(locale, "en_US.UTF-8") == 0) {
536 return setlocale(category, utf8_locale);
537 }
538 return setlocale(category, "C");
539 }
540 }
541
542 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
543 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
544 * Quote from POSIX section "8.2 Internationalization Variables":
545 * "4. If the LANG environment variable is not set or is set to the empty
546 * string, the implementation-defined default locale shall be used." */
547
548#ifdef PY_COERCE_C_LOCALE
549 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
550 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
551 /* Some other ported code may check the environment variables (e.g. in
552 * extension modules), so we make sure that they match the locale
553 * configuration */
554 if (setenv("LC_CTYPE", utf8_locale, 1)) {
555 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
556 "environment variable to %s\n", utf8_locale);
557 }
558 }
559#endif
560 return setlocale(category, utf8_locale);
561#else /* __ANDROID__ */
562 return setlocale(category, "");
563#endif /* __ANDROID__ */
564}
565
Nick Coghlan6ea41862017-06-11 13:16:15 +1000566
Eric Snow1abcf672017-05-23 21:46:51 -0700567/* Global initializations. Can be undone by Py_Finalize(). Don't
568 call this twice without an intervening Py_Finalize() call.
569
570 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
571 must have a corresponding call to Py_Finalize.
572
573 Locking: you must hold the interpreter lock while calling these APIs.
574 (If the lock has not yet been initialized, that's equivalent to
575 having the lock, but you cannot use multiple threads.)
576
577*/
578
579/* Begin interpreter initialization
580 *
581 * On return, the first thread and interpreter state have been created,
582 * but the compiler, signal handling, multithreading and
583 * multiple interpreter support, and codec infrastructure are not yet
584 * available.
585 *
586 * The import system will support builtin and frozen modules only.
587 * The only supported io is writing to sys.stderr
588 *
589 * If any operation invoked by this function fails, a fatal error is
590 * issued and the function does not return.
591 *
592 * Any code invoked from this function should *not* assume it has access
593 * to the Python C API (unless the API is explicitly listed as being
594 * safe to call without calling Py_Initialize first)
595 */
596
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800597_PyInitError
Victor Stinnerda273412017-12-15 01:46:02 +0100598_Py_InitializeCore(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000599{
Victor Stinnerda273412017-12-15 01:46:02 +0100600 assert(core_config != NULL);
601
Nick Coghland6009512014-11-20 21:39:37 +1000602 PyInterpreterState *interp;
603 PyThreadState *tstate;
604 PyObject *bimod, *sysmod, *pstderr;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800605 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000606
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800607 err = _PyRuntime_Initialize();
608 if (_Py_INIT_FAILED(err)) {
609 return err;
610 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600611
Victor Stinner31e99082017-12-20 23:41:38 +0100612 if (core_config->allocator != NULL) {
613 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
614 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
615 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800616 }
617
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600618 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800619 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700620 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600621 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800622 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700623 }
624
625 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
626 * threads behave a little more gracefully at interpreter shutdown.
627 * We clobber it here so the new interpreter can start with a clean
628 * slate.
629 *
630 * However, this may still lead to misbehaviour if there are daemon
631 * threads still hanging around from a previous Py_Initialize/Finalize
632 * pair :(
633 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600634 _PyRuntime.finalizing = NULL;
635
Nick Coghlan6ea41862017-06-11 13:16:15 +1000636#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000637 /* Set up the LC_CTYPE locale, so we can obtain
638 the locale's charset without having to switch
639 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100640 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner94540602017-12-16 04:54:22 +0100641 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000642#endif
Nick Coghland6009512014-11-20 21:39:37 +1000643
Victor Stinnerda273412017-12-15 01:46:02 +0100644 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800645 if (_Py_INIT_FAILED(err)) {
646 return err;
647 }
648
Victor Stinnerda273412017-12-15 01:46:02 +0100649 if (!core_config->use_hash_seed || core_config->hash_seed) {
Eric Snow1abcf672017-05-23 21:46:51 -0700650 /* Random or non-zero hash seed */
651 Py_HashRandomizationFlag = 1;
652 }
Nick Coghland6009512014-11-20 21:39:37 +1000653
Victor Stinnera7368ac2017-11-15 18:11:45 -0800654 err = _PyInterpreterState_Enable(&_PyRuntime);
655 if (_Py_INIT_FAILED(err)) {
656 return err;
657 }
658
Nick Coghland6009512014-11-20 21:39:37 +1000659 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100660 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800661 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100662 }
663
664 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
665 return _Py_INIT_ERR("failed to copy core config");
666 }
Nick Coghland6009512014-11-20 21:39:37 +1000667
668 tstate = PyThreadState_New(interp);
669 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800670 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000671 (void) PyThreadState_Swap(tstate);
672
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000673 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000674 destroying the GIL might fail when it is being referenced from
675 another running thread (see issue #9901).
676 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000677 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000678 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100679
Nick Coghland6009512014-11-20 21:39:37 +1000680 /* Auto-thread-state API */
681 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000682
Victor Stinner2914bb32018-01-29 11:57:45 +0100683 /* Create the GIL */
684 PyEval_InitThreads();
685
Nick Coghland6009512014-11-20 21:39:37 +1000686 _Py_ReadyTypes();
687
688 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800689 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000690
691 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800692 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000693
694 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800695 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000696
697 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800698 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000699
Eric Snowd393c1b2017-09-14 12:18:12 -0600700 PyObject *modules = PyDict_New();
701 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800702 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600703 interp->modules = modules;
704
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800705 err = _PySys_BeginInit(&sysmod);
706 if (_Py_INIT_FAILED(err)) {
707 return err;
708 }
709
Eric Snowd393c1b2017-09-14 12:18:12 -0600710 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800711 if (interp->sysdict == NULL) {
712 return _Py_INIT_ERR("can't initialize sys dict");
713 }
714
Eric Snowd393c1b2017-09-14 12:18:12 -0600715 Py_INCREF(interp->sysdict);
716 PyDict_SetItemString(interp->sysdict, "modules", modules);
717 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000718
719 /* Init Unicode implementation; relies on the codec registry */
720 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800721 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700722
Nick Coghland6009512014-11-20 21:39:37 +1000723 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800724 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000725
726 bimod = _PyBuiltin_Init();
727 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800728 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600729 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000730 interp->builtins = PyModule_GetDict(bimod);
731 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800732 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000733 Py_INCREF(interp->builtins);
734
735 /* initialize builtin exceptions */
736 _PyExc_Init(bimod);
737
Nick Coghland6009512014-11-20 21:39:37 +1000738 /* Set up a preliminary stderr printer until we have enough
739 infrastructure for the io module in place. */
740 pstderr = PyFile_NewStdPrinter(fileno(stderr));
741 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800742 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000743 _PySys_SetObjectId(&PyId_stderr, pstderr);
744 PySys_SetObject("__stderr__", pstderr);
745 Py_DECREF(pstderr);
746
Victor Stinner672b6ba2017-12-06 17:25:50 +0100747 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800748 if (_Py_INIT_FAILED(err)) {
749 return err;
750 }
Nick Coghland6009512014-11-20 21:39:37 +1000751
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800752 err = _PyImportHooks_Init();
753 if (_Py_INIT_FAILED(err)) {
754 return err;
755 }
Nick Coghland6009512014-11-20 21:39:37 +1000756
757 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100758 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100759 return _Py_INIT_ERR("can't initialize warnings");
760 }
Nick Coghland6009512014-11-20 21:39:37 +1000761
Yury Selivanovf23746a2018-01-22 19:11:18 -0500762 if (!_PyContext_Init())
763 return _Py_INIT_ERR("can't init context");
764
Eric Snow1abcf672017-05-23 21:46:51 -0700765 /* This call sets up builtin and frozen import support */
766 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800767 err = initimport(interp, sysmod);
768 if (_Py_INIT_FAILED(err)) {
769 return err;
770 }
Eric Snow1abcf672017-05-23 21:46:51 -0700771 }
772
773 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600774 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800775 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700776}
777
Eric Snowc7ec9982017-05-23 23:00:52 -0700778/* Update interpreter state based on supplied configuration settings
779 *
780 * After calling this function, most of the restrictions on the interpreter
781 * are lifted. The only remaining incomplete settings are those related
782 * to the main module (sys.argv[0], __main__ metadata)
783 *
784 * Calling this when the interpreter is not initializing, is already
785 * initialized or without a valid current thread state is a fatal error.
786 * Other errors should be reported as normal Python exceptions with a
787 * non-zero return code.
788 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800789_PyInitError
790_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700791{
792 PyInterpreterState *interp;
793 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800794 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700795
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600796 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800797 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700798 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600799 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800800 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700801 }
802
Eric Snow1abcf672017-05-23 21:46:51 -0700803 /* Get current thread state and interpreter pointer */
804 tstate = PyThreadState_GET();
805 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800806 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700807 interp = tstate->interp;
808 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800809 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700810
811 /* Now finish configuring the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100812 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
813 return _Py_INIT_ERR("failed to copy main interpreter config");
814 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700815
Eric Snow1abcf672017-05-23 21:46:51 -0700816 if (interp->core_config._disable_importlib) {
817 /* Special mode for freeze_importlib: run with no import system
818 *
819 * This means anything which needs support from extension modules
820 * or pure Python code in the standard library won't work.
821 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600822 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800823 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700824 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100825
Victor Stinner33c377e2017-12-05 15:12:41 +0100826 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800827 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100828 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200829
Victor Stinner41264f12017-12-15 02:05:29 +0100830 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800831 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100832 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800833
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800834 err = initexternalimport(interp);
835 if (_Py_INIT_FAILED(err)) {
836 return err;
837 }
Nick Coghland6009512014-11-20 21:39:37 +1000838
839 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800840 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800841 if (_Py_INIT_FAILED(err)) {
842 return err;
843 }
Nick Coghland6009512014-11-20 21:39:37 +1000844
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800845 err = initfsencoding(interp);
846 if (_Py_INIT_FAILED(err)) {
847 return err;
848 }
Nick Coghland6009512014-11-20 21:39:37 +1000849
Victor Stinner1f151112017-11-23 10:43:14 +0100850 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800851 err = initsigs(); /* Signal handling stuff, including initintr() */
852 if (_Py_INIT_FAILED(err)) {
853 return err;
854 }
855 }
Nick Coghland6009512014-11-20 21:39:37 +1000856
Victor Stinnera7368ac2017-11-15 18:11:45 -0800857 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800858 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000859
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800860 err = add_main_module(interp);
861 if (_Py_INIT_FAILED(err)) {
862 return err;
863 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800864
Victor Stinner91106cd2017-12-13 12:29:09 +0100865 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800866 if (_Py_INIT_FAILED(err)) {
867 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800868 }
Nick Coghland6009512014-11-20 21:39:37 +1000869
870 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100871 if (interp->config.warnoptions != NULL &&
872 PyList_Size(interp->config.warnoptions) > 0)
873 {
Nick Coghland6009512014-11-20 21:39:37 +1000874 PyObject *warnings_module = PyImport_ImportModule("warnings");
875 if (warnings_module == NULL) {
876 fprintf(stderr, "'import warnings' failed; traceback:\n");
877 PyErr_Print();
878 }
879 Py_XDECREF(warnings_module);
880 }
881
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600882 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700883
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800884 if (!Py_NoSiteFlag) {
885 err = initsite(); /* Module site */
886 if (_Py_INIT_FAILED(err)) {
887 return err;
888 }
889 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800890 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000891}
892
Eric Snowc7ec9982017-05-23 23:00:52 -0700893#undef _INIT_DEBUG_PRINT
894
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800895_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700896_Py_InitializeEx_Private(int install_sigs, int install_importlib)
897{
Victor Stinner9cfc0022017-12-20 19:36:46 +0100898 _PyCoreConfig config = _PyCoreConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800899 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700900
Victor Stinner9cfc0022017-12-20 19:36:46 +0100901 config.ignore_environment = Py_IgnoreEnvironmentFlag;
902 config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700903 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800904
Victor Stinner9cfc0022017-12-20 19:36:46 +0100905 err = _PyCoreConfig_Read(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800906 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100907 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800908 }
909
Victor Stinner9cfc0022017-12-20 19:36:46 +0100910 err = _Py_InitializeCore(&config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100911 if (_Py_INIT_FAILED(err)) {
912 goto done;
913 }
914
Victor Stinner9cfc0022017-12-20 19:36:46 +0100915 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
916 err = _PyMainInterpreterConfig_Read(&main_config, &config);
917 if (!_Py_INIT_FAILED(err)) {
918 err = _Py_InitializeMainInterpreter(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800919 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100920 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800921 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100922 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800923 }
924
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100925 err = _Py_INIT_OK();
926
927done:
Victor Stinner9cfc0022017-12-20 19:36:46 +0100928 _PyCoreConfig_Clear(&config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100929 return err;
Eric Snow1abcf672017-05-23 21:46:51 -0700930}
931
932
933void
Nick Coghland6009512014-11-20 21:39:37 +1000934Py_InitializeEx(int install_sigs)
935{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800936 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
937 if (_Py_INIT_FAILED(err)) {
938 _Py_FatalInitError(err);
939 }
Nick Coghland6009512014-11-20 21:39:37 +1000940}
941
942void
943Py_Initialize(void)
944{
945 Py_InitializeEx(1);
946}
947
948
949#ifdef COUNT_ALLOCS
950extern void dump_counts(FILE*);
951#endif
952
953/* Flush stdout and stderr */
954
955static int
956file_is_closed(PyObject *fobj)
957{
958 int r;
959 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
960 if (tmp == NULL) {
961 PyErr_Clear();
962 return 0;
963 }
964 r = PyObject_IsTrue(tmp);
965 Py_DECREF(tmp);
966 if (r < 0)
967 PyErr_Clear();
968 return r > 0;
969}
970
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000971static int
Nick Coghland6009512014-11-20 21:39:37 +1000972flush_std_files(void)
973{
974 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
975 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
976 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000977 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000978
979 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700980 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000981 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000982 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000983 status = -1;
984 }
Nick Coghland6009512014-11-20 21:39:37 +1000985 else
986 Py_DECREF(tmp);
987 }
988
989 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700990 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000991 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000992 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000993 status = -1;
994 }
Nick Coghland6009512014-11-20 21:39:37 +1000995 else
996 Py_DECREF(tmp);
997 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000998
999 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001000}
1001
1002/* Undo the effect of Py_Initialize().
1003
1004 Beware: if multiple interpreter and/or thread states exist, these
1005 are not wiped out; only the current thread and interpreter state
1006 are deleted. But since everything else is deleted, those other
1007 interpreter and thread states should no longer be used.
1008
1009 (XXX We should do better, e.g. wipe out all interpreters and
1010 threads.)
1011
1012 Locking: as above.
1013
1014*/
1015
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001016int
1017Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001018{
1019 PyInterpreterState *interp;
1020 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001021 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001022
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001023 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001024 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001025
1026 wait_for_thread_shutdown();
1027
Marcel Plch776407f2017-12-20 11:17:58 +01001028 /* Get current thread state and interpreter pointer */
1029 tstate = PyThreadState_GET();
1030 interp = tstate->interp;
1031
Nick Coghland6009512014-11-20 21:39:37 +10001032 /* The interpreter is still entirely intact at this point, and the
1033 * exit funcs may be relying on that. In particular, if some thread
1034 * or exit func is still waiting to do an import, the import machinery
1035 * expects Py_IsInitialized() to return true. So don't say the
1036 * interpreter is uninitialized until after the exit funcs have run.
1037 * Note that Threading.py uses an exit func to do a join on all the
1038 * threads created thru it, so this also protects pending imports in
1039 * the threads created via Threading.
1040 */
Nick Coghland6009512014-11-20 21:39:37 +10001041
Marcel Plch776407f2017-12-20 11:17:58 +01001042 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001043
Victor Stinnerda273412017-12-15 01:46:02 +01001044 /* Copy the core config, PyInterpreterState_Delete() free
1045 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001046#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001047 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001048#endif
1049#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001050 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001051#endif
1052#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001053 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001054#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001055
Nick Coghland6009512014-11-20 21:39:37 +10001056 /* Remaining threads (e.g. daemon threads) will automatically exit
1057 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001058 _PyRuntime.finalizing = tstate;
1059 _PyRuntime.initialized = 0;
1060 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001061
Victor Stinnere0deff32015-03-24 13:46:18 +01001062 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001063 if (flush_std_files() < 0) {
1064 status = -1;
1065 }
Nick Coghland6009512014-11-20 21:39:37 +10001066
1067 /* Disable signal handling */
1068 PyOS_FiniInterrupts();
1069
1070 /* Collect garbage. This may call finalizers; it's nice to call these
1071 * before all modules are destroyed.
1072 * XXX If a __del__ or weakref callback is triggered here, and tries to
1073 * XXX import a module, bad things can happen, because Python no
1074 * XXX longer believes it's initialized.
1075 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1076 * XXX is easy to provoke that way. I've also seen, e.g.,
1077 * XXX Exception exceptions.ImportError: 'No module named sha'
1078 * XXX in <function callback at 0x008F5718> ignored
1079 * XXX but I'm unclear on exactly how that one happens. In any case,
1080 * XXX I haven't seen a real-life report of either of these.
1081 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001082 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001083#ifdef COUNT_ALLOCS
1084 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1085 each collection might release some types from the type
1086 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001087 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001088 /* nothing */;
1089#endif
Eric Snowdae02762017-09-14 00:35:58 -07001090
Nick Coghland6009512014-11-20 21:39:37 +10001091 /* Destroy all modules */
1092 PyImport_Cleanup();
1093
Victor Stinnere0deff32015-03-24 13:46:18 +01001094 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001095 if (flush_std_files() < 0) {
1096 status = -1;
1097 }
Nick Coghland6009512014-11-20 21:39:37 +10001098
1099 /* Collect final garbage. This disposes of cycles created by
1100 * class definitions, for example.
1101 * XXX This is disabled because it caused too many problems. If
1102 * XXX a __del__ or weakref callback triggers here, Python code has
1103 * XXX a hard time running, because even the sys module has been
1104 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1105 * XXX One symptom is a sequence of information-free messages
1106 * XXX coming from threads (if a __del__ or callback is invoked,
1107 * XXX other threads can execute too, and any exception they encounter
1108 * XXX triggers a comedy of errors as subsystem after subsystem
1109 * XXX fails to find what it *expects* to find in sys to help report
1110 * XXX the exception and consequent unexpected failures). I've also
1111 * XXX seen segfaults then, after adding print statements to the
1112 * XXX Python code getting called.
1113 */
1114#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001115 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001116#endif
1117
1118 /* Disable tracemalloc after all Python objects have been destroyed,
1119 so it is possible to use tracemalloc in objects destructor. */
1120 _PyTraceMalloc_Fini();
1121
1122 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1123 _PyImport_Fini();
1124
1125 /* Cleanup typeobject.c's internal caches. */
1126 _PyType_Fini();
1127
1128 /* unload faulthandler module */
1129 _PyFaulthandler_Fini();
1130
1131 /* Debugging stuff */
1132#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001133 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001134#endif
1135 /* dump hash stats */
1136 _PyHash_Fini();
1137
Eric Snowdae02762017-09-14 00:35:58 -07001138#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001139 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001140 _PyDebug_PrintTotalRefs();
1141 }
Eric Snowdae02762017-09-14 00:35:58 -07001142#endif
Nick Coghland6009512014-11-20 21:39:37 +10001143
1144#ifdef Py_TRACE_REFS
1145 /* Display all objects still alive -- this can invoke arbitrary
1146 * __repr__ overrides, so requires a mostly-intact interpreter.
1147 * Alas, a lot of stuff may still be alive now that will be cleaned
1148 * up later.
1149 */
Victor Stinnerda273412017-12-15 01:46:02 +01001150 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001151 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001152 }
Nick Coghland6009512014-11-20 21:39:37 +10001153#endif /* Py_TRACE_REFS */
1154
1155 /* Clear interpreter state and all thread states. */
1156 PyInterpreterState_Clear(interp);
1157
1158 /* Now we decref the exception classes. After this point nothing
1159 can raise an exception. That's okay, because each Fini() method
1160 below has been checked to make sure no exceptions are ever
1161 raised.
1162 */
1163
1164 _PyExc_Fini();
1165
1166 /* Sundry finalizers */
1167 PyMethod_Fini();
1168 PyFrame_Fini();
1169 PyCFunction_Fini();
1170 PyTuple_Fini();
1171 PyList_Fini();
1172 PySet_Fini();
1173 PyBytes_Fini();
1174 PyByteArray_Fini();
1175 PyLong_Fini();
1176 PyFloat_Fini();
1177 PyDict_Fini();
1178 PySlice_Fini();
1179 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001180 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001181 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001182 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001183 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001184
1185 /* Cleanup Unicode implementation */
1186 _PyUnicode_Fini();
1187
1188 /* reset file system default encoding */
1189 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1190 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1191 Py_FileSystemDefaultEncoding = NULL;
1192 }
1193
1194 /* XXX Still allocated:
1195 - various static ad-hoc pointers to interned strings
1196 - int and float free list blocks
1197 - whatever various modules and libraries allocate
1198 */
1199
1200 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1201
1202 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001203 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001204
1205 /* Delete current thread. After this, many C API calls become crashy. */
1206 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001207
Nick Coghland6009512014-11-20 21:39:37 +10001208 PyInterpreterState_Delete(interp);
1209
1210#ifdef Py_TRACE_REFS
1211 /* Display addresses (& refcnts) of all objects still alive.
1212 * An address can be used to find the repr of the object, printed
1213 * above by _Py_PrintReferences.
1214 */
Victor Stinnerda273412017-12-15 01:46:02 +01001215 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001216 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001217 }
Nick Coghland6009512014-11-20 21:39:37 +10001218#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001219#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001220 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001221 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001222 }
Nick Coghland6009512014-11-20 21:39:37 +10001223#endif
1224
1225 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001226
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001227 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001228 return status;
1229}
1230
1231void
1232Py_Finalize(void)
1233{
1234 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001235}
1236
1237/* Create and initialize a new interpreter and thread, and return the
1238 new thread. This requires that Py_Initialize() has been called
1239 first.
1240
1241 Unsuccessful initialization yields a NULL pointer. Note that *no*
1242 exception information is available even in this case -- the
1243 exception information is held in the thread, and there is no
1244 thread.
1245
1246 Locking: as above.
1247
1248*/
1249
Victor Stinnera7368ac2017-11-15 18:11:45 -08001250static _PyInitError
1251new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001252{
1253 PyInterpreterState *interp;
1254 PyThreadState *tstate, *save_tstate;
1255 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001256 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001257
Victor Stinnera7368ac2017-11-15 18:11:45 -08001258 if (!_PyRuntime.initialized) {
1259 return _Py_INIT_ERR("Py_Initialize must be called first");
1260 }
Nick Coghland6009512014-11-20 21:39:37 +10001261
Victor Stinner8a1be612016-03-14 22:07:55 +01001262 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1263 interpreters: disable PyGILState_Check(). */
1264 _PyGILState_check_enabled = 0;
1265
Nick Coghland6009512014-11-20 21:39:37 +10001266 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001267 if (interp == NULL) {
1268 *tstate_p = NULL;
1269 return _Py_INIT_OK();
1270 }
Nick Coghland6009512014-11-20 21:39:37 +10001271
1272 tstate = PyThreadState_New(interp);
1273 if (tstate == NULL) {
1274 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001275 *tstate_p = NULL;
1276 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001277 }
1278
1279 save_tstate = PyThreadState_Swap(tstate);
1280
Eric Snow1abcf672017-05-23 21:46:51 -07001281 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001282 _PyCoreConfig *core_config;
1283 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001284 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001285 core_config = &save_tstate->interp->core_config;
1286 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001287 } else {
1288 /* No current thread state, copy from the main interpreter */
1289 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001290 core_config = &main_interp->core_config;
1291 config = &main_interp->config;
1292 }
1293
1294 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1295 return _Py_INIT_ERR("failed to copy core config");
1296 }
1297 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1298 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001299 }
1300
Nick Coghland6009512014-11-20 21:39:37 +10001301 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001302 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001303 if (modules == NULL) {
1304 return _Py_INIT_ERR("can't make modules dictionary");
1305 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001306 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001307
Eric Snowd393c1b2017-09-14 12:18:12 -06001308 sysmod = _PyImport_FindBuiltin("sys", modules);
1309 if (sysmod != NULL) {
1310 interp->sysdict = PyModule_GetDict(sysmod);
1311 if (interp->sysdict == NULL)
1312 goto handle_error;
1313 Py_INCREF(interp->sysdict);
1314 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001315 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001316 }
1317
1318 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001319 if (bimod != NULL) {
1320 interp->builtins = PyModule_GetDict(bimod);
1321 if (interp->builtins == NULL)
1322 goto handle_error;
1323 Py_INCREF(interp->builtins);
1324 }
1325
1326 /* initialize builtin exceptions */
1327 _PyExc_Init(bimod);
1328
Nick Coghland6009512014-11-20 21:39:37 +10001329 if (bimod != NULL && sysmod != NULL) {
1330 PyObject *pstderr;
1331
Nick Coghland6009512014-11-20 21:39:37 +10001332 /* Set up a preliminary stderr printer until we have enough
1333 infrastructure for the io module in place. */
1334 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001335 if (pstderr == NULL) {
1336 return _Py_INIT_ERR("can't set preliminary stderr");
1337 }
Nick Coghland6009512014-11-20 21:39:37 +10001338 _PySys_SetObjectId(&PyId_stderr, pstderr);
1339 PySys_SetObject("__stderr__", pstderr);
1340 Py_DECREF(pstderr);
1341
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001342 err = _PyImportHooks_Init();
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 = initimport(interp, sysmod);
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 = initexternalimport(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 }
Nick Coghland6009512014-11-20 21:39:37 +10001356
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001357 err = initfsencoding(interp);
1358 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001359 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001360 }
1361
Victor Stinner91106cd2017-12-13 12:29:09 +01001362 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001363 if (_Py_INIT_FAILED(err)) {
1364 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001365 }
1366
1367 err = add_main_module(interp);
1368 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001369 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001370 }
1371
1372 if (!Py_NoSiteFlag) {
1373 err = initsite();
1374 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001375 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001376 }
1377 }
Nick Coghland6009512014-11-20 21:39:37 +10001378 }
1379
Victor Stinnera7368ac2017-11-15 18:11:45 -08001380 if (PyErr_Occurred()) {
1381 goto handle_error;
1382 }
Nick Coghland6009512014-11-20 21:39:37 +10001383
Victor Stinnera7368ac2017-11-15 18:11:45 -08001384 *tstate_p = tstate;
1385 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001386
Nick Coghland6009512014-11-20 21:39:37 +10001387handle_error:
1388 /* Oops, it didn't work. Undo it all. */
1389
1390 PyErr_PrintEx(0);
1391 PyThreadState_Clear(tstate);
1392 PyThreadState_Swap(save_tstate);
1393 PyThreadState_Delete(tstate);
1394 PyInterpreterState_Delete(interp);
1395
Victor Stinnera7368ac2017-11-15 18:11:45 -08001396 *tstate_p = NULL;
1397 return _Py_INIT_OK();
1398}
1399
1400PyThreadState *
1401Py_NewInterpreter(void)
1402{
1403 PyThreadState *tstate;
1404 _PyInitError err = new_interpreter(&tstate);
1405 if (_Py_INIT_FAILED(err)) {
1406 _Py_FatalInitError(err);
1407 }
1408 return tstate;
1409
Nick Coghland6009512014-11-20 21:39:37 +10001410}
1411
1412/* Delete an interpreter and its last thread. This requires that the
1413 given thread state is current, that the thread has no remaining
1414 frames, and that it is its interpreter's only remaining thread.
1415 It is a fatal error to violate these constraints.
1416
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001417 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001418 everything, regardless.)
1419
1420 Locking: as above.
1421
1422*/
1423
1424void
1425Py_EndInterpreter(PyThreadState *tstate)
1426{
1427 PyInterpreterState *interp = tstate->interp;
1428
1429 if (tstate != PyThreadState_GET())
1430 Py_FatalError("Py_EndInterpreter: thread is not current");
1431 if (tstate->frame != NULL)
1432 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1433
1434 wait_for_thread_shutdown();
1435
Marcel Plch776407f2017-12-20 11:17:58 +01001436 call_py_exitfuncs(interp);
1437
Nick Coghland6009512014-11-20 21:39:37 +10001438 if (tstate != interp->tstate_head || tstate->next != NULL)
1439 Py_FatalError("Py_EndInterpreter: not the last thread");
1440
1441 PyImport_Cleanup();
1442 PyInterpreterState_Clear(interp);
1443 PyThreadState_Swap(NULL);
1444 PyInterpreterState_Delete(interp);
1445}
1446
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001447/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001448
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001449static _PyInitError
1450add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001451{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001452 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001453 m = PyImport_AddModule("__main__");
1454 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001455 return _Py_INIT_ERR("can't create __main__ module");
1456
Nick Coghland6009512014-11-20 21:39:37 +10001457 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001458 ann_dict = PyDict_New();
1459 if ((ann_dict == NULL) ||
1460 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001461 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001462 }
1463 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001464
Nick Coghland6009512014-11-20 21:39:37 +10001465 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1466 PyObject *bimod = PyImport_ImportModule("builtins");
1467 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001468 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001469 }
1470 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001471 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001472 }
1473 Py_DECREF(bimod);
1474 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001475
Nick Coghland6009512014-11-20 21:39:37 +10001476 /* Main is a little special - imp.is_builtin("__main__") will return
1477 * False, but BuiltinImporter is still the most appropriate initial
1478 * setting for its __loader__ attribute. A more suitable value will
1479 * be set if __main__ gets further initialized later in the startup
1480 * process.
1481 */
1482 loader = PyDict_GetItemString(d, "__loader__");
1483 if (loader == NULL || loader == Py_None) {
1484 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1485 "BuiltinImporter");
1486 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001487 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001488 }
1489 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001490 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001491 }
1492 Py_DECREF(loader);
1493 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001494 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001495}
1496
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001497static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001498initfsencoding(PyInterpreterState *interp)
1499{
1500 PyObject *codec;
1501
Steve Dowercc16be82016-09-08 10:35:16 -07001502#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001503 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001504 Py_FileSystemDefaultEncoding = "mbcs";
1505 Py_FileSystemDefaultEncodeErrors = "replace";
1506 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001507 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001508 Py_FileSystemDefaultEncoding = "utf-8";
1509 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1510 }
1511#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001512 if (Py_FileSystemDefaultEncoding == NULL &&
1513 interp->core_config.utf8_mode)
1514 {
1515 Py_FileSystemDefaultEncoding = "utf-8";
1516 Py_HasFileSystemDefaultEncoding = 1;
1517 }
1518 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001519 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001520 if (Py_FileSystemDefaultEncoding == NULL) {
1521 return _Py_INIT_ERR("Unable to get the locale encoding");
1522 }
Nick Coghland6009512014-11-20 21:39:37 +10001523
1524 Py_HasFileSystemDefaultEncoding = 0;
1525 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001526 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001527 }
Steve Dowercc16be82016-09-08 10:35:16 -07001528#endif
Nick Coghland6009512014-11-20 21:39:37 +10001529
1530 /* the encoding is mbcs, utf-8 or ascii */
1531 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1532 if (!codec) {
1533 /* Such error can only occurs in critical situations: no more
1534 * memory, import a module of the standard library failed,
1535 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001536 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001537 }
1538 Py_DECREF(codec);
1539 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001540 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001541}
1542
1543/* Import the site module (not into __main__ though) */
1544
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001545static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001546initsite(void)
1547{
1548 PyObject *m;
1549 m = PyImport_ImportModule("site");
1550 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001551 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001552 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001553 Py_DECREF(m);
1554 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001555}
1556
Victor Stinner874dbe82015-09-04 17:29:57 +02001557/* Check if a file descriptor is valid or not.
1558 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1559static int
1560is_valid_fd(int fd)
1561{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001562#ifdef __APPLE__
1563 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1564 and the other side of the pipe is closed, dup(1) succeed, whereas
1565 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1566 such error. */
1567 struct stat st;
1568 return (fstat(fd, &st) == 0);
1569#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001570 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001571 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001572 return 0;
1573 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001574 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1575 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1576 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001577 fd2 = dup(fd);
1578 if (fd2 >= 0)
1579 close(fd2);
1580 _Py_END_SUPPRESS_IPH
1581 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001582#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001583}
1584
1585/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001586static PyObject*
1587create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001588 int fd, int write_mode, const char* name,
1589 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001590{
1591 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1592 const char* mode;
1593 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001594 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001595 int buffering, isatty;
1596 _Py_IDENTIFIER(open);
1597 _Py_IDENTIFIER(isatty);
1598 _Py_IDENTIFIER(TextIOWrapper);
1599 _Py_IDENTIFIER(mode);
1600
Victor Stinner874dbe82015-09-04 17:29:57 +02001601 if (!is_valid_fd(fd))
1602 Py_RETURN_NONE;
1603
Nick Coghland6009512014-11-20 21:39:37 +10001604 /* stdin is always opened in buffered mode, first because it shouldn't
1605 make a difference in common use cases, second because TextIOWrapper
1606 depends on the presence of a read1() method which only exists on
1607 buffered streams.
1608 */
1609 if (Py_UnbufferedStdioFlag && write_mode)
1610 buffering = 0;
1611 else
1612 buffering = -1;
1613 if (write_mode)
1614 mode = "wb";
1615 else
1616 mode = "rb";
1617 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1618 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001619 Py_None, Py_None, /* encoding, errors */
1620 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001621 if (buf == NULL)
1622 goto error;
1623
1624 if (buffering) {
1625 _Py_IDENTIFIER(raw);
1626 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1627 if (raw == NULL)
1628 goto error;
1629 }
1630 else {
1631 raw = buf;
1632 Py_INCREF(raw);
1633 }
1634
Steve Dower39294992016-08-30 21:22:36 -07001635#ifdef MS_WINDOWS
1636 /* Windows console IO is always UTF-8 encoded */
1637 if (PyWindowsConsoleIO_Check(raw))
1638 encoding = "utf-8";
1639#endif
1640
Nick Coghland6009512014-11-20 21:39:37 +10001641 text = PyUnicode_FromString(name);
1642 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1643 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001644 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001645 if (res == NULL)
1646 goto error;
1647 isatty = PyObject_IsTrue(res);
1648 Py_DECREF(res);
1649 if (isatty == -1)
1650 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001651 if (Py_UnbufferedStdioFlag)
1652 write_through = Py_True;
1653 else
1654 write_through = Py_False;
1655 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001656 line_buffering = Py_True;
1657 else
1658 line_buffering = Py_False;
1659
1660 Py_CLEAR(raw);
1661 Py_CLEAR(text);
1662
1663#ifdef MS_WINDOWS
1664 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1665 newlines to "\n".
1666 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1667 newline = NULL;
1668#else
1669 /* sys.stdin: split lines at "\n".
1670 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1671 newline = "\n";
1672#endif
1673
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001674 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001675 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001676 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001677 Py_CLEAR(buf);
1678 if (stream == NULL)
1679 goto error;
1680
1681 if (write_mode)
1682 mode = "w";
1683 else
1684 mode = "r";
1685 text = PyUnicode_FromString(mode);
1686 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1687 goto error;
1688 Py_CLEAR(text);
1689 return stream;
1690
1691error:
1692 Py_XDECREF(buf);
1693 Py_XDECREF(stream);
1694 Py_XDECREF(text);
1695 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001696
Victor Stinner874dbe82015-09-04 17:29:57 +02001697 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1698 /* Issue #24891: the file descriptor was closed after the first
1699 is_valid_fd() check was called. Ignore the OSError and set the
1700 stream to None. */
1701 PyErr_Clear();
1702 Py_RETURN_NONE;
1703 }
1704 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001705}
1706
1707/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001708static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001709init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001710{
1711 PyObject *iomod = NULL, *wrapper;
1712 PyObject *bimod = NULL;
1713 PyObject *m;
1714 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001715 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001716 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001717 char *pythonioencoding = NULL;
1718 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001719 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001720
1721 /* Hack to avoid a nasty recursion issue when Python is invoked
1722 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1723 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1724 goto error;
1725 }
1726 Py_DECREF(m);
1727
1728 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1729 goto error;
1730 }
1731 Py_DECREF(m);
1732
1733 if (!(bimod = PyImport_ImportModule("builtins"))) {
1734 goto error;
1735 }
1736
1737 if (!(iomod = PyImport_ImportModule("io"))) {
1738 goto error;
1739 }
1740 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1741 goto error;
1742 }
1743
1744 /* Set builtins.open */
1745 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1746 Py_DECREF(wrapper);
1747 goto error;
1748 }
1749 Py_DECREF(wrapper);
1750
1751 encoding = _Py_StandardStreamEncoding;
1752 errors = _Py_StandardStreamErrors;
1753 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001754 char *opt = Py_GETENV("PYTHONIOENCODING");
1755 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001756 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001757 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001758 if (pythonioencoding == NULL) {
1759 PyErr_NoMemory();
1760 goto error;
1761 }
1762 err = strchr(pythonioencoding, ':');
1763 if (err) {
1764 *err = '\0';
1765 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001766 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001767 errors = err;
1768 }
1769 }
1770 if (*pythonioencoding && !encoding) {
1771 encoding = pythonioencoding;
1772 }
1773 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001774 else if (interp->core_config.utf8_mode) {
1775 encoding = "utf-8";
1776 errors = "surrogateescape";
1777 }
1778
1779 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001780 /* Choose the default error handler based on the current locale */
1781 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001782 }
Nick Coghland6009512014-11-20 21:39:37 +10001783 }
1784
1785 /* Set sys.stdin */
1786 fd = fileno(stdin);
1787 /* Under some conditions stdin, stdout and stderr may not be connected
1788 * and fileno() may point to an invalid file descriptor. For example
1789 * GUI apps don't have valid standard streams by default.
1790 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001791 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1792 if (std == NULL)
1793 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001794 PySys_SetObject("__stdin__", std);
1795 _PySys_SetObjectId(&PyId_stdin, std);
1796 Py_DECREF(std);
1797
1798 /* Set sys.stdout */
1799 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001800 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1801 if (std == NULL)
1802 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001803 PySys_SetObject("__stdout__", std);
1804 _PySys_SetObjectId(&PyId_stdout, std);
1805 Py_DECREF(std);
1806
1807#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1808 /* Set sys.stderr, replaces the preliminary stderr */
1809 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001810 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1811 if (std == NULL)
1812 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001813
1814 /* Same as hack above, pre-import stderr's codec to avoid recursion
1815 when import.c tries to write to stderr in verbose mode. */
1816 encoding_attr = PyObject_GetAttrString(std, "encoding");
1817 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001818 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001819 if (std_encoding != NULL) {
1820 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1821 Py_XDECREF(codec_info);
1822 }
1823 Py_DECREF(encoding_attr);
1824 }
1825 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1826
1827 if (PySys_SetObject("__stderr__", std) < 0) {
1828 Py_DECREF(std);
1829 goto error;
1830 }
1831 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1832 Py_DECREF(std);
1833 goto error;
1834 }
1835 Py_DECREF(std);
1836#endif
1837
Victor Stinnera7368ac2017-11-15 18:11:45 -08001838 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001839
Victor Stinnera7368ac2017-11-15 18:11:45 -08001840error:
1841 res = _Py_INIT_ERR("can't initialize sys standard streams");
1842
Victor Stinner31e99082017-12-20 23:41:38 +01001843 /* Use the same allocator than Py_SetStandardStreamEncoding() */
1844 PyMemAllocatorEx old_alloc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001845done:
Victor Stinner31e99082017-12-20 23:41:38 +01001846 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1847
Nick Coghland6009512014-11-20 21:39:37 +10001848 /* We won't need them anymore. */
1849 if (_Py_StandardStreamEncoding) {
1850 PyMem_RawFree(_Py_StandardStreamEncoding);
1851 _Py_StandardStreamEncoding = NULL;
1852 }
1853 if (_Py_StandardStreamErrors) {
1854 PyMem_RawFree(_Py_StandardStreamErrors);
1855 _Py_StandardStreamErrors = NULL;
1856 }
Victor Stinner31e99082017-12-20 23:41:38 +01001857
1858 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1859
Nick Coghland6009512014-11-20 21:39:37 +10001860 PyMem_Free(pythonioencoding);
1861 Py_XDECREF(bimod);
1862 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001863 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001864}
1865
1866
Victor Stinner10dc4842015-03-24 12:01:30 +01001867static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001868_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001869{
Victor Stinner10dc4842015-03-24 12:01:30 +01001870 fputc('\n', stderr);
1871 fflush(stderr);
1872
1873 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001874 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001875}
Victor Stinner791da1c2016-03-14 16:53:12 +01001876
1877/* Print the current exception (if an exception is set) with its traceback,
1878 or display the current Python stack.
1879
1880 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1881 called on catastrophic cases.
1882
1883 Return 1 if the traceback was displayed, 0 otherwise. */
1884
1885static int
1886_Py_FatalError_PrintExc(int fd)
1887{
1888 PyObject *ferr, *res;
1889 PyObject *exception, *v, *tb;
1890 int has_tb;
1891
1892 if (PyThreadState_GET() == NULL) {
1893 /* The GIL is released: trying to acquire it is likely to deadlock,
1894 just give up. */
1895 return 0;
1896 }
1897
1898 PyErr_Fetch(&exception, &v, &tb);
1899 if (exception == NULL) {
1900 /* No current exception */
1901 return 0;
1902 }
1903
1904 ferr = _PySys_GetObjectId(&PyId_stderr);
1905 if (ferr == NULL || ferr == Py_None) {
1906 /* sys.stderr is not set yet or set to None,
1907 no need to try to display the exception */
1908 return 0;
1909 }
1910
1911 PyErr_NormalizeException(&exception, &v, &tb);
1912 if (tb == NULL) {
1913 tb = Py_None;
1914 Py_INCREF(tb);
1915 }
1916 PyException_SetTraceback(v, tb);
1917 if (exception == NULL) {
1918 /* PyErr_NormalizeException() failed */
1919 return 0;
1920 }
1921
1922 has_tb = (tb != Py_None);
1923 PyErr_Display(exception, v, tb);
1924 Py_XDECREF(exception);
1925 Py_XDECREF(v);
1926 Py_XDECREF(tb);
1927
1928 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001929 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001930 if (res == NULL)
1931 PyErr_Clear();
1932 else
1933 Py_DECREF(res);
1934
1935 return has_tb;
1936}
1937
Nick Coghland6009512014-11-20 21:39:37 +10001938/* Print fatal error message and abort */
1939
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001940#ifdef MS_WINDOWS
1941static void
1942fatal_output_debug(const char *msg)
1943{
1944 /* buffer of 256 bytes allocated on the stack */
1945 WCHAR buffer[256 / sizeof(WCHAR)];
1946 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1947 size_t msglen;
1948
1949 OutputDebugStringW(L"Fatal Python error: ");
1950
1951 msglen = strlen(msg);
1952 while (msglen) {
1953 size_t i;
1954
1955 if (buflen > msglen) {
1956 buflen = msglen;
1957 }
1958
1959 /* Convert the message to wchar_t. This uses a simple one-to-one
1960 conversion, assuming that the this error message actually uses
1961 ASCII only. If this ceases to be true, we will have to convert. */
1962 for (i=0; i < buflen; ++i) {
1963 buffer[i] = msg[i];
1964 }
1965 buffer[i] = L'\0';
1966 OutputDebugStringW(buffer);
1967
1968 msg += buflen;
1969 msglen -= buflen;
1970 }
1971 OutputDebugStringW(L"\n");
1972}
1973#endif
1974
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001975static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001976fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001977{
1978 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001979 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001980
1981 if (reentrant) {
1982 /* Py_FatalError() caused a second fatal error.
1983 Example: flush_std_files() raises a recursion error. */
1984 goto exit;
1985 }
1986 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001987
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001988 fprintf(stderr, "Fatal Python error: ");
1989 if (prefix) {
1990 fputs(prefix, stderr);
1991 fputs(": ", stderr);
1992 }
1993 if (msg) {
1994 fputs(msg, stderr);
1995 }
1996 else {
1997 fprintf(stderr, "<message not set>");
1998 }
1999 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002000 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002001
Victor Stinnere0deff32015-03-24 13:46:18 +01002002 /* Print the exception (if an exception is set) with its traceback,
2003 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002004 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002005 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002006 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002007
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002008 /* The main purpose of faulthandler is to display the traceback.
2009 This function already did its best to display a traceback.
2010 Disable faulthandler to prevent writing a second traceback
2011 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002012 _PyFaulthandler_Fini();
2013
Victor Stinner791da1c2016-03-14 16:53:12 +01002014 /* Check if the current Python thread hold the GIL */
2015 if (PyThreadState_GET() != NULL) {
2016 /* Flush sys.stdout and sys.stderr */
2017 flush_std_files();
2018 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002019
Nick Coghland6009512014-11-20 21:39:37 +10002020#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002021 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002022#endif /* MS_WINDOWS */
2023
2024exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002025 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002026#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002027 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002028#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002029 abort();
2030 }
2031 else {
2032 exit(status);
2033 }
2034}
2035
Victor Stinner19760862017-12-20 01:41:59 +01002036void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002037Py_FatalError(const char *msg)
2038{
2039 fatal_error(NULL, msg, -1);
2040}
2041
Victor Stinner19760862017-12-20 01:41:59 +01002042void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002043_Py_FatalInitError(_PyInitError err)
2044{
2045 /* On "user" error: exit with status 1.
2046 For all other errors, call abort(). */
2047 int status = err.user_err ? 1 : -1;
2048 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002049}
2050
2051/* Clean up and exit */
2052
Victor Stinnerd7292b52016-06-17 12:29:00 +02002053# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002054
Nick Coghland6009512014-11-20 21:39:37 +10002055/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002056void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002057{
Marcel Plch776407f2017-12-20 11:17:58 +01002058 PyThreadState *ts;
2059 PyInterpreterState *is;
Victor Stinnerca719ac2017-12-20 18:00:19 +01002060
Marcel Plch776407f2017-12-20 11:17:58 +01002061 ts = PyThreadState_GET();
2062 is = ts->interp;
2063
Antoine Pitroufc5db952017-12-13 02:29:07 +01002064 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002065 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2066
2067 is->pyexitfunc = func;
2068 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002069}
2070
2071static void
Marcel Plch776407f2017-12-20 11:17:58 +01002072call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002073{
Marcel Plch776407f2017-12-20 11:17:58 +01002074 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002075 return;
2076
Marcel Plch776407f2017-12-20 11:17:58 +01002077 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002078 PyErr_Clear();
2079}
2080
2081/* Wait until threading._shutdown completes, provided
2082 the threading module was imported in the first place.
2083 The shutdown routine will wait until all non-daemon
2084 "threading" threads have completed. */
2085static void
2086wait_for_thread_shutdown(void)
2087{
Nick Coghland6009512014-11-20 21:39:37 +10002088 _Py_IDENTIFIER(_shutdown);
2089 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002090 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002091 if (threading == NULL) {
2092 /* threading not imported */
2093 PyErr_Clear();
2094 return;
2095 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002096 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002097 if (result == NULL) {
2098 PyErr_WriteUnraisable(threading);
2099 }
2100 else {
2101 Py_DECREF(result);
2102 }
2103 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002104}
2105
2106#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002107int Py_AtExit(void (*func)(void))
2108{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002109 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002110 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002111 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002112 return 0;
2113}
2114
2115static void
2116call_ll_exitfuncs(void)
2117{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002118 while (_PyRuntime.nexitfuncs > 0)
2119 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002120
2121 fflush(stdout);
2122 fflush(stderr);
2123}
2124
2125void
2126Py_Exit(int sts)
2127{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002128 if (Py_FinalizeEx() < 0) {
2129 sts = 120;
2130 }
Nick Coghland6009512014-11-20 21:39:37 +10002131
2132 exit(sts);
2133}
2134
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002135static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002136initsigs(void)
2137{
2138#ifdef SIGPIPE
2139 PyOS_setsig(SIGPIPE, SIG_IGN);
2140#endif
2141#ifdef SIGXFZ
2142 PyOS_setsig(SIGXFZ, SIG_IGN);
2143#endif
2144#ifdef SIGXFSZ
2145 PyOS_setsig(SIGXFSZ, SIG_IGN);
2146#endif
2147 PyOS_InitInterrupts(); /* May imply initsignal() */
2148 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002149 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002150 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002151 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002152}
2153
2154
2155/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2156 *
2157 * All of the code in this function must only use async-signal-safe functions,
2158 * listed at `man 7 signal` or
2159 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2160 */
2161void
2162_Py_RestoreSignals(void)
2163{
2164#ifdef SIGPIPE
2165 PyOS_setsig(SIGPIPE, SIG_DFL);
2166#endif
2167#ifdef SIGXFZ
2168 PyOS_setsig(SIGXFZ, SIG_DFL);
2169#endif
2170#ifdef SIGXFSZ
2171 PyOS_setsig(SIGXFSZ, SIG_DFL);
2172#endif
2173}
2174
2175
2176/*
2177 * The file descriptor fd is considered ``interactive'' if either
2178 * a) isatty(fd) is TRUE, or
2179 * b) the -i flag was given, and the filename associated with
2180 * the descriptor is NULL or "<stdin>" or "???".
2181 */
2182int
2183Py_FdIsInteractive(FILE *fp, const char *filename)
2184{
2185 if (isatty((int)fileno(fp)))
2186 return 1;
2187 if (!Py_InteractiveFlag)
2188 return 0;
2189 return (filename == NULL) ||
2190 (strcmp(filename, "<stdin>") == 0) ||
2191 (strcmp(filename, "???") == 0);
2192}
2193
2194
Nick Coghland6009512014-11-20 21:39:37 +10002195/* Wrappers around sigaction() or signal(). */
2196
2197PyOS_sighandler_t
2198PyOS_getsig(int sig)
2199{
2200#ifdef HAVE_SIGACTION
2201 struct sigaction context;
2202 if (sigaction(sig, NULL, &context) == -1)
2203 return SIG_ERR;
2204 return context.sa_handler;
2205#else
2206 PyOS_sighandler_t handler;
2207/* Special signal handling for the secure CRT in Visual Studio 2005 */
2208#if defined(_MSC_VER) && _MSC_VER >= 1400
2209 switch (sig) {
2210 /* Only these signals are valid */
2211 case SIGINT:
2212 case SIGILL:
2213 case SIGFPE:
2214 case SIGSEGV:
2215 case SIGTERM:
2216 case SIGBREAK:
2217 case SIGABRT:
2218 break;
2219 /* Don't call signal() with other values or it will assert */
2220 default:
2221 return SIG_ERR;
2222 }
2223#endif /* _MSC_VER && _MSC_VER >= 1400 */
2224 handler = signal(sig, SIG_IGN);
2225 if (handler != SIG_ERR)
2226 signal(sig, handler);
2227 return handler;
2228#endif
2229}
2230
2231/*
2232 * All of the code in this function must only use async-signal-safe functions,
2233 * listed at `man 7 signal` or
2234 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2235 */
2236PyOS_sighandler_t
2237PyOS_setsig(int sig, PyOS_sighandler_t handler)
2238{
2239#ifdef HAVE_SIGACTION
2240 /* Some code in Modules/signalmodule.c depends on sigaction() being
2241 * used here if HAVE_SIGACTION is defined. Fix that if this code
2242 * changes to invalidate that assumption.
2243 */
2244 struct sigaction context, ocontext;
2245 context.sa_handler = handler;
2246 sigemptyset(&context.sa_mask);
2247 context.sa_flags = 0;
2248 if (sigaction(sig, &context, &ocontext) == -1)
2249 return SIG_ERR;
2250 return ocontext.sa_handler;
2251#else
2252 PyOS_sighandler_t oldhandler;
2253 oldhandler = signal(sig, handler);
2254#ifdef HAVE_SIGINTERRUPT
2255 siginterrupt(sig, 1);
2256#endif
2257 return oldhandler;
2258#endif
2259}
2260
2261#ifdef __cplusplus
2262}
2263#endif