blob: 5db586e15dffc04437d5381f53ae9d037b2d6b41 [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);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200328 if (value != NULL) {
329 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700330 value = PyObject_CallMethod(importlib,
331 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200332 }
Nick Coghland6009512014-11-20 21:39:37 +1000333 if (value == NULL) {
334 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800335 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000336 }
337 Py_DECREF(value);
338 Py_DECREF(impmod);
339
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800340 err = _PyImportZip_Init();
341 if (_Py_INIT_FAILED(err)) {
342 return err;
343 }
344
345 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000346}
347
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800348static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700349initexternalimport(PyInterpreterState *interp)
350{
351 PyObject *value;
352 value = PyObject_CallMethod(interp->importlib,
353 "_install_external_importers", "");
354 if (value == NULL) {
355 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800356 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700357 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200358 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800359 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700360}
Nick Coghland6009512014-11-20 21:39:37 +1000361
Nick Coghlan6ea41862017-06-11 13:16:15 +1000362/* Helper functions to better handle the legacy C locale
363 *
364 * The legacy C locale assumes ASCII as the default text encoding, which
365 * causes problems not only for the CPython runtime, but also other
366 * components like GNU readline.
367 *
368 * Accordingly, when the CLI detects it, it attempts to coerce it to a
369 * more capable UTF-8 based alternative as follows:
370 *
371 * if (_Py_LegacyLocaleDetected()) {
372 * _Py_CoerceLegacyLocale();
373 * }
374 *
375 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
376 *
377 * Locale coercion also impacts the default error handler for the standard
378 * streams: while the usual default is "strict", the default for the legacy
379 * C locale and for any of the coercion target locales is "surrogateescape".
380 */
381
382int
383_Py_LegacyLocaleDetected(void)
384{
385#ifndef MS_WINDOWS
386 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000387 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
388 * the POSIX locale as a simple alias for the C locale, so
389 * we may also want to check for that explicitly.
390 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000391 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
392 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
393#else
394 /* Windows uses code pages instead of locales, so no locale is legacy */
395 return 0;
396#endif
397}
398
Nick Coghlaneb817952017-06-18 12:29:42 +1000399static const char *_C_LOCALE_WARNING =
400 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
401 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
402 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
403 "locales is recommended.\n";
404
Nick Coghlaneb817952017-06-18 12:29:42 +1000405static void
Victor Stinner94540602017-12-16 04:54:22 +0100406_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000407{
Victor Stinner94540602017-12-16 04:54:22 +0100408 if (core_config->coerce_c_locale_warn) {
Nick Coghlaneb817952017-06-18 12:29:42 +1000409 if (_Py_LegacyLocaleDetected()) {
410 fprintf(stderr, "%s", _C_LOCALE_WARNING);
411 }
412 }
413}
414
Nick Coghlan6ea41862017-06-11 13:16:15 +1000415typedef struct _CandidateLocale {
416 const char *locale_name; /* The locale to try as a coercion target */
417} _LocaleCoercionTarget;
418
419static _LocaleCoercionTarget _TARGET_LOCALES[] = {
420 {"C.UTF-8"},
421 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000422 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000423 {NULL}
424};
425
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200426static const char *
Nick Coghlan6ea41862017-06-11 13:16:15 +1000427get_default_standard_stream_error_handler(void)
428{
429 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
430 if (ctype_loc != NULL) {
431 /* "surrogateescape" is the default in the legacy C locale */
432 if (strcmp(ctype_loc, "C") == 0) {
433 return "surrogateescape";
434 }
435
436#ifdef PY_COERCE_C_LOCALE
437 /* "surrogateescape" is the default in locale coercion target locales */
438 const _LocaleCoercionTarget *target = NULL;
439 for (target = _TARGET_LOCALES; target->locale_name; target++) {
440 if (strcmp(ctype_loc, target->locale_name) == 0) {
441 return "surrogateescape";
442 }
443 }
444#endif
445 }
446
447 /* Otherwise return NULL to request the typical default error handler */
448 return NULL;
449}
450
451#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100452static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000453 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
454 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
455
456static void
Victor Stinner94540602017-12-16 04:54:22 +0100457_coerce_default_locale_settings(const _PyCoreConfig *config, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000458{
459 const char *newloc = target->locale_name;
460
461 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100462 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000463
464 /* Set the relevant locale environment variable */
465 if (setenv("LC_CTYPE", newloc, 1)) {
466 fprintf(stderr,
467 "Error setting LC_CTYPE, skipping C locale coercion\n");
468 return;
469 }
Victor Stinner94540602017-12-16 04:54:22 +0100470 if (config->coerce_c_locale_warn) {
471 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000472 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000473
474 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100475 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000476}
477#endif
478
479void
Victor Stinner94540602017-12-16 04:54:22 +0100480_Py_CoerceLegacyLocale(const _PyCoreConfig *config)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000481{
482#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100483 const char *locale_override = getenv("LC_ALL");
484 if (locale_override == NULL || *locale_override == '\0') {
485 /* LC_ALL is also not set (or is set to an empty string) */
486 const _LocaleCoercionTarget *target = NULL;
487 for (target = _TARGET_LOCALES; target->locale_name; target++) {
488 const char *new_locale = setlocale(LC_CTYPE,
489 target->locale_name);
490 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100491#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100492defined(HAVE_LANGINFO_H) && defined(CODESET)
493 /* Also ensure that nl_langinfo works in this locale */
494 char *codeset = nl_langinfo(CODESET);
495 if (!codeset || *codeset == '\0') {
496 /* CODESET is not set or empty, so skip coercion */
497 new_locale = NULL;
498 _Py_SetLocaleFromEnv(LC_CTYPE);
499 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000500 }
Victor Stinner94540602017-12-16 04:54:22 +0100501#endif
502 /* Successfully configured locale, so make it the default */
503 _coerce_default_locale_settings(config, target);
504 return;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000505 }
506 }
507 }
508 /* No C locale warning here, as Py_Initialize will emit one later */
509#endif
510}
511
xdegaye1588be62017-11-12 12:45:59 +0100512/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
513 * isolate the idiosyncrasies of different libc implementations. It reads the
514 * appropriate environment variable and uses its value to select the locale for
515 * 'category'. */
516char *
517_Py_SetLocaleFromEnv(int category)
518{
519#ifdef __ANDROID__
520 const char *locale;
521 const char **pvar;
522#ifdef PY_COERCE_C_LOCALE
523 const char *coerce_c_locale;
524#endif
525 const char *utf8_locale = "C.UTF-8";
526 const char *env_var_set[] = {
527 "LC_ALL",
528 "LC_CTYPE",
529 "LANG",
530 NULL,
531 };
532
533 /* Android setlocale(category, "") doesn't check the environment variables
534 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
535 * check the environment variables listed in env_var_set. */
536 for (pvar=env_var_set; *pvar; pvar++) {
537 locale = getenv(*pvar);
538 if (locale != NULL && *locale != '\0') {
539 if (strcmp(locale, utf8_locale) == 0 ||
540 strcmp(locale, "en_US.UTF-8") == 0) {
541 return setlocale(category, utf8_locale);
542 }
543 return setlocale(category, "C");
544 }
545 }
546
547 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
548 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
549 * Quote from POSIX section "8.2 Internationalization Variables":
550 * "4. If the LANG environment variable is not set or is set to the empty
551 * string, the implementation-defined default locale shall be used." */
552
553#ifdef PY_COERCE_C_LOCALE
554 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
555 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
556 /* Some other ported code may check the environment variables (e.g. in
557 * extension modules), so we make sure that they match the locale
558 * configuration */
559 if (setenv("LC_CTYPE", utf8_locale, 1)) {
560 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
561 "environment variable to %s\n", utf8_locale);
562 }
563 }
564#endif
565 return setlocale(category, utf8_locale);
566#else /* __ANDROID__ */
567 return setlocale(category, "");
568#endif /* __ANDROID__ */
569}
570
Nick Coghlan6ea41862017-06-11 13:16:15 +1000571
Eric Snow1abcf672017-05-23 21:46:51 -0700572/* Global initializations. Can be undone by Py_Finalize(). Don't
573 call this twice without an intervening Py_Finalize() call.
574
575 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
576 must have a corresponding call to Py_Finalize.
577
578 Locking: you must hold the interpreter lock while calling these APIs.
579 (If the lock has not yet been initialized, that's equivalent to
580 having the lock, but you cannot use multiple threads.)
581
582*/
583
584/* Begin interpreter initialization
585 *
586 * On return, the first thread and interpreter state have been created,
587 * but the compiler, signal handling, multithreading and
588 * multiple interpreter support, and codec infrastructure are not yet
589 * available.
590 *
591 * The import system will support builtin and frozen modules only.
592 * The only supported io is writing to sys.stderr
593 *
594 * If any operation invoked by this function fails, a fatal error is
595 * issued and the function does not return.
596 *
597 * Any code invoked from this function should *not* assume it has access
598 * to the Python C API (unless the API is explicitly listed as being
599 * safe to call without calling Py_Initialize first)
600 */
601
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800602_PyInitError
Victor Stinnerda273412017-12-15 01:46:02 +0100603_Py_InitializeCore(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000604{
Victor Stinnerda273412017-12-15 01:46:02 +0100605 assert(core_config != NULL);
606
Nick Coghland6009512014-11-20 21:39:37 +1000607 PyInterpreterState *interp;
608 PyThreadState *tstate;
609 PyObject *bimod, *sysmod, *pstderr;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800610 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000611
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800612 err = _PyRuntime_Initialize();
613 if (_Py_INIT_FAILED(err)) {
614 return err;
615 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600616
Victor Stinner31e99082017-12-20 23:41:38 +0100617 if (core_config->allocator != NULL) {
618 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
619 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
620 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800621 }
622
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600623 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800624 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700625 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600626 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800627 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700628 }
629
630 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
631 * threads behave a little more gracefully at interpreter shutdown.
632 * We clobber it here so the new interpreter can start with a clean
633 * slate.
634 *
635 * However, this may still lead to misbehaviour if there are daemon
636 * threads still hanging around from a previous Py_Initialize/Finalize
637 * pair :(
638 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600639 _PyRuntime.finalizing = NULL;
640
Nick Coghlan6ea41862017-06-11 13:16:15 +1000641#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000642 /* Set up the LC_CTYPE locale, so we can obtain
643 the locale's charset without having to switch
644 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100645 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner94540602017-12-16 04:54:22 +0100646 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000647#endif
Nick Coghland6009512014-11-20 21:39:37 +1000648
Victor Stinnerda273412017-12-15 01:46:02 +0100649 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800650 if (_Py_INIT_FAILED(err)) {
651 return err;
652 }
653
Victor Stinnerda273412017-12-15 01:46:02 +0100654 if (!core_config->use_hash_seed || core_config->hash_seed) {
Eric Snow1abcf672017-05-23 21:46:51 -0700655 /* Random or non-zero hash seed */
656 Py_HashRandomizationFlag = 1;
657 }
Nick Coghland6009512014-11-20 21:39:37 +1000658
Victor Stinnera7368ac2017-11-15 18:11:45 -0800659 err = _PyInterpreterState_Enable(&_PyRuntime);
660 if (_Py_INIT_FAILED(err)) {
661 return err;
662 }
663
Nick Coghland6009512014-11-20 21:39:37 +1000664 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100665 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800666 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100667 }
668
669 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
670 return _Py_INIT_ERR("failed to copy core config");
671 }
Nick Coghland6009512014-11-20 21:39:37 +1000672
673 tstate = PyThreadState_New(interp);
674 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800675 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000676 (void) PyThreadState_Swap(tstate);
677
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000678 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000679 destroying the GIL might fail when it is being referenced from
680 another running thread (see issue #9901).
681 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000682 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000683 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100684
Nick Coghland6009512014-11-20 21:39:37 +1000685 /* Auto-thread-state API */
686 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000687
Victor Stinner2914bb32018-01-29 11:57:45 +0100688 /* Create the GIL */
689 PyEval_InitThreads();
690
Nick Coghland6009512014-11-20 21:39:37 +1000691 _Py_ReadyTypes();
692
693 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800694 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000695
696 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800697 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000698
699 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800700 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000701
702 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800703 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000704
Eric Snowd393c1b2017-09-14 12:18:12 -0600705 PyObject *modules = PyDict_New();
706 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800707 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600708 interp->modules = modules;
709
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800710 err = _PySys_BeginInit(&sysmod);
711 if (_Py_INIT_FAILED(err)) {
712 return err;
713 }
714
Eric Snowd393c1b2017-09-14 12:18:12 -0600715 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800716 if (interp->sysdict == NULL) {
717 return _Py_INIT_ERR("can't initialize sys dict");
718 }
719
Eric Snowd393c1b2017-09-14 12:18:12 -0600720 Py_INCREF(interp->sysdict);
721 PyDict_SetItemString(interp->sysdict, "modules", modules);
722 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000723
724 /* Init Unicode implementation; relies on the codec registry */
725 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800726 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700727
Nick Coghland6009512014-11-20 21:39:37 +1000728 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800729 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000730
731 bimod = _PyBuiltin_Init();
732 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800733 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600734 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000735 interp->builtins = PyModule_GetDict(bimod);
736 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800737 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000738 Py_INCREF(interp->builtins);
739
740 /* initialize builtin exceptions */
741 _PyExc_Init(bimod);
742
Nick Coghland6009512014-11-20 21:39:37 +1000743 /* Set up a preliminary stderr printer until we have enough
744 infrastructure for the io module in place. */
745 pstderr = PyFile_NewStdPrinter(fileno(stderr));
746 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800747 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000748 _PySys_SetObjectId(&PyId_stderr, pstderr);
749 PySys_SetObject("__stderr__", pstderr);
750 Py_DECREF(pstderr);
751
Victor Stinner672b6ba2017-12-06 17:25:50 +0100752 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800753 if (_Py_INIT_FAILED(err)) {
754 return err;
755 }
Nick Coghland6009512014-11-20 21:39:37 +1000756
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800757 err = _PyImportHooks_Init();
758 if (_Py_INIT_FAILED(err)) {
759 return err;
760 }
Nick Coghland6009512014-11-20 21:39:37 +1000761
762 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100763 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100764 return _Py_INIT_ERR("can't initialize warnings");
765 }
Nick Coghland6009512014-11-20 21:39:37 +1000766
Yury Selivanovf23746a2018-01-22 19:11:18 -0500767 if (!_PyContext_Init())
768 return _Py_INIT_ERR("can't init context");
769
Eric Snow1abcf672017-05-23 21:46:51 -0700770 /* This call sets up builtin and frozen import support */
771 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800772 err = initimport(interp, sysmod);
773 if (_Py_INIT_FAILED(err)) {
774 return err;
775 }
Eric Snow1abcf672017-05-23 21:46:51 -0700776 }
777
778 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600779 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800780 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700781}
782
Eric Snowc7ec9982017-05-23 23:00:52 -0700783/* Update interpreter state based on supplied configuration settings
784 *
785 * After calling this function, most of the restrictions on the interpreter
786 * are lifted. The only remaining incomplete settings are those related
787 * to the main module (sys.argv[0], __main__ metadata)
788 *
789 * Calling this when the interpreter is not initializing, is already
790 * initialized or without a valid current thread state is a fatal error.
791 * Other errors should be reported as normal Python exceptions with a
792 * non-zero return code.
793 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800794_PyInitError
795_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700796{
797 PyInterpreterState *interp;
798 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800799 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700800
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600801 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800802 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700803 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600804 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800805 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700806 }
807
Eric Snow1abcf672017-05-23 21:46:51 -0700808 /* Get current thread state and interpreter pointer */
809 tstate = PyThreadState_GET();
810 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800811 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700812 interp = tstate->interp;
813 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800814 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700815
816 /* Now finish configuring the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100817 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
818 return _Py_INIT_ERR("failed to copy main interpreter config");
819 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700820
Eric Snow1abcf672017-05-23 21:46:51 -0700821 if (interp->core_config._disable_importlib) {
822 /* Special mode for freeze_importlib: run with no import system
823 *
824 * This means anything which needs support from extension modules
825 * or pure Python code in the standard library won't work.
826 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600827 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800828 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700829 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100830
Victor Stinner33c377e2017-12-05 15:12:41 +0100831 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800832 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100833 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200834
Victor Stinner41264f12017-12-15 02:05:29 +0100835 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800836 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100837 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800838
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800839 err = initexternalimport(interp);
840 if (_Py_INIT_FAILED(err)) {
841 return err;
842 }
Nick Coghland6009512014-11-20 21:39:37 +1000843
844 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800845 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800846 if (_Py_INIT_FAILED(err)) {
847 return err;
848 }
Nick Coghland6009512014-11-20 21:39:37 +1000849
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800850 err = initfsencoding(interp);
851 if (_Py_INIT_FAILED(err)) {
852 return err;
853 }
Nick Coghland6009512014-11-20 21:39:37 +1000854
Victor Stinner1f151112017-11-23 10:43:14 +0100855 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800856 err = initsigs(); /* Signal handling stuff, including initintr() */
857 if (_Py_INIT_FAILED(err)) {
858 return err;
859 }
860 }
Nick Coghland6009512014-11-20 21:39:37 +1000861
Victor Stinnera7368ac2017-11-15 18:11:45 -0800862 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800863 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000864
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800865 err = add_main_module(interp);
866 if (_Py_INIT_FAILED(err)) {
867 return err;
868 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800869
Victor Stinner91106cd2017-12-13 12:29:09 +0100870 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800871 if (_Py_INIT_FAILED(err)) {
872 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800873 }
Nick Coghland6009512014-11-20 21:39:37 +1000874
875 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100876 if (interp->config.warnoptions != NULL &&
877 PyList_Size(interp->config.warnoptions) > 0)
878 {
Nick Coghland6009512014-11-20 21:39:37 +1000879 PyObject *warnings_module = PyImport_ImportModule("warnings");
880 if (warnings_module == NULL) {
881 fprintf(stderr, "'import warnings' failed; traceback:\n");
882 PyErr_Print();
883 }
884 Py_XDECREF(warnings_module);
885 }
886
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600887 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700888
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800889 if (!Py_NoSiteFlag) {
890 err = initsite(); /* Module site */
891 if (_Py_INIT_FAILED(err)) {
892 return err;
893 }
894 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800895 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000896}
897
Eric Snowc7ec9982017-05-23 23:00:52 -0700898#undef _INIT_DEBUG_PRINT
899
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800900_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700901_Py_InitializeEx_Private(int install_sigs, int install_importlib)
902{
Victor Stinner9cfc0022017-12-20 19:36:46 +0100903 _PyCoreConfig config = _PyCoreConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800904 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700905
Victor Stinner9cfc0022017-12-20 19:36:46 +0100906 config.ignore_environment = Py_IgnoreEnvironmentFlag;
907 config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700908 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800909
Victor Stinner9cfc0022017-12-20 19:36:46 +0100910 err = _PyCoreConfig_Read(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800911 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100912 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 }
914
Victor Stinner9cfc0022017-12-20 19:36:46 +0100915 err = _Py_InitializeCore(&config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100916 if (_Py_INIT_FAILED(err)) {
917 goto done;
918 }
919
Victor Stinner9cfc0022017-12-20 19:36:46 +0100920 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
921 err = _PyMainInterpreterConfig_Read(&main_config, &config);
922 if (!_Py_INIT_FAILED(err)) {
923 err = _Py_InitializeMainInterpreter(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800924 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100925 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800926 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100927 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800928 }
929
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100930 err = _Py_INIT_OK();
931
932done:
Victor Stinner9cfc0022017-12-20 19:36:46 +0100933 _PyCoreConfig_Clear(&config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100934 return err;
Eric Snow1abcf672017-05-23 21:46:51 -0700935}
936
937
938void
Nick Coghland6009512014-11-20 21:39:37 +1000939Py_InitializeEx(int install_sigs)
940{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800941 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
942 if (_Py_INIT_FAILED(err)) {
943 _Py_FatalInitError(err);
944 }
Nick Coghland6009512014-11-20 21:39:37 +1000945}
946
947void
948Py_Initialize(void)
949{
950 Py_InitializeEx(1);
951}
952
953
954#ifdef COUNT_ALLOCS
955extern void dump_counts(FILE*);
956#endif
957
958/* Flush stdout and stderr */
959
960static int
961file_is_closed(PyObject *fobj)
962{
963 int r;
964 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
965 if (tmp == NULL) {
966 PyErr_Clear();
967 return 0;
968 }
969 r = PyObject_IsTrue(tmp);
970 Py_DECREF(tmp);
971 if (r < 0)
972 PyErr_Clear();
973 return r > 0;
974}
975
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000976static int
Nick Coghland6009512014-11-20 21:39:37 +1000977flush_std_files(void)
978{
979 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
980 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
981 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000982 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000983
984 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700985 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000986 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000987 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000988 status = -1;
989 }
Nick Coghland6009512014-11-20 21:39:37 +1000990 else
991 Py_DECREF(tmp);
992 }
993
994 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700995 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000996 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000997 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000998 status = -1;
999 }
Nick Coghland6009512014-11-20 21:39:37 +10001000 else
1001 Py_DECREF(tmp);
1002 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001003
1004 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001005}
1006
1007/* Undo the effect of Py_Initialize().
1008
1009 Beware: if multiple interpreter and/or thread states exist, these
1010 are not wiped out; only the current thread and interpreter state
1011 are deleted. But since everything else is deleted, those other
1012 interpreter and thread states should no longer be used.
1013
1014 (XXX We should do better, e.g. wipe out all interpreters and
1015 threads.)
1016
1017 Locking: as above.
1018
1019*/
1020
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001021int
1022Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001023{
1024 PyInterpreterState *interp;
1025 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001026 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001027
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001028 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001029 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001030
1031 wait_for_thread_shutdown();
1032
Marcel Plch776407f2017-12-20 11:17:58 +01001033 /* Get current thread state and interpreter pointer */
1034 tstate = PyThreadState_GET();
1035 interp = tstate->interp;
1036
Nick Coghland6009512014-11-20 21:39:37 +10001037 /* The interpreter is still entirely intact at this point, and the
1038 * exit funcs may be relying on that. In particular, if some thread
1039 * or exit func is still waiting to do an import, the import machinery
1040 * expects Py_IsInitialized() to return true. So don't say the
1041 * interpreter is uninitialized until after the exit funcs have run.
1042 * Note that Threading.py uses an exit func to do a join on all the
1043 * threads created thru it, so this also protects pending imports in
1044 * the threads created via Threading.
1045 */
Nick Coghland6009512014-11-20 21:39:37 +10001046
Marcel Plch776407f2017-12-20 11:17:58 +01001047 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001048
Victor Stinnerda273412017-12-15 01:46:02 +01001049 /* Copy the core config, PyInterpreterState_Delete() free
1050 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001051#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001052 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001053#endif
1054#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001055 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001056#endif
1057#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001058 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001059#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001060
Nick Coghland6009512014-11-20 21:39:37 +10001061 /* Remaining threads (e.g. daemon threads) will automatically exit
1062 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001063 _PyRuntime.finalizing = tstate;
1064 _PyRuntime.initialized = 0;
1065 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001066
Victor Stinnere0deff32015-03-24 13:46:18 +01001067 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001068 if (flush_std_files() < 0) {
1069 status = -1;
1070 }
Nick Coghland6009512014-11-20 21:39:37 +10001071
1072 /* Disable signal handling */
1073 PyOS_FiniInterrupts();
1074
1075 /* Collect garbage. This may call finalizers; it's nice to call these
1076 * before all modules are destroyed.
1077 * XXX If a __del__ or weakref callback is triggered here, and tries to
1078 * XXX import a module, bad things can happen, because Python no
1079 * XXX longer believes it's initialized.
1080 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1081 * XXX is easy to provoke that way. I've also seen, e.g.,
1082 * XXX Exception exceptions.ImportError: 'No module named sha'
1083 * XXX in <function callback at 0x008F5718> ignored
1084 * XXX but I'm unclear on exactly how that one happens. In any case,
1085 * XXX I haven't seen a real-life report of either of these.
1086 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001087 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001088#ifdef COUNT_ALLOCS
1089 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1090 each collection might release some types from the type
1091 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001092 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001093 /* nothing */;
1094#endif
Eric Snowdae02762017-09-14 00:35:58 -07001095
Nick Coghland6009512014-11-20 21:39:37 +10001096 /* Destroy all modules */
1097 PyImport_Cleanup();
1098
Victor Stinnere0deff32015-03-24 13:46:18 +01001099 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001100 if (flush_std_files() < 0) {
1101 status = -1;
1102 }
Nick Coghland6009512014-11-20 21:39:37 +10001103
1104 /* Collect final garbage. This disposes of cycles created by
1105 * class definitions, for example.
1106 * XXX This is disabled because it caused too many problems. If
1107 * XXX a __del__ or weakref callback triggers here, Python code has
1108 * XXX a hard time running, because even the sys module has been
1109 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1110 * XXX One symptom is a sequence of information-free messages
1111 * XXX coming from threads (if a __del__ or callback is invoked,
1112 * XXX other threads can execute too, and any exception they encounter
1113 * XXX triggers a comedy of errors as subsystem after subsystem
1114 * XXX fails to find what it *expects* to find in sys to help report
1115 * XXX the exception and consequent unexpected failures). I've also
1116 * XXX seen segfaults then, after adding print statements to the
1117 * XXX Python code getting called.
1118 */
1119#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001120 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001121#endif
1122
1123 /* Disable tracemalloc after all Python objects have been destroyed,
1124 so it is possible to use tracemalloc in objects destructor. */
1125 _PyTraceMalloc_Fini();
1126
1127 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1128 _PyImport_Fini();
1129
1130 /* Cleanup typeobject.c's internal caches. */
1131 _PyType_Fini();
1132
1133 /* unload faulthandler module */
1134 _PyFaulthandler_Fini();
1135
1136 /* Debugging stuff */
1137#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001138 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001139#endif
1140 /* dump hash stats */
1141 _PyHash_Fini();
1142
Eric Snowdae02762017-09-14 00:35:58 -07001143#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001144 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001145 _PyDebug_PrintTotalRefs();
1146 }
Eric Snowdae02762017-09-14 00:35:58 -07001147#endif
Nick Coghland6009512014-11-20 21:39:37 +10001148
1149#ifdef Py_TRACE_REFS
1150 /* Display all objects still alive -- this can invoke arbitrary
1151 * __repr__ overrides, so requires a mostly-intact interpreter.
1152 * Alas, a lot of stuff may still be alive now that will be cleaned
1153 * up later.
1154 */
Victor Stinnerda273412017-12-15 01:46:02 +01001155 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001156 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001157 }
Nick Coghland6009512014-11-20 21:39:37 +10001158#endif /* Py_TRACE_REFS */
1159
1160 /* Clear interpreter state and all thread states. */
1161 PyInterpreterState_Clear(interp);
1162
1163 /* Now we decref the exception classes. After this point nothing
1164 can raise an exception. That's okay, because each Fini() method
1165 below has been checked to make sure no exceptions are ever
1166 raised.
1167 */
1168
1169 _PyExc_Fini();
1170
1171 /* Sundry finalizers */
1172 PyMethod_Fini();
1173 PyFrame_Fini();
1174 PyCFunction_Fini();
1175 PyTuple_Fini();
1176 PyList_Fini();
1177 PySet_Fini();
1178 PyBytes_Fini();
1179 PyByteArray_Fini();
1180 PyLong_Fini();
1181 PyFloat_Fini();
1182 PyDict_Fini();
1183 PySlice_Fini();
1184 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001185 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001186 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001187 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001188 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001189
1190 /* Cleanup Unicode implementation */
1191 _PyUnicode_Fini();
1192
1193 /* reset file system default encoding */
1194 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1195 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1196 Py_FileSystemDefaultEncoding = NULL;
1197 }
1198
1199 /* XXX Still allocated:
1200 - various static ad-hoc pointers to interned strings
1201 - int and float free list blocks
1202 - whatever various modules and libraries allocate
1203 */
1204
1205 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1206
1207 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001208 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001209
1210 /* Delete current thread. After this, many C API calls become crashy. */
1211 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001212
Nick Coghland6009512014-11-20 21:39:37 +10001213 PyInterpreterState_Delete(interp);
1214
1215#ifdef Py_TRACE_REFS
1216 /* Display addresses (& refcnts) of all objects still alive.
1217 * An address can be used to find the repr of the object, printed
1218 * above by _Py_PrintReferences.
1219 */
Victor Stinnerda273412017-12-15 01:46:02 +01001220 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001221 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001222 }
Nick Coghland6009512014-11-20 21:39:37 +10001223#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001224#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001225 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001226 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001227 }
Nick Coghland6009512014-11-20 21:39:37 +10001228#endif
1229
1230 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001231
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001232 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001233 return status;
1234}
1235
1236void
1237Py_Finalize(void)
1238{
1239 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001240}
1241
1242/* Create and initialize a new interpreter and thread, and return the
1243 new thread. This requires that Py_Initialize() has been called
1244 first.
1245
1246 Unsuccessful initialization yields a NULL pointer. Note that *no*
1247 exception information is available even in this case -- the
1248 exception information is held in the thread, and there is no
1249 thread.
1250
1251 Locking: as above.
1252
1253*/
1254
Victor Stinnera7368ac2017-11-15 18:11:45 -08001255static _PyInitError
1256new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001257{
1258 PyInterpreterState *interp;
1259 PyThreadState *tstate, *save_tstate;
1260 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001261 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001262
Victor Stinnera7368ac2017-11-15 18:11:45 -08001263 if (!_PyRuntime.initialized) {
1264 return _Py_INIT_ERR("Py_Initialize must be called first");
1265 }
Nick Coghland6009512014-11-20 21:39:37 +10001266
Victor Stinner8a1be612016-03-14 22:07:55 +01001267 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1268 interpreters: disable PyGILState_Check(). */
1269 _PyGILState_check_enabled = 0;
1270
Nick Coghland6009512014-11-20 21:39:37 +10001271 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001272 if (interp == NULL) {
1273 *tstate_p = NULL;
1274 return _Py_INIT_OK();
1275 }
Nick Coghland6009512014-11-20 21:39:37 +10001276
1277 tstate = PyThreadState_New(interp);
1278 if (tstate == NULL) {
1279 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001280 *tstate_p = NULL;
1281 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001282 }
1283
1284 save_tstate = PyThreadState_Swap(tstate);
1285
Eric Snow1abcf672017-05-23 21:46:51 -07001286 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001287 _PyCoreConfig *core_config;
1288 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001289 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001290 core_config = &save_tstate->interp->core_config;
1291 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001292 } else {
1293 /* No current thread state, copy from the main interpreter */
1294 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001295 core_config = &main_interp->core_config;
1296 config = &main_interp->config;
1297 }
1298
1299 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1300 return _Py_INIT_ERR("failed to copy core config");
1301 }
1302 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1303 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001304 }
1305
Nick Coghland6009512014-11-20 21:39:37 +10001306 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001307 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001308 if (modules == NULL) {
1309 return _Py_INIT_ERR("can't make modules dictionary");
1310 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001311 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001312
Eric Snowd393c1b2017-09-14 12:18:12 -06001313 sysmod = _PyImport_FindBuiltin("sys", modules);
1314 if (sysmod != NULL) {
1315 interp->sysdict = PyModule_GetDict(sysmod);
1316 if (interp->sysdict == NULL)
1317 goto handle_error;
1318 Py_INCREF(interp->sysdict);
1319 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001320 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001321 }
1322
1323 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001324 if (bimod != NULL) {
1325 interp->builtins = PyModule_GetDict(bimod);
1326 if (interp->builtins == NULL)
1327 goto handle_error;
1328 Py_INCREF(interp->builtins);
1329 }
1330
1331 /* initialize builtin exceptions */
1332 _PyExc_Init(bimod);
1333
Nick Coghland6009512014-11-20 21:39:37 +10001334 if (bimod != NULL && sysmod != NULL) {
1335 PyObject *pstderr;
1336
Nick Coghland6009512014-11-20 21:39:37 +10001337 /* Set up a preliminary stderr printer until we have enough
1338 infrastructure for the io module in place. */
1339 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001340 if (pstderr == NULL) {
1341 return _Py_INIT_ERR("can't set preliminary stderr");
1342 }
Nick Coghland6009512014-11-20 21:39:37 +10001343 _PySys_SetObjectId(&PyId_stderr, pstderr);
1344 PySys_SetObject("__stderr__", pstderr);
1345 Py_DECREF(pstderr);
1346
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001347 err = _PyImportHooks_Init();
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 = initimport(interp, sysmod);
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 = initexternalimport(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 }
Nick Coghland6009512014-11-20 21:39:37 +10001361
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001362 err = initfsencoding(interp);
1363 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001364 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001365 }
1366
Victor Stinner91106cd2017-12-13 12:29:09 +01001367 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001368 if (_Py_INIT_FAILED(err)) {
1369 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001370 }
1371
1372 err = add_main_module(interp);
1373 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001374 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001375 }
1376
1377 if (!Py_NoSiteFlag) {
1378 err = initsite();
1379 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001380 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001381 }
1382 }
Nick Coghland6009512014-11-20 21:39:37 +10001383 }
1384
Victor Stinnera7368ac2017-11-15 18:11:45 -08001385 if (PyErr_Occurred()) {
1386 goto handle_error;
1387 }
Nick Coghland6009512014-11-20 21:39:37 +10001388
Victor Stinnera7368ac2017-11-15 18:11:45 -08001389 *tstate_p = tstate;
1390 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001391
Nick Coghland6009512014-11-20 21:39:37 +10001392handle_error:
1393 /* Oops, it didn't work. Undo it all. */
1394
1395 PyErr_PrintEx(0);
1396 PyThreadState_Clear(tstate);
1397 PyThreadState_Swap(save_tstate);
1398 PyThreadState_Delete(tstate);
1399 PyInterpreterState_Delete(interp);
1400
Victor Stinnera7368ac2017-11-15 18:11:45 -08001401 *tstate_p = NULL;
1402 return _Py_INIT_OK();
1403}
1404
1405PyThreadState *
1406Py_NewInterpreter(void)
1407{
1408 PyThreadState *tstate;
1409 _PyInitError err = new_interpreter(&tstate);
1410 if (_Py_INIT_FAILED(err)) {
1411 _Py_FatalInitError(err);
1412 }
1413 return tstate;
1414
Nick Coghland6009512014-11-20 21:39:37 +10001415}
1416
1417/* Delete an interpreter and its last thread. This requires that the
1418 given thread state is current, that the thread has no remaining
1419 frames, and that it is its interpreter's only remaining thread.
1420 It is a fatal error to violate these constraints.
1421
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001422 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001423 everything, regardless.)
1424
1425 Locking: as above.
1426
1427*/
1428
1429void
1430Py_EndInterpreter(PyThreadState *tstate)
1431{
1432 PyInterpreterState *interp = tstate->interp;
1433
1434 if (tstate != PyThreadState_GET())
1435 Py_FatalError("Py_EndInterpreter: thread is not current");
1436 if (tstate->frame != NULL)
1437 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1438
1439 wait_for_thread_shutdown();
1440
Marcel Plch776407f2017-12-20 11:17:58 +01001441 call_py_exitfuncs(interp);
1442
Nick Coghland6009512014-11-20 21:39:37 +10001443 if (tstate != interp->tstate_head || tstate->next != NULL)
1444 Py_FatalError("Py_EndInterpreter: not the last thread");
1445
1446 PyImport_Cleanup();
1447 PyInterpreterState_Clear(interp);
1448 PyThreadState_Swap(NULL);
1449 PyInterpreterState_Delete(interp);
1450}
1451
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001452/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001453
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001454static _PyInitError
1455add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001456{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001457 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001458 m = PyImport_AddModule("__main__");
1459 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001460 return _Py_INIT_ERR("can't create __main__ module");
1461
Nick Coghland6009512014-11-20 21:39:37 +10001462 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001463 ann_dict = PyDict_New();
1464 if ((ann_dict == NULL) ||
1465 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001466 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001467 }
1468 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001469
Nick Coghland6009512014-11-20 21:39:37 +10001470 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1471 PyObject *bimod = PyImport_ImportModule("builtins");
1472 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001473 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001474 }
1475 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001476 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001477 }
1478 Py_DECREF(bimod);
1479 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001480
Nick Coghland6009512014-11-20 21:39:37 +10001481 /* Main is a little special - imp.is_builtin("__main__") will return
1482 * False, but BuiltinImporter is still the most appropriate initial
1483 * setting for its __loader__ attribute. A more suitable value will
1484 * be set if __main__ gets further initialized later in the startup
1485 * process.
1486 */
1487 loader = PyDict_GetItemString(d, "__loader__");
1488 if (loader == NULL || loader == Py_None) {
1489 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1490 "BuiltinImporter");
1491 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001492 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001493 }
1494 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001495 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001496 }
1497 Py_DECREF(loader);
1498 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001499 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001500}
1501
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001502static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001503initfsencoding(PyInterpreterState *interp)
1504{
1505 PyObject *codec;
1506
Steve Dowercc16be82016-09-08 10:35:16 -07001507#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001508 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001509 Py_FileSystemDefaultEncoding = "mbcs";
1510 Py_FileSystemDefaultEncodeErrors = "replace";
1511 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001512 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001513 Py_FileSystemDefaultEncoding = "utf-8";
1514 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1515 }
1516#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001517 if (Py_FileSystemDefaultEncoding == NULL &&
1518 interp->core_config.utf8_mode)
1519 {
1520 Py_FileSystemDefaultEncoding = "utf-8";
1521 Py_HasFileSystemDefaultEncoding = 1;
1522 }
1523 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001524 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001525 if (Py_FileSystemDefaultEncoding == NULL) {
1526 return _Py_INIT_ERR("Unable to get the locale encoding");
1527 }
Nick Coghland6009512014-11-20 21:39:37 +10001528
1529 Py_HasFileSystemDefaultEncoding = 0;
1530 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001531 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001532 }
Steve Dowercc16be82016-09-08 10:35:16 -07001533#endif
Nick Coghland6009512014-11-20 21:39:37 +10001534
1535 /* the encoding is mbcs, utf-8 or ascii */
1536 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1537 if (!codec) {
1538 /* Such error can only occurs in critical situations: no more
1539 * memory, import a module of the standard library failed,
1540 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001541 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001542 }
1543 Py_DECREF(codec);
1544 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001545 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001546}
1547
1548/* Import the site module (not into __main__ though) */
1549
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001550static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001551initsite(void)
1552{
1553 PyObject *m;
1554 m = PyImport_ImportModule("site");
1555 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001556 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001557 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001558 Py_DECREF(m);
1559 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001560}
1561
Victor Stinner874dbe82015-09-04 17:29:57 +02001562/* Check if a file descriptor is valid or not.
1563 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1564static int
1565is_valid_fd(int fd)
1566{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001567#ifdef __APPLE__
1568 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1569 and the other side of the pipe is closed, dup(1) succeed, whereas
1570 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1571 such error. */
1572 struct stat st;
1573 return (fstat(fd, &st) == 0);
1574#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001575 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001576 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001577 return 0;
1578 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001579 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1580 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1581 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001582 fd2 = dup(fd);
1583 if (fd2 >= 0)
1584 close(fd2);
1585 _Py_END_SUPPRESS_IPH
1586 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001587#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001588}
1589
1590/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001591static PyObject*
1592create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001593 int fd, int write_mode, const char* name,
1594 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001595{
1596 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1597 const char* mode;
1598 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001599 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001600 int buffering, isatty;
1601 _Py_IDENTIFIER(open);
1602 _Py_IDENTIFIER(isatty);
1603 _Py_IDENTIFIER(TextIOWrapper);
1604 _Py_IDENTIFIER(mode);
1605
Victor Stinner874dbe82015-09-04 17:29:57 +02001606 if (!is_valid_fd(fd))
1607 Py_RETURN_NONE;
1608
Nick Coghland6009512014-11-20 21:39:37 +10001609 /* stdin is always opened in buffered mode, first because it shouldn't
1610 make a difference in common use cases, second because TextIOWrapper
1611 depends on the presence of a read1() method which only exists on
1612 buffered streams.
1613 */
1614 if (Py_UnbufferedStdioFlag && write_mode)
1615 buffering = 0;
1616 else
1617 buffering = -1;
1618 if (write_mode)
1619 mode = "wb";
1620 else
1621 mode = "rb";
1622 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1623 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001624 Py_None, Py_None, /* encoding, errors */
1625 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001626 if (buf == NULL)
1627 goto error;
1628
1629 if (buffering) {
1630 _Py_IDENTIFIER(raw);
1631 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1632 if (raw == NULL)
1633 goto error;
1634 }
1635 else {
1636 raw = buf;
1637 Py_INCREF(raw);
1638 }
1639
Steve Dower39294992016-08-30 21:22:36 -07001640#ifdef MS_WINDOWS
1641 /* Windows console IO is always UTF-8 encoded */
1642 if (PyWindowsConsoleIO_Check(raw))
1643 encoding = "utf-8";
1644#endif
1645
Nick Coghland6009512014-11-20 21:39:37 +10001646 text = PyUnicode_FromString(name);
1647 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1648 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001649 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001650 if (res == NULL)
1651 goto error;
1652 isatty = PyObject_IsTrue(res);
1653 Py_DECREF(res);
1654 if (isatty == -1)
1655 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001656 if (Py_UnbufferedStdioFlag)
1657 write_through = Py_True;
1658 else
1659 write_through = Py_False;
1660 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001661 line_buffering = Py_True;
1662 else
1663 line_buffering = Py_False;
1664
1665 Py_CLEAR(raw);
1666 Py_CLEAR(text);
1667
1668#ifdef MS_WINDOWS
1669 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1670 newlines to "\n".
1671 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1672 newline = NULL;
1673#else
1674 /* sys.stdin: split lines at "\n".
1675 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1676 newline = "\n";
1677#endif
1678
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001679 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001680 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001681 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001682 Py_CLEAR(buf);
1683 if (stream == NULL)
1684 goto error;
1685
1686 if (write_mode)
1687 mode = "w";
1688 else
1689 mode = "r";
1690 text = PyUnicode_FromString(mode);
1691 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1692 goto error;
1693 Py_CLEAR(text);
1694 return stream;
1695
1696error:
1697 Py_XDECREF(buf);
1698 Py_XDECREF(stream);
1699 Py_XDECREF(text);
1700 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001701
Victor Stinner874dbe82015-09-04 17:29:57 +02001702 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1703 /* Issue #24891: the file descriptor was closed after the first
1704 is_valid_fd() check was called. Ignore the OSError and set the
1705 stream to None. */
1706 PyErr_Clear();
1707 Py_RETURN_NONE;
1708 }
1709 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001710}
1711
1712/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001713static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001714init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001715{
1716 PyObject *iomod = NULL, *wrapper;
1717 PyObject *bimod = NULL;
1718 PyObject *m;
1719 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001720 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001721 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001722 char *pythonioencoding = NULL;
1723 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001724 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001725
1726 /* Hack to avoid a nasty recursion issue when Python is invoked
1727 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1728 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1729 goto error;
1730 }
1731 Py_DECREF(m);
1732
1733 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1734 goto error;
1735 }
1736 Py_DECREF(m);
1737
1738 if (!(bimod = PyImport_ImportModule("builtins"))) {
1739 goto error;
1740 }
1741
1742 if (!(iomod = PyImport_ImportModule("io"))) {
1743 goto error;
1744 }
1745 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1746 goto error;
1747 }
1748
1749 /* Set builtins.open */
1750 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1751 Py_DECREF(wrapper);
1752 goto error;
1753 }
1754 Py_DECREF(wrapper);
1755
1756 encoding = _Py_StandardStreamEncoding;
1757 errors = _Py_StandardStreamErrors;
1758 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001759 char *opt = Py_GETENV("PYTHONIOENCODING");
1760 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001761 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001762 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001763 if (pythonioencoding == NULL) {
1764 PyErr_NoMemory();
1765 goto error;
1766 }
1767 err = strchr(pythonioencoding, ':');
1768 if (err) {
1769 *err = '\0';
1770 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001771 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001772 errors = err;
1773 }
1774 }
1775 if (*pythonioencoding && !encoding) {
1776 encoding = pythonioencoding;
1777 }
1778 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001779 else if (interp->core_config.utf8_mode) {
1780 encoding = "utf-8";
1781 errors = "surrogateescape";
1782 }
1783
1784 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001785 /* Choose the default error handler based on the current locale */
1786 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001787 }
Nick Coghland6009512014-11-20 21:39:37 +10001788 }
1789
1790 /* Set sys.stdin */
1791 fd = fileno(stdin);
1792 /* Under some conditions stdin, stdout and stderr may not be connected
1793 * and fileno() may point to an invalid file descriptor. For example
1794 * GUI apps don't have valid standard streams by default.
1795 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001796 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1797 if (std == NULL)
1798 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001799 PySys_SetObject("__stdin__", std);
1800 _PySys_SetObjectId(&PyId_stdin, std);
1801 Py_DECREF(std);
1802
1803 /* Set sys.stdout */
1804 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001805 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1806 if (std == NULL)
1807 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001808 PySys_SetObject("__stdout__", std);
1809 _PySys_SetObjectId(&PyId_stdout, std);
1810 Py_DECREF(std);
1811
1812#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1813 /* Set sys.stderr, replaces the preliminary stderr */
1814 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001815 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1816 if (std == NULL)
1817 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001818
1819 /* Same as hack above, pre-import stderr's codec to avoid recursion
1820 when import.c tries to write to stderr in verbose mode. */
1821 encoding_attr = PyObject_GetAttrString(std, "encoding");
1822 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001823 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001824 if (std_encoding != NULL) {
1825 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1826 Py_XDECREF(codec_info);
1827 }
1828 Py_DECREF(encoding_attr);
1829 }
1830 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1831
1832 if (PySys_SetObject("__stderr__", std) < 0) {
1833 Py_DECREF(std);
1834 goto error;
1835 }
1836 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1837 Py_DECREF(std);
1838 goto error;
1839 }
1840 Py_DECREF(std);
1841#endif
1842
Victor Stinnera7368ac2017-11-15 18:11:45 -08001843 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001844
Victor Stinnera7368ac2017-11-15 18:11:45 -08001845error:
1846 res = _Py_INIT_ERR("can't initialize sys standard streams");
1847
Victor Stinner31e99082017-12-20 23:41:38 +01001848 /* Use the same allocator than Py_SetStandardStreamEncoding() */
1849 PyMemAllocatorEx old_alloc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001850done:
Victor Stinner31e99082017-12-20 23:41:38 +01001851 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1852
Nick Coghland6009512014-11-20 21:39:37 +10001853 /* We won't need them anymore. */
1854 if (_Py_StandardStreamEncoding) {
1855 PyMem_RawFree(_Py_StandardStreamEncoding);
1856 _Py_StandardStreamEncoding = NULL;
1857 }
1858 if (_Py_StandardStreamErrors) {
1859 PyMem_RawFree(_Py_StandardStreamErrors);
1860 _Py_StandardStreamErrors = NULL;
1861 }
Victor Stinner31e99082017-12-20 23:41:38 +01001862
1863 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1864
Nick Coghland6009512014-11-20 21:39:37 +10001865 PyMem_Free(pythonioencoding);
1866 Py_XDECREF(bimod);
1867 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001868 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001869}
1870
1871
Victor Stinner10dc4842015-03-24 12:01:30 +01001872static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001873_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001874{
Victor Stinner10dc4842015-03-24 12:01:30 +01001875 fputc('\n', stderr);
1876 fflush(stderr);
1877
1878 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001879 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001880}
Victor Stinner791da1c2016-03-14 16:53:12 +01001881
1882/* Print the current exception (if an exception is set) with its traceback,
1883 or display the current Python stack.
1884
1885 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1886 called on catastrophic cases.
1887
1888 Return 1 if the traceback was displayed, 0 otherwise. */
1889
1890static int
1891_Py_FatalError_PrintExc(int fd)
1892{
1893 PyObject *ferr, *res;
1894 PyObject *exception, *v, *tb;
1895 int has_tb;
1896
1897 if (PyThreadState_GET() == NULL) {
1898 /* The GIL is released: trying to acquire it is likely to deadlock,
1899 just give up. */
1900 return 0;
1901 }
1902
1903 PyErr_Fetch(&exception, &v, &tb);
1904 if (exception == NULL) {
1905 /* No current exception */
1906 return 0;
1907 }
1908
1909 ferr = _PySys_GetObjectId(&PyId_stderr);
1910 if (ferr == NULL || ferr == Py_None) {
1911 /* sys.stderr is not set yet or set to None,
1912 no need to try to display the exception */
1913 return 0;
1914 }
1915
1916 PyErr_NormalizeException(&exception, &v, &tb);
1917 if (tb == NULL) {
1918 tb = Py_None;
1919 Py_INCREF(tb);
1920 }
1921 PyException_SetTraceback(v, tb);
1922 if (exception == NULL) {
1923 /* PyErr_NormalizeException() failed */
1924 return 0;
1925 }
1926
1927 has_tb = (tb != Py_None);
1928 PyErr_Display(exception, v, tb);
1929 Py_XDECREF(exception);
1930 Py_XDECREF(v);
1931 Py_XDECREF(tb);
1932
1933 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001934 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001935 if (res == NULL)
1936 PyErr_Clear();
1937 else
1938 Py_DECREF(res);
1939
1940 return has_tb;
1941}
1942
Nick Coghland6009512014-11-20 21:39:37 +10001943/* Print fatal error message and abort */
1944
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001945#ifdef MS_WINDOWS
1946static void
1947fatal_output_debug(const char *msg)
1948{
1949 /* buffer of 256 bytes allocated on the stack */
1950 WCHAR buffer[256 / sizeof(WCHAR)];
1951 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1952 size_t msglen;
1953
1954 OutputDebugStringW(L"Fatal Python error: ");
1955
1956 msglen = strlen(msg);
1957 while (msglen) {
1958 size_t i;
1959
1960 if (buflen > msglen) {
1961 buflen = msglen;
1962 }
1963
1964 /* Convert the message to wchar_t. This uses a simple one-to-one
1965 conversion, assuming that the this error message actually uses
1966 ASCII only. If this ceases to be true, we will have to convert. */
1967 for (i=0; i < buflen; ++i) {
1968 buffer[i] = msg[i];
1969 }
1970 buffer[i] = L'\0';
1971 OutputDebugStringW(buffer);
1972
1973 msg += buflen;
1974 msglen -= buflen;
1975 }
1976 OutputDebugStringW(L"\n");
1977}
1978#endif
1979
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001980static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001981fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001982{
1983 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001984 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001985
1986 if (reentrant) {
1987 /* Py_FatalError() caused a second fatal error.
1988 Example: flush_std_files() raises a recursion error. */
1989 goto exit;
1990 }
1991 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001992
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001993 fprintf(stderr, "Fatal Python error: ");
1994 if (prefix) {
1995 fputs(prefix, stderr);
1996 fputs(": ", stderr);
1997 }
1998 if (msg) {
1999 fputs(msg, stderr);
2000 }
2001 else {
2002 fprintf(stderr, "<message not set>");
2003 }
2004 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002005 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002006
Victor Stinnere0deff32015-03-24 13:46:18 +01002007 /* Print the exception (if an exception is set) with its traceback,
2008 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002009 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002010 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002011 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002012
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002013 /* The main purpose of faulthandler is to display the traceback.
2014 This function already did its best to display a traceback.
2015 Disable faulthandler to prevent writing a second traceback
2016 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002017 _PyFaulthandler_Fini();
2018
Victor Stinner791da1c2016-03-14 16:53:12 +01002019 /* Check if the current Python thread hold the GIL */
2020 if (PyThreadState_GET() != NULL) {
2021 /* Flush sys.stdout and sys.stderr */
2022 flush_std_files();
2023 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002024
Nick Coghland6009512014-11-20 21:39:37 +10002025#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002026 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002027#endif /* MS_WINDOWS */
2028
2029exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002030 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002031#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002032 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002033#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002034 abort();
2035 }
2036 else {
2037 exit(status);
2038 }
2039}
2040
Victor Stinner19760862017-12-20 01:41:59 +01002041void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002042Py_FatalError(const char *msg)
2043{
2044 fatal_error(NULL, msg, -1);
2045}
2046
Victor Stinner19760862017-12-20 01:41:59 +01002047void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002048_Py_FatalInitError(_PyInitError err)
2049{
2050 /* On "user" error: exit with status 1.
2051 For all other errors, call abort(). */
2052 int status = err.user_err ? 1 : -1;
2053 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002054}
2055
2056/* Clean up and exit */
2057
Victor Stinnerd7292b52016-06-17 12:29:00 +02002058# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002059
Nick Coghland6009512014-11-20 21:39:37 +10002060/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002061void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002062{
Marcel Plch776407f2017-12-20 11:17:58 +01002063 PyThreadState *ts;
2064 PyInterpreterState *is;
Victor Stinnerca719ac2017-12-20 18:00:19 +01002065
Marcel Plch776407f2017-12-20 11:17:58 +01002066 ts = PyThreadState_GET();
2067 is = ts->interp;
2068
Antoine Pitroufc5db952017-12-13 02:29:07 +01002069 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002070 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2071
2072 is->pyexitfunc = func;
2073 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002074}
2075
2076static void
Marcel Plch776407f2017-12-20 11:17:58 +01002077call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002078{
Marcel Plch776407f2017-12-20 11:17:58 +01002079 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002080 return;
2081
Marcel Plch776407f2017-12-20 11:17:58 +01002082 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002083 PyErr_Clear();
2084}
2085
2086/* Wait until threading._shutdown completes, provided
2087 the threading module was imported in the first place.
2088 The shutdown routine will wait until all non-daemon
2089 "threading" threads have completed. */
2090static void
2091wait_for_thread_shutdown(void)
2092{
Nick Coghland6009512014-11-20 21:39:37 +10002093 _Py_IDENTIFIER(_shutdown);
2094 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002095 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002096 if (threading == NULL) {
2097 /* threading not imported */
2098 PyErr_Clear();
2099 return;
2100 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002101 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002102 if (result == NULL) {
2103 PyErr_WriteUnraisable(threading);
2104 }
2105 else {
2106 Py_DECREF(result);
2107 }
2108 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002109}
2110
2111#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002112int Py_AtExit(void (*func)(void))
2113{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002114 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002115 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002116 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002117 return 0;
2118}
2119
2120static void
2121call_ll_exitfuncs(void)
2122{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002123 while (_PyRuntime.nexitfuncs > 0)
2124 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002125
2126 fflush(stdout);
2127 fflush(stderr);
2128}
2129
2130void
2131Py_Exit(int sts)
2132{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002133 if (Py_FinalizeEx() < 0) {
2134 sts = 120;
2135 }
Nick Coghland6009512014-11-20 21:39:37 +10002136
2137 exit(sts);
2138}
2139
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002140static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002141initsigs(void)
2142{
2143#ifdef SIGPIPE
2144 PyOS_setsig(SIGPIPE, SIG_IGN);
2145#endif
2146#ifdef SIGXFZ
2147 PyOS_setsig(SIGXFZ, SIG_IGN);
2148#endif
2149#ifdef SIGXFSZ
2150 PyOS_setsig(SIGXFSZ, SIG_IGN);
2151#endif
2152 PyOS_InitInterrupts(); /* May imply initsignal() */
2153 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002154 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002155 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002156 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002157}
2158
2159
2160/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2161 *
2162 * All of the code in this function must only use async-signal-safe functions,
2163 * listed at `man 7 signal` or
2164 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2165 */
2166void
2167_Py_RestoreSignals(void)
2168{
2169#ifdef SIGPIPE
2170 PyOS_setsig(SIGPIPE, SIG_DFL);
2171#endif
2172#ifdef SIGXFZ
2173 PyOS_setsig(SIGXFZ, SIG_DFL);
2174#endif
2175#ifdef SIGXFSZ
2176 PyOS_setsig(SIGXFSZ, SIG_DFL);
2177#endif
2178}
2179
2180
2181/*
2182 * The file descriptor fd is considered ``interactive'' if either
2183 * a) isatty(fd) is TRUE, or
2184 * b) the -i flag was given, and the filename associated with
2185 * the descriptor is NULL or "<stdin>" or "???".
2186 */
2187int
2188Py_FdIsInteractive(FILE *fp, const char *filename)
2189{
2190 if (isatty((int)fileno(fp)))
2191 return 1;
2192 if (!Py_InteractiveFlag)
2193 return 0;
2194 return (filename == NULL) ||
2195 (strcmp(filename, "<stdin>") == 0) ||
2196 (strcmp(filename, "???") == 0);
2197}
2198
2199
Nick Coghland6009512014-11-20 21:39:37 +10002200/* Wrappers around sigaction() or signal(). */
2201
2202PyOS_sighandler_t
2203PyOS_getsig(int sig)
2204{
2205#ifdef HAVE_SIGACTION
2206 struct sigaction context;
2207 if (sigaction(sig, NULL, &context) == -1)
2208 return SIG_ERR;
2209 return context.sa_handler;
2210#else
2211 PyOS_sighandler_t handler;
2212/* Special signal handling for the secure CRT in Visual Studio 2005 */
2213#if defined(_MSC_VER) && _MSC_VER >= 1400
2214 switch (sig) {
2215 /* Only these signals are valid */
2216 case SIGINT:
2217 case SIGILL:
2218 case SIGFPE:
2219 case SIGSEGV:
2220 case SIGTERM:
2221 case SIGBREAK:
2222 case SIGABRT:
2223 break;
2224 /* Don't call signal() with other values or it will assert */
2225 default:
2226 return SIG_ERR;
2227 }
2228#endif /* _MSC_VER && _MSC_VER >= 1400 */
2229 handler = signal(sig, SIG_IGN);
2230 if (handler != SIG_ERR)
2231 signal(sig, handler);
2232 return handler;
2233#endif
2234}
2235
2236/*
2237 * All of the code in this function must only use async-signal-safe functions,
2238 * listed at `man 7 signal` or
2239 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2240 */
2241PyOS_sighandler_t
2242PyOS_setsig(int sig, PyOS_sighandler_t handler)
2243{
2244#ifdef HAVE_SIGACTION
2245 /* Some code in Modules/signalmodule.c depends on sigaction() being
2246 * used here if HAVE_SIGACTION is defined. Fix that if this code
2247 * changes to invalidate that assumption.
2248 */
2249 struct sigaction context, ocontext;
2250 context.sa_handler = handler;
2251 sigemptyset(&context.sa_mask);
2252 context.sa_flags = 0;
2253 if (sigaction(sig, &context, &ocontext) == -1)
2254 return SIG_ERR;
2255 return ocontext.sa_handler;
2256#else
2257 PyOS_sighandler_t oldhandler;
2258 oldhandler = signal(sig, handler);
2259#ifdef HAVE_SIGINTERRUPT
2260 siginterrupt(sig, 1);
2261#endif
2262 return oldhandler;
2263#endif
2264}
2265
2266#ifdef __cplusplus
2267}
2268#endif