blob: ba4b54864fd8e746f49ae20cb4925eb4f90fc4e2 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
Yury Selivanovf23746a2018-01-22 19:11:18 -05007#include "internal/context.h"
8#include "internal/hamt.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06009#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100010#include "grammar.h"
11#include "node.h"
12#include "token.h"
13#include "parsetok.h"
14#include "errcode.h"
15#include "code.h"
16#include "symtable.h"
17#include "ast.h"
18#include "marshal.h"
19#include "osdefs.h"
20#include <locale.h>
21
22#ifdef HAVE_SIGNAL_H
23#include <signal.h>
24#endif
25
26#ifdef MS_WINDOWS
27#include "malloc.h" /* for alloca */
28#endif
29
30#ifdef HAVE_LANGINFO_H
31#include <langinfo.h>
32#endif
33
34#ifdef MS_WINDOWS
35#undef BYTE
36#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070037
38extern PyTypeObject PyWindowsConsoleIO_Type;
39#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100040#endif
41
42_Py_IDENTIFIER(flush);
43_Py_IDENTIFIER(name);
44_Py_IDENTIFIER(stdin);
45_Py_IDENTIFIER(stdout);
46_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060047_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100048
49#ifdef __cplusplus
50extern "C" {
51#endif
52
Nick Coghland6009512014-11-20 21:39:37 +100053extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056static _PyInitError add_main_module(PyInterpreterState *interp);
57static _PyInitError initfsencoding(PyInterpreterState *interp);
58static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010059static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010061static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100062static void wait_for_thread_shutdown(void);
63static void call_ll_exitfuncs(void);
64extern int _PyUnicode_Init(void);
65extern int _PyStructSequence_Init(void);
66extern void _PyUnicode_Fini(void);
67extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080069extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100070extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080072extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100073extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070074extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100075
Nick Coghland6009512014-11-20 21:39:37 +100076extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082_PyRuntime_Initialize(void)
83{
84 /* XXX We only initialize once in the process, which aligns with
85 the static initialization of the former globals now found in
86 _PyRuntime. However, _PyRuntime *should* be initialized with
87 every Py_Initialize() call, but doing so breaks the runtime.
88 This is because the runtime state is not properly finalized
89 currently. */
90 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091 if (initialized) {
92 return _Py_INIT_OK();
93 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095
96 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99void
100_PyRuntime_Finalize(void)
101{
102 _PyRuntimeState_Fini(&_PyRuntime);
103}
104
105int
106_Py_IsFinalizing(void)
107{
108 return _PyRuntime.finalizing != NULL;
109}
110
Nick Coghland6009512014-11-20 21:39:37 +1000111/* Global configuration variable declarations are in pydebug.h */
112/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
Benjamin Peterson0a37a302017-12-31 10:04:13 -0800113int Py_DebugFlag = 0; /* Needed by parser.c */
114int Py_VerboseFlag = 0; /* Needed by import.c */
115int Py_QuietFlag = 0; /* Needed by sysmodule.c */
116int Py_InteractiveFlag = 0; /* Needed by Py_FdIsInteractive() below */
117int Py_InspectFlag = 0; /* Needed to determine whether to exit at SystemExit */
Nick Coghland6009512014-11-20 21:39:37 +1000118int Py_OptimizeFlag = 0; /* Needed by compile.c */
Benjamin Peterson0a37a302017-12-31 10:04:13 -0800119int Py_NoSiteFlag = 0; /* Suppress 'import site' */
120int Py_BytesWarningFlag = 0; /* Warn on str(bytes) and str(buffer) */
121int Py_FrozenFlag = 0; /* Needed by getpath.c */
122int Py_IgnoreEnvironmentFlag = 0; /* e.g. PYTHONPATH, PYTHONHOME */
123int Py_DontWriteBytecodeFlag = 0; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000124int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
125int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
126int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
127int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700128#ifdef MS_WINDOWS
129int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700130int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700131#endif
Nick Coghland6009512014-11-20 21:39:37 +1000132
Nick Coghland6009512014-11-20 21:39:37 +1000133/* Hack to force loading of object files */
134int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
135 PyOS_mystrnicmp; /* Python/pystrcmp.o */
136
137/* PyModule_GetWarningsModule is no longer necessary as of 2.6
138since _warnings is builtin. This API should not be used. */
139PyObject *
140PyModule_GetWarningsModule(void)
141{
142 return PyImport_ImportModule("warnings");
143}
144
Eric Snowc7ec9982017-05-23 23:00:52 -0700145
Eric Snow1abcf672017-05-23 21:46:51 -0700146/* APIs to access the initialization flags
147 *
148 * Can be called prior to Py_Initialize.
149 */
Nick Coghland6009512014-11-20 21:39:37 +1000150
Eric Snow1abcf672017-05-23 21:46:51 -0700151int
152_Py_IsCoreInitialized(void)
153{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600154 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700155}
Nick Coghland6009512014-11-20 21:39:37 +1000156
157int
158Py_IsInitialized(void)
159{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600160 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000161}
162
163/* Helper to allow an embedding application to override the normal
164 * mechanism that attempts to figure out an appropriate IO encoding
165 */
166
167static char *_Py_StandardStreamEncoding = NULL;
168static char *_Py_StandardStreamErrors = NULL;
169
170int
171Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
172{
173 if (Py_IsInitialized()) {
174 /* This is too late to have any effect */
175 return -1;
176 }
Victor Stinner31e99082017-12-20 23:41:38 +0100177
178 int res = 0;
179
180 /* Py_SetStandardStreamEncoding() can be called before Py_Initialize(),
181 but Py_Initialize() can change the allocator. Use a known allocator
182 to be able to release the memory later. */
183 PyMemAllocatorEx old_alloc;
184 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
185
Nick Coghland6009512014-11-20 21:39:37 +1000186 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
187 * initialised yet.
188 *
189 * However, the raw memory allocators are initialised appropriately
190 * as C static variables, so _PyMem_RawStrdup is OK even though
191 * Py_Initialize hasn't been called yet.
192 */
193 if (encoding) {
194 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
195 if (!_Py_StandardStreamEncoding) {
Victor Stinner31e99082017-12-20 23:41:38 +0100196 res = -2;
197 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000198 }
199 }
200 if (errors) {
201 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
202 if (!_Py_StandardStreamErrors) {
203 if (_Py_StandardStreamEncoding) {
204 PyMem_RawFree(_Py_StandardStreamEncoding);
205 }
Victor Stinner31e99082017-12-20 23:41:38 +0100206 res = -3;
207 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000208 }
209 }
Steve Dower39294992016-08-30 21:22:36 -0700210#ifdef MS_WINDOWS
211 if (_Py_StandardStreamEncoding) {
212 /* Overriding the stream encoding implies legacy streams */
213 Py_LegacyWindowsStdioFlag = 1;
214 }
215#endif
Victor Stinner31e99082017-12-20 23:41:38 +0100216
217done:
218 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
219
220 return res;
Nick Coghland6009512014-11-20 21:39:37 +1000221}
222
Nick Coghlan6ea41862017-06-11 13:16:15 +1000223
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000224/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
225 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000226 initializations fail, a fatal error is issued and the function does
227 not return. On return, the first thread and interpreter state have
228 been created.
229
230 Locking: you must hold the interpreter lock while calling this.
231 (If the lock has not yet been initialized, that's equivalent to
232 having the lock, but you cannot use multiple threads.)
233
234*/
235
Nick Coghland6009512014-11-20 21:39:37 +1000236static char*
237get_codec_name(const char *encoding)
238{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200239 const char *name_utf8;
240 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000241 PyObject *codec, *name = NULL;
242
243 codec = _PyCodec_Lookup(encoding);
244 if (!codec)
245 goto error;
246
247 name = _PyObject_GetAttrId(codec, &PyId_name);
248 Py_CLEAR(codec);
249 if (!name)
250 goto error;
251
Serhiy Storchaka06515832016-11-20 09:13:07 +0200252 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000253 if (name_utf8 == NULL)
254 goto error;
255 name_str = _PyMem_RawStrdup(name_utf8);
256 Py_DECREF(name);
257 if (name_str == NULL) {
258 PyErr_NoMemory();
259 return NULL;
260 }
261 return name_str;
262
263error:
264 Py_XDECREF(codec);
265 Py_XDECREF(name);
266 return NULL;
267}
268
269static char*
270get_locale_encoding(void)
271{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700272#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000273 char* codeset = nl_langinfo(CODESET);
274 if (!codeset || codeset[0] == '\0') {
275 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
276 return NULL;
277 }
278 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200279#elif defined(__ANDROID__)
280 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000281#else
282 PyErr_SetNone(PyExc_NotImplementedError);
283 return NULL;
284#endif
285}
286
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800287static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700288initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000289{
290 PyObject *importlib;
291 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000292 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800293 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000294
295 /* Import _importlib through its frozen version, _frozen_importlib. */
296 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800297 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000298 }
299 else if (Py_VerboseFlag) {
300 PySys_FormatStderr("import _frozen_importlib # frozen\n");
301 }
302 importlib = PyImport_AddModule("_frozen_importlib");
303 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800304 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000305 }
306 interp->importlib = importlib;
307 Py_INCREF(interp->importlib);
308
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300309 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
310 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800311 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300312 Py_INCREF(interp->import_func);
313
Victor Stinnercd6e6942015-09-18 09:11:57 +0200314 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800315 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000316 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800317 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000318 }
319 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200320 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000321 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600322 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800323 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000324 }
325
Victor Stinnercd6e6942015-09-18 09:11:57 +0200326 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000327 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
328 if (value == NULL) {
329 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800330 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000331 }
332 Py_DECREF(value);
333 Py_DECREF(impmod);
334
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800335 err = _PyImportZip_Init();
336 if (_Py_INIT_FAILED(err)) {
337 return err;
338 }
339
340 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000341}
342
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800343static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700344initexternalimport(PyInterpreterState *interp)
345{
346 PyObject *value;
347 value = PyObject_CallMethod(interp->importlib,
348 "_install_external_importers", "");
349 if (value == NULL) {
350 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800351 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700352 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200353 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800354 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700355}
Nick Coghland6009512014-11-20 21:39:37 +1000356
Nick Coghlan6ea41862017-06-11 13:16:15 +1000357/* Helper functions to better handle the legacy C locale
358 *
359 * The legacy C locale assumes ASCII as the default text encoding, which
360 * causes problems not only for the CPython runtime, but also other
361 * components like GNU readline.
362 *
363 * Accordingly, when the CLI detects it, it attempts to coerce it to a
364 * more capable UTF-8 based alternative as follows:
365 *
366 * if (_Py_LegacyLocaleDetected()) {
367 * _Py_CoerceLegacyLocale();
368 * }
369 *
370 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
371 *
372 * Locale coercion also impacts the default error handler for the standard
373 * streams: while the usual default is "strict", the default for the legacy
374 * C locale and for any of the coercion target locales is "surrogateescape".
375 */
376
377int
378_Py_LegacyLocaleDetected(void)
379{
380#ifndef MS_WINDOWS
381 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000382 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
383 * the POSIX locale as a simple alias for the C locale, so
384 * we may also want to check for that explicitly.
385 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000386 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
387 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
388#else
389 /* Windows uses code pages instead of locales, so no locale is legacy */
390 return 0;
391#endif
392}
393
Nick Coghlaneb817952017-06-18 12:29:42 +1000394static const char *_C_LOCALE_WARNING =
395 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
396 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
397 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
398 "locales is recommended.\n";
399
Nick Coghlaneb817952017-06-18 12:29:42 +1000400static void
Victor Stinner94540602017-12-16 04:54:22 +0100401_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000402{
Victor Stinner95cc3ee2018-09-19 12:01:52 -0700403 if (core_config->coerce_c_locale_warn) {
Nick Coghlaneb817952017-06-18 12:29:42 +1000404 if (_Py_LegacyLocaleDetected()) {
405 fprintf(stderr, "%s", _C_LOCALE_WARNING);
406 }
407 }
408}
409
Nick Coghlan6ea41862017-06-11 13:16:15 +1000410typedef struct _CandidateLocale {
411 const char *locale_name; /* The locale to try as a coercion target */
412} _LocaleCoercionTarget;
413
414static _LocaleCoercionTarget _TARGET_LOCALES[] = {
415 {"C.UTF-8"},
416 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000417 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000418 {NULL}
419};
420
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200421static const char *
Nick Coghlan6ea41862017-06-11 13:16:15 +1000422get_default_standard_stream_error_handler(void)
423{
424 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
425 if (ctype_loc != NULL) {
Victor Stinner0b9ea4b2018-08-29 11:01:33 +0200426 /* surrogateescape is the default in the legacy C and POSIX locales */
427 if (strcmp(ctype_loc, "C") == 0 || strcmp(ctype_loc, "POSIX") == 0) {
Nick Coghlan6ea41862017-06-11 13:16:15 +1000428 return "surrogateescape";
429 }
430
431#ifdef PY_COERCE_C_LOCALE
Victor Stinner0b9ea4b2018-08-29 11:01:33 +0200432 /* surrogateescape is the default in locale coercion target locales */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000433 const _LocaleCoercionTarget *target = NULL;
434 for (target = _TARGET_LOCALES; target->locale_name; target++) {
435 if (strcmp(ctype_loc, target->locale_name) == 0) {
436 return "surrogateescape";
437 }
438 }
439#endif
440 }
441
442 /* Otherwise return NULL to request the typical default error handler */
Victor Stinner0b9ea4b2018-08-29 11:01:33 +0200443 return "strict";
Nick Coghlan6ea41862017-06-11 13:16:15 +1000444}
445
446#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100447static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000448 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
449 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
450
451static void
Victor Stinner94540602017-12-16 04:54:22 +0100452_coerce_default_locale_settings(const _PyCoreConfig *config, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000453{
454 const char *newloc = target->locale_name;
455
456 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100457 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000458
459 /* Set the relevant locale environment variable */
460 if (setenv("LC_CTYPE", newloc, 1)) {
461 fprintf(stderr,
462 "Error setting LC_CTYPE, skipping C locale coercion\n");
463 return;
464 }
Victor Stinner95cc3ee2018-09-19 12:01:52 -0700465 if (config->coerce_c_locale_warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100466 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000467 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000468
469 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100470 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000471}
472#endif
473
474void
Victor Stinner94540602017-12-16 04:54:22 +0100475_Py_CoerceLegacyLocale(const _PyCoreConfig *config)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000476{
477#ifdef PY_COERCE_C_LOCALE
Victor Stinner84b01292018-09-03 22:17:07 +0200478 char *oldloc = NULL;
479
480 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
481 if (oldloc == NULL) {
482 return;
483 }
484
Victor Stinner94540602017-12-16 04:54:22 +0100485 const char *locale_override = getenv("LC_ALL");
486 if (locale_override == NULL || *locale_override == '\0') {
487 /* LC_ALL is also not set (or is set to an empty string) */
488 const _LocaleCoercionTarget *target = NULL;
489 for (target = _TARGET_LOCALES; target->locale_name; target++) {
490 const char *new_locale = setlocale(LC_CTYPE,
491 target->locale_name);
492 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100493#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100494defined(HAVE_LANGINFO_H) && defined(CODESET)
495 /* Also ensure that nl_langinfo works in this locale */
496 char *codeset = nl_langinfo(CODESET);
497 if (!codeset || *codeset == '\0') {
498 /* CODESET is not set or empty, so skip coercion */
499 new_locale = NULL;
500 _Py_SetLocaleFromEnv(LC_CTYPE);
501 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000502 }
Victor Stinner94540602017-12-16 04:54:22 +0100503#endif
504 /* Successfully configured locale, so make it the default */
505 _coerce_default_locale_settings(config, target);
Victor Stinner84b01292018-09-03 22:17:07 +0200506 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000507 }
508 }
509 }
510 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner84b01292018-09-03 22:17:07 +0200511
512 setlocale(LC_CTYPE, oldloc);
513
514done:
515 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000516#endif
517}
518
xdegaye1588be62017-11-12 12:45:59 +0100519/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
520 * isolate the idiosyncrasies of different libc implementations. It reads the
521 * appropriate environment variable and uses its value to select the locale for
522 * 'category'. */
523char *
524_Py_SetLocaleFromEnv(int category)
525{
526#ifdef __ANDROID__
527 const char *locale;
528 const char **pvar;
529#ifdef PY_COERCE_C_LOCALE
530 const char *coerce_c_locale;
531#endif
532 const char *utf8_locale = "C.UTF-8";
533 const char *env_var_set[] = {
534 "LC_ALL",
535 "LC_CTYPE",
536 "LANG",
537 NULL,
538 };
539
540 /* Android setlocale(category, "") doesn't check the environment variables
541 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
542 * check the environment variables listed in env_var_set. */
543 for (pvar=env_var_set; *pvar; pvar++) {
544 locale = getenv(*pvar);
545 if (locale != NULL && *locale != '\0') {
546 if (strcmp(locale, utf8_locale) == 0 ||
547 strcmp(locale, "en_US.UTF-8") == 0) {
548 return setlocale(category, utf8_locale);
549 }
550 return setlocale(category, "C");
551 }
552 }
553
554 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
555 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
556 * Quote from POSIX section "8.2 Internationalization Variables":
557 * "4. If the LANG environment variable is not set or is set to the empty
558 * string, the implementation-defined default locale shall be used." */
559
560#ifdef PY_COERCE_C_LOCALE
561 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
562 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
563 /* Some other ported code may check the environment variables (e.g. in
564 * extension modules), so we make sure that they match the locale
565 * configuration */
566 if (setenv("LC_CTYPE", utf8_locale, 1)) {
567 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
568 "environment variable to %s\n", utf8_locale);
569 }
570 }
571#endif
572 return setlocale(category, utf8_locale);
573#else /* __ANDROID__ */
574 return setlocale(category, "");
575#endif /* __ANDROID__ */
576}
577
Nick Coghlan6ea41862017-06-11 13:16:15 +1000578
Eric Snow1abcf672017-05-23 21:46:51 -0700579/* Global initializations. Can be undone by Py_Finalize(). Don't
580 call this twice without an intervening Py_Finalize() call.
581
582 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
583 must have a corresponding call to Py_Finalize.
584
585 Locking: you must hold the interpreter lock while calling these APIs.
586 (If the lock has not yet been initialized, that's equivalent to
587 having the lock, but you cannot use multiple threads.)
588
589*/
590
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200591static _PyInitError
592_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
593 const _PyCoreConfig *core_config)
594{
595 if (core_config->allocator != NULL) {
596 const char *allocator = _PyMem_GetAllocatorsName();
597 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
598 return _Py_INIT_USER_ERR("cannot modify memory allocator "
599 "after first Py_Initialize()");
600 }
601 }
602
603 _PyCoreConfig_SetGlobalConfig(core_config);
604
605 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
606 return _Py_INIT_ERR("failed to copy core config");
607 }
608 return _Py_INIT_OK();
609}
610
611
Eric Snow1abcf672017-05-23 21:46:51 -0700612/* Begin interpreter initialization
613 *
614 * On return, the first thread and interpreter state have been created,
615 * but the compiler, signal handling, multithreading and
616 * multiple interpreter support, and codec infrastructure are not yet
617 * available.
618 *
619 * The import system will support builtin and frozen modules only.
620 * The only supported io is writing to sys.stderr
621 *
622 * If any operation invoked by this function fails, a fatal error is
623 * issued and the function does not return.
624 *
625 * Any code invoked from this function should *not* assume it has access
626 * to the Python C API (unless the API is explicitly listed as being
627 * safe to call without calling Py_Initialize first)
628 */
629
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800630_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200631_Py_InitializeCore_impl(PyInterpreterState **interp_p,
632 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000633{
634 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800635 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000636
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200637 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
638 Py_Initialize() ignores the new configuration. */
639 if (_PyRuntime.core_initialized) {
640 PyThreadState *tstate = PyThreadState_GET();
641 if (!tstate) {
642 return _Py_INIT_ERR("no thread state found");
643 }
644
645 interp = tstate->interp;
646 if (interp == NULL) {
647 return _Py_INIT_ERR("no main interpreter found");
648 }
649 *interp_p = interp;
650
651 return _Py_Initialize_ReconfigureCore(interp, core_config);
652 }
653
654
655 _PyCoreConfig_SetGlobalConfig(core_config);
656
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800657 err = _PyRuntime_Initialize();
658 if (_Py_INIT_FAILED(err)) {
659 return err;
660 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600661
Victor Stinner31e99082017-12-20 23:41:38 +0100662 if (core_config->allocator != NULL) {
663 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
664 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
665 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800666 }
667
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600668 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800669 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700670 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600671 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800672 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700673 }
674
675 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
676 * threads behave a little more gracefully at interpreter shutdown.
677 * We clobber it here so the new interpreter can start with a clean
678 * slate.
679 *
680 * However, this may still lead to misbehaviour if there are daemon
681 * threads still hanging around from a previous Py_Initialize/Finalize
682 * pair :(
683 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600684 _PyRuntime.finalizing = NULL;
685
Nick Coghlan6ea41862017-06-11 13:16:15 +1000686#ifndef MS_WINDOWS
Victor Stinner94540602017-12-16 04:54:22 +0100687 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000688#endif
Nick Coghland6009512014-11-20 21:39:37 +1000689
Victor Stinnerda273412017-12-15 01:46:02 +0100690 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800691 if (_Py_INIT_FAILED(err)) {
692 return err;
693 }
694
Victor Stinnerda273412017-12-15 01:46:02 +0100695 if (!core_config->use_hash_seed || core_config->hash_seed) {
Eric Snow1abcf672017-05-23 21:46:51 -0700696 /* Random or non-zero hash seed */
697 Py_HashRandomizationFlag = 1;
698 }
Nick Coghland6009512014-11-20 21:39:37 +1000699
Victor Stinnera7368ac2017-11-15 18:11:45 -0800700 err = _PyInterpreterState_Enable(&_PyRuntime);
701 if (_Py_INIT_FAILED(err)) {
702 return err;
703 }
704
Nick Coghland6009512014-11-20 21:39:37 +1000705 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100706 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800707 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100708 }
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200709 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100710
711 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
712 return _Py_INIT_ERR("failed to copy core config");
713 }
Nick Coghland6009512014-11-20 21:39:37 +1000714
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200715 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000716 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800717 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000718 (void) PyThreadState_Swap(tstate);
719
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000720 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000721 destroying the GIL might fail when it is being referenced from
722 another running thread (see issue #9901).
723 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000724 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000725 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100726
Nick Coghland6009512014-11-20 21:39:37 +1000727 /* Auto-thread-state API */
728 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000729
Victor Stinner2914bb32018-01-29 11:57:45 +0100730 /* Create the GIL */
731 PyEval_InitThreads();
732
Nick Coghland6009512014-11-20 21:39:37 +1000733 _Py_ReadyTypes();
734
735 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800736 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000737
738 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800739 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000740
741 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800742 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000743
744 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800745 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000746
Eric Snowd393c1b2017-09-14 12:18:12 -0600747 PyObject *modules = PyDict_New();
748 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800749 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600750 interp->modules = modules;
751
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200752 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800753 err = _PySys_BeginInit(&sysmod);
754 if (_Py_INIT_FAILED(err)) {
755 return err;
756 }
757
Eric Snowd393c1b2017-09-14 12:18:12 -0600758 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800759 if (interp->sysdict == NULL) {
760 return _Py_INIT_ERR("can't initialize sys dict");
761 }
762
Eric Snowd393c1b2017-09-14 12:18:12 -0600763 Py_INCREF(interp->sysdict);
764 PyDict_SetItemString(interp->sysdict, "modules", modules);
765 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000766
767 /* Init Unicode implementation; relies on the codec registry */
768 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800769 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700770
Nick Coghland6009512014-11-20 21:39:37 +1000771 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800772 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000773
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200774 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000775 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800776 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600777 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000778 interp->builtins = PyModule_GetDict(bimod);
779 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800780 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000781 Py_INCREF(interp->builtins);
782
783 /* initialize builtin exceptions */
784 _PyExc_Init(bimod);
785
Nick Coghland6009512014-11-20 21:39:37 +1000786 /* Set up a preliminary stderr printer until we have enough
787 infrastructure for the io module in place. */
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200788 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000789 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800790 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000791 _PySys_SetObjectId(&PyId_stderr, pstderr);
792 PySys_SetObject("__stderr__", pstderr);
793 Py_DECREF(pstderr);
794
Victor Stinner672b6ba2017-12-06 17:25:50 +0100795 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800796 if (_Py_INIT_FAILED(err)) {
797 return err;
798 }
Nick Coghland6009512014-11-20 21:39:37 +1000799
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800800 err = _PyImportHooks_Init();
801 if (_Py_INIT_FAILED(err)) {
802 return err;
803 }
Nick Coghland6009512014-11-20 21:39:37 +1000804
805 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100806 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100807 return _Py_INIT_ERR("can't initialize warnings");
808 }
Nick Coghland6009512014-11-20 21:39:37 +1000809
Yury Selivanovf23746a2018-01-22 19:11:18 -0500810 if (!_PyContext_Init())
811 return _Py_INIT_ERR("can't init context");
812
Eric Snow1abcf672017-05-23 21:46:51 -0700813 /* This call sets up builtin and frozen import support */
814 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800815 err = initimport(interp, sysmod);
816 if (_Py_INIT_FAILED(err)) {
817 return err;
818 }
Eric Snow1abcf672017-05-23 21:46:51 -0700819 }
820
821 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600822 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800823 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700824}
825
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200826
827_PyInitError
828_Py_InitializeCore(PyInterpreterState **interp_p,
829 const _PyCoreConfig *src_config)
830{
831 assert(src_config != NULL);
832
833 PyMemAllocatorEx old_alloc;
834 _PyInitError err;
835
836 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
837 (and the input configuration is read only). */
838 _PyCoreConfig config = _PyCoreConfig_INIT;
839
Victor Stinner98c49c62018-08-29 01:13:29 +0200840#ifndef MS_WINDOWS
841 /* Set up the LC_CTYPE locale, so we can obtain the locale's charset
842 without having to switch locales. */
843 _Py_SetLocaleFromEnv(LC_CTYPE);
844#endif
845
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200846 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
847 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
848 err = _PyCoreConfig_Read(&config);
849 }
850 else {
851 err = _Py_INIT_ERR("failed to copy core config");
852 }
853 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
854
855 if (_Py_INIT_FAILED(err)) {
856 goto done;
857 }
858
859 err = _Py_InitializeCore_impl(interp_p, &config);
860
861done:
862 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
863 _PyCoreConfig_Clear(&config);
864 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
865
866 return err;
867}
868
Miss Islington (bot)03ec4df2018-07-20 17:16:22 -0700869/* Py_Initialize() has already been called: update the main interpreter
870 configuration. Example of bpo-34008: Py_Main() called after
871 Py_Initialize(). */
872static _PyInitError
873_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
874 const _PyMainInterpreterConfig *config)
875{
876 if (config->argv != NULL) {
877 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
878 if (res < 0) {
879 return _Py_INIT_ERR("fail to set sys.argv");
880 }
881 }
882 return _Py_INIT_OK();
883}
884
Eric Snowc7ec9982017-05-23 23:00:52 -0700885/* Update interpreter state based on supplied configuration settings
886 *
887 * After calling this function, most of the restrictions on the interpreter
888 * are lifted. The only remaining incomplete settings are those related
889 * to the main module (sys.argv[0], __main__ metadata)
890 *
891 * Calling this when the interpreter is not initializing, is already
892 * initialized or without a valid current thread state is a fatal error.
893 * Other errors should be reported as normal Python exceptions with a
894 * non-zero return code.
895 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800896_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200897_Py_InitializeMainInterpreter(PyInterpreterState *interp,
898 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700899{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800900 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700901
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600902 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800903 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700904 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700905
Eric Snow1abcf672017-05-23 21:46:51 -0700906 /* Now finish configuring the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100907 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
908 return _Py_INIT_ERR("failed to copy main interpreter config");
909 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700910
Miss Islington (bot)03ec4df2018-07-20 17:16:22 -0700911 if (_PyRuntime.initialized) {
912 return _Py_ReconfigureMainInterpreter(interp, config);
913 }
914
Eric Snow1abcf672017-05-23 21:46:51 -0700915 if (interp->core_config._disable_importlib) {
916 /* Special mode for freeze_importlib: run with no import system
917 *
918 * This means anything which needs support from extension modules
919 * or pure Python code in the standard library won't work.
920 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600921 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800922 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700923 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100924
Victor Stinner33c377e2017-12-05 15:12:41 +0100925 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800926 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100927 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200928
Victor Stinner41264f12017-12-15 02:05:29 +0100929 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800930 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100931 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800932
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800933 err = initexternalimport(interp);
934 if (_Py_INIT_FAILED(err)) {
935 return err;
936 }
Nick Coghland6009512014-11-20 21:39:37 +1000937
938 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800939 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800940 if (_Py_INIT_FAILED(err)) {
941 return err;
942 }
Nick Coghland6009512014-11-20 21:39:37 +1000943
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800944 err = initfsencoding(interp);
945 if (_Py_INIT_FAILED(err)) {
946 return err;
947 }
Nick Coghland6009512014-11-20 21:39:37 +1000948
Victor Stinner1f151112017-11-23 10:43:14 +0100949 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800950 err = initsigs(); /* Signal handling stuff, including initintr() */
951 if (_Py_INIT_FAILED(err)) {
952 return err;
953 }
954 }
Nick Coghland6009512014-11-20 21:39:37 +1000955
Victor Stinnera7368ac2017-11-15 18:11:45 -0800956 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800957 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000958
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800959 err = add_main_module(interp);
960 if (_Py_INIT_FAILED(err)) {
961 return err;
962 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800963
Victor Stinner91106cd2017-12-13 12:29:09 +0100964 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800965 if (_Py_INIT_FAILED(err)) {
966 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800967 }
Nick Coghland6009512014-11-20 21:39:37 +1000968
969 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100970 if (interp->config.warnoptions != NULL &&
971 PyList_Size(interp->config.warnoptions) > 0)
972 {
Nick Coghland6009512014-11-20 21:39:37 +1000973 PyObject *warnings_module = PyImport_ImportModule("warnings");
974 if (warnings_module == NULL) {
975 fprintf(stderr, "'import warnings' failed; traceback:\n");
976 PyErr_Print();
977 }
978 Py_XDECREF(warnings_module);
979 }
980
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600981 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700982
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800983 if (!Py_NoSiteFlag) {
984 err = initsite(); /* Module site */
985 if (_Py_INIT_FAILED(err)) {
986 return err;
987 }
988 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800989 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000990}
991
Eric Snowc7ec9982017-05-23 23:00:52 -0700992#undef _INIT_DEBUG_PRINT
993
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200994
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800995_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200996_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700997{
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200998 _Py_Initialize_ReadEnvVarsNoAlloc();
Miss Islington (bot)3747dd12018-06-22 10:33:48 -0700999
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001000 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001001 _PyInitError err;
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001002 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001003 if (_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001004 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001005 }
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001006 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001007
Victor Stinner9cfc0022017-12-20 19:36:46 +01001008 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001009 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +01001010 if (!_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001011 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001012 }
Victor Stinner9cfc0022017-12-20 19:36:46 +01001013 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001014 if (_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001015 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001016 }
1017
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001018 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001019}
1020
1021
1022void
Nick Coghland6009512014-11-20 21:39:37 +10001023Py_InitializeEx(int install_sigs)
1024{
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001025 if (_PyRuntime.initialized) {
1026 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1027 return;
1028 }
1029
1030 _PyInitError err;
1031 _PyCoreConfig config = _PyCoreConfig_INIT;
1032 config.install_signal_handlers = install_sigs;
1033
1034 err = _Py_InitializeFromConfig(&config);
1035 _PyCoreConfig_Clear(&config);
1036
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001037 if (_Py_INIT_FAILED(err)) {
1038 _Py_FatalInitError(err);
1039 }
Nick Coghland6009512014-11-20 21:39:37 +10001040}
1041
1042void
1043Py_Initialize(void)
1044{
1045 Py_InitializeEx(1);
1046}
1047
1048
1049#ifdef COUNT_ALLOCS
1050extern void dump_counts(FILE*);
1051#endif
1052
1053/* Flush stdout and stderr */
1054
1055static int
1056file_is_closed(PyObject *fobj)
1057{
1058 int r;
1059 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1060 if (tmp == NULL) {
1061 PyErr_Clear();
1062 return 0;
1063 }
1064 r = PyObject_IsTrue(tmp);
1065 Py_DECREF(tmp);
1066 if (r < 0)
1067 PyErr_Clear();
1068 return r > 0;
1069}
1070
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001071static int
Nick Coghland6009512014-11-20 21:39:37 +10001072flush_std_files(void)
1073{
1074 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1075 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1076 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001077 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001078
1079 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001080 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001081 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001082 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001083 status = -1;
1084 }
Nick Coghland6009512014-11-20 21:39:37 +10001085 else
1086 Py_DECREF(tmp);
1087 }
1088
1089 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001090 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001091 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001092 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001093 status = -1;
1094 }
Nick Coghland6009512014-11-20 21:39:37 +10001095 else
1096 Py_DECREF(tmp);
1097 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001098
1099 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001100}
1101
1102/* Undo the effect of Py_Initialize().
1103
1104 Beware: if multiple interpreter and/or thread states exist, these
1105 are not wiped out; only the current thread and interpreter state
1106 are deleted. But since everything else is deleted, those other
1107 interpreter and thread states should no longer be used.
1108
1109 (XXX We should do better, e.g. wipe out all interpreters and
1110 threads.)
1111
1112 Locking: as above.
1113
1114*/
1115
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001116int
1117Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001118{
1119 PyInterpreterState *interp;
1120 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001121 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001122
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001123 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001124 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001125
1126 wait_for_thread_shutdown();
1127
Marcel Plch776407f2017-12-20 11:17:58 +01001128 /* Get current thread state and interpreter pointer */
1129 tstate = PyThreadState_GET();
1130 interp = tstate->interp;
1131
Nick Coghland6009512014-11-20 21:39:37 +10001132 /* The interpreter is still entirely intact at this point, and the
1133 * exit funcs may be relying on that. In particular, if some thread
1134 * or exit func is still waiting to do an import, the import machinery
1135 * expects Py_IsInitialized() to return true. So don't say the
1136 * interpreter is uninitialized until after the exit funcs have run.
1137 * Note that Threading.py uses an exit func to do a join on all the
1138 * threads created thru it, so this also protects pending imports in
1139 * the threads created via Threading.
1140 */
Nick Coghland6009512014-11-20 21:39:37 +10001141
Marcel Plch776407f2017-12-20 11:17:58 +01001142 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001143
Victor Stinnerda273412017-12-15 01:46:02 +01001144 /* Copy the core config, PyInterpreterState_Delete() free
1145 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001146#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001147 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001148#endif
1149#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001150 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001151#endif
1152#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001153 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001154#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001155
Nick Coghland6009512014-11-20 21:39:37 +10001156 /* Remaining threads (e.g. daemon threads) will automatically exit
1157 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001158 _PyRuntime.finalizing = tstate;
1159 _PyRuntime.initialized = 0;
1160 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001161
Victor Stinnere0deff32015-03-24 13:46:18 +01001162 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001163 if (flush_std_files() < 0) {
1164 status = -1;
1165 }
Nick Coghland6009512014-11-20 21:39:37 +10001166
1167 /* Disable signal handling */
1168 PyOS_FiniInterrupts();
1169
1170 /* Collect garbage. This may call finalizers; it's nice to call these
1171 * before all modules are destroyed.
1172 * XXX If a __del__ or weakref callback is triggered here, and tries to
1173 * XXX import a module, bad things can happen, because Python no
1174 * XXX longer believes it's initialized.
1175 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1176 * XXX is easy to provoke that way. I've also seen, e.g.,
1177 * XXX Exception exceptions.ImportError: 'No module named sha'
1178 * XXX in <function callback at 0x008F5718> ignored
1179 * XXX but I'm unclear on exactly how that one happens. In any case,
1180 * XXX I haven't seen a real-life report of either of these.
1181 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001182 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001183#ifdef COUNT_ALLOCS
1184 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1185 each collection might release some types from the type
1186 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001187 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001188 /* nothing */;
1189#endif
Eric Snowdae02762017-09-14 00:35:58 -07001190
Nick Coghland6009512014-11-20 21:39:37 +10001191 /* Destroy all modules */
1192 PyImport_Cleanup();
1193
Victor Stinnere0deff32015-03-24 13:46:18 +01001194 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001195 if (flush_std_files() < 0) {
1196 status = -1;
1197 }
Nick Coghland6009512014-11-20 21:39:37 +10001198
1199 /* Collect final garbage. This disposes of cycles created by
1200 * class definitions, for example.
1201 * XXX This is disabled because it caused too many problems. If
1202 * XXX a __del__ or weakref callback triggers here, Python code has
1203 * XXX a hard time running, because even the sys module has been
1204 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1205 * XXX One symptom is a sequence of information-free messages
1206 * XXX coming from threads (if a __del__ or callback is invoked,
1207 * XXX other threads can execute too, and any exception they encounter
1208 * XXX triggers a comedy of errors as subsystem after subsystem
1209 * XXX fails to find what it *expects* to find in sys to help report
1210 * XXX the exception and consequent unexpected failures). I've also
1211 * XXX seen segfaults then, after adding print statements to the
1212 * XXX Python code getting called.
1213 */
1214#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001215 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001216#endif
1217
1218 /* Disable tracemalloc after all Python objects have been destroyed,
1219 so it is possible to use tracemalloc in objects destructor. */
1220 _PyTraceMalloc_Fini();
1221
1222 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1223 _PyImport_Fini();
1224
1225 /* Cleanup typeobject.c's internal caches. */
1226 _PyType_Fini();
1227
1228 /* unload faulthandler module */
1229 _PyFaulthandler_Fini();
1230
1231 /* Debugging stuff */
1232#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001233 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001234#endif
1235 /* dump hash stats */
1236 _PyHash_Fini();
1237
Eric Snowdae02762017-09-14 00:35:58 -07001238#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001239 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001240 _PyDebug_PrintTotalRefs();
1241 }
Eric Snowdae02762017-09-14 00:35:58 -07001242#endif
Nick Coghland6009512014-11-20 21:39:37 +10001243
1244#ifdef Py_TRACE_REFS
1245 /* Display all objects still alive -- this can invoke arbitrary
1246 * __repr__ overrides, so requires a mostly-intact interpreter.
1247 * Alas, a lot of stuff may still be alive now that will be cleaned
1248 * up later.
1249 */
Victor Stinnerda273412017-12-15 01:46:02 +01001250 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001251 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001252 }
Nick Coghland6009512014-11-20 21:39:37 +10001253#endif /* Py_TRACE_REFS */
1254
1255 /* Clear interpreter state and all thread states. */
1256 PyInterpreterState_Clear(interp);
1257
1258 /* Now we decref the exception classes. After this point nothing
1259 can raise an exception. That's okay, because each Fini() method
1260 below has been checked to make sure no exceptions are ever
1261 raised.
1262 */
1263
1264 _PyExc_Fini();
1265
1266 /* Sundry finalizers */
1267 PyMethod_Fini();
1268 PyFrame_Fini();
1269 PyCFunction_Fini();
1270 PyTuple_Fini();
1271 PyList_Fini();
1272 PySet_Fini();
1273 PyBytes_Fini();
1274 PyByteArray_Fini();
1275 PyLong_Fini();
1276 PyFloat_Fini();
1277 PyDict_Fini();
1278 PySlice_Fini();
1279 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001280 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001281 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001282 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001283 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001284
1285 /* Cleanup Unicode implementation */
1286 _PyUnicode_Fini();
1287
1288 /* reset file system default encoding */
1289 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1290 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1291 Py_FileSystemDefaultEncoding = NULL;
1292 }
1293
1294 /* XXX Still allocated:
1295 - various static ad-hoc pointers to interned strings
1296 - int and float free list blocks
1297 - whatever various modules and libraries allocate
1298 */
1299
1300 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1301
1302 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001303 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001304
1305 /* Delete current thread. After this, many C API calls become crashy. */
1306 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001307
Nick Coghland6009512014-11-20 21:39:37 +10001308 PyInterpreterState_Delete(interp);
1309
1310#ifdef Py_TRACE_REFS
1311 /* Display addresses (& refcnts) of all objects still alive.
1312 * An address can be used to find the repr of the object, printed
1313 * above by _Py_PrintReferences.
1314 */
Victor Stinnerda273412017-12-15 01:46:02 +01001315 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001316 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001317 }
Nick Coghland6009512014-11-20 21:39:37 +10001318#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001319#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001320 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001321 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001322 }
Nick Coghland6009512014-11-20 21:39:37 +10001323#endif
1324
1325 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001326
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001327 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001328 return status;
1329}
1330
1331void
1332Py_Finalize(void)
1333{
1334 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001335}
1336
1337/* Create and initialize a new interpreter and thread, and return the
1338 new thread. This requires that Py_Initialize() has been called
1339 first.
1340
1341 Unsuccessful initialization yields a NULL pointer. Note that *no*
1342 exception information is available even in this case -- the
1343 exception information is held in the thread, and there is no
1344 thread.
1345
1346 Locking: as above.
1347
1348*/
1349
Victor Stinnera7368ac2017-11-15 18:11:45 -08001350static _PyInitError
1351new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001352{
1353 PyInterpreterState *interp;
1354 PyThreadState *tstate, *save_tstate;
1355 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001356 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001357
Victor Stinnera7368ac2017-11-15 18:11:45 -08001358 if (!_PyRuntime.initialized) {
1359 return _Py_INIT_ERR("Py_Initialize must be called first");
1360 }
Nick Coghland6009512014-11-20 21:39:37 +10001361
Victor Stinner8a1be612016-03-14 22:07:55 +01001362 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1363 interpreters: disable PyGILState_Check(). */
1364 _PyGILState_check_enabled = 0;
1365
Nick Coghland6009512014-11-20 21:39:37 +10001366 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001367 if (interp == NULL) {
1368 *tstate_p = NULL;
1369 return _Py_INIT_OK();
1370 }
Nick Coghland6009512014-11-20 21:39:37 +10001371
1372 tstate = PyThreadState_New(interp);
1373 if (tstate == NULL) {
1374 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001375 *tstate_p = NULL;
1376 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001377 }
1378
1379 save_tstate = PyThreadState_Swap(tstate);
1380
Eric Snow1abcf672017-05-23 21:46:51 -07001381 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001382 _PyCoreConfig *core_config;
1383 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001384 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001385 core_config = &save_tstate->interp->core_config;
1386 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001387 } else {
1388 /* No current thread state, copy from the main interpreter */
1389 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001390 core_config = &main_interp->core_config;
1391 config = &main_interp->config;
1392 }
1393
1394 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1395 return _Py_INIT_ERR("failed to copy core config");
1396 }
1397 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1398 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001399 }
1400
Nick Coghland6009512014-11-20 21:39:37 +10001401 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001402 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001403 if (modules == NULL) {
1404 return _Py_INIT_ERR("can't make modules dictionary");
1405 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001406 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001407
Eric Snowd393c1b2017-09-14 12:18:12 -06001408 sysmod = _PyImport_FindBuiltin("sys", modules);
1409 if (sysmod != NULL) {
1410 interp->sysdict = PyModule_GetDict(sysmod);
1411 if (interp->sysdict == NULL)
1412 goto handle_error;
1413 Py_INCREF(interp->sysdict);
1414 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001415 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001416 }
1417
1418 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001419 if (bimod != NULL) {
1420 interp->builtins = PyModule_GetDict(bimod);
1421 if (interp->builtins == NULL)
1422 goto handle_error;
1423 Py_INCREF(interp->builtins);
1424 }
1425
1426 /* initialize builtin exceptions */
1427 _PyExc_Init(bimod);
1428
Nick Coghland6009512014-11-20 21:39:37 +10001429 if (bimod != NULL && sysmod != NULL) {
1430 PyObject *pstderr;
1431
Nick Coghland6009512014-11-20 21:39:37 +10001432 /* Set up a preliminary stderr printer until we have enough
1433 infrastructure for the io module in place. */
1434 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001435 if (pstderr == NULL) {
1436 return _Py_INIT_ERR("can't set preliminary stderr");
1437 }
Nick Coghland6009512014-11-20 21:39:37 +10001438 _PySys_SetObjectId(&PyId_stderr, pstderr);
1439 PySys_SetObject("__stderr__", pstderr);
1440 Py_DECREF(pstderr);
1441
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001442 err = _PyImportHooks_Init();
1443 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001444 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001445 }
Nick Coghland6009512014-11-20 21:39:37 +10001446
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001447 err = initimport(interp, sysmod);
1448 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001449 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001450 }
Nick Coghland6009512014-11-20 21:39:37 +10001451
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001452 err = initexternalimport(interp);
1453 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001454 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001455 }
Nick Coghland6009512014-11-20 21:39:37 +10001456
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001457 err = initfsencoding(interp);
1458 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001459 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001460 }
1461
Victor Stinner91106cd2017-12-13 12:29:09 +01001462 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001463 if (_Py_INIT_FAILED(err)) {
1464 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001465 }
1466
1467 err = add_main_module(interp);
1468 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001469 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001470 }
1471
1472 if (!Py_NoSiteFlag) {
1473 err = initsite();
1474 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001475 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001476 }
1477 }
Nick Coghland6009512014-11-20 21:39:37 +10001478 }
1479
Victor Stinnera7368ac2017-11-15 18:11:45 -08001480 if (PyErr_Occurred()) {
1481 goto handle_error;
1482 }
Nick Coghland6009512014-11-20 21:39:37 +10001483
Victor Stinnera7368ac2017-11-15 18:11:45 -08001484 *tstate_p = tstate;
1485 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001486
Nick Coghland6009512014-11-20 21:39:37 +10001487handle_error:
1488 /* Oops, it didn't work. Undo it all. */
1489
1490 PyErr_PrintEx(0);
1491 PyThreadState_Clear(tstate);
1492 PyThreadState_Swap(save_tstate);
1493 PyThreadState_Delete(tstate);
1494 PyInterpreterState_Delete(interp);
1495
Victor Stinnera7368ac2017-11-15 18:11:45 -08001496 *tstate_p = NULL;
1497 return _Py_INIT_OK();
1498}
1499
1500PyThreadState *
1501Py_NewInterpreter(void)
1502{
1503 PyThreadState *tstate;
1504 _PyInitError err = new_interpreter(&tstate);
1505 if (_Py_INIT_FAILED(err)) {
1506 _Py_FatalInitError(err);
1507 }
1508 return tstate;
1509
Nick Coghland6009512014-11-20 21:39:37 +10001510}
1511
1512/* Delete an interpreter and its last thread. This requires that the
1513 given thread state is current, that the thread has no remaining
1514 frames, and that it is its interpreter's only remaining thread.
1515 It is a fatal error to violate these constraints.
1516
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001517 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001518 everything, regardless.)
1519
1520 Locking: as above.
1521
1522*/
1523
1524void
1525Py_EndInterpreter(PyThreadState *tstate)
1526{
1527 PyInterpreterState *interp = tstate->interp;
1528
1529 if (tstate != PyThreadState_GET())
1530 Py_FatalError("Py_EndInterpreter: thread is not current");
1531 if (tstate->frame != NULL)
1532 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1533
1534 wait_for_thread_shutdown();
1535
Marcel Plch776407f2017-12-20 11:17:58 +01001536 call_py_exitfuncs(interp);
1537
Nick Coghland6009512014-11-20 21:39:37 +10001538 if (tstate != interp->tstate_head || tstate->next != NULL)
1539 Py_FatalError("Py_EndInterpreter: not the last thread");
1540
1541 PyImport_Cleanup();
1542 PyInterpreterState_Clear(interp);
1543 PyThreadState_Swap(NULL);
1544 PyInterpreterState_Delete(interp);
1545}
1546
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001547/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001548
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001549static _PyInitError
1550add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001551{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001552 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001553 m = PyImport_AddModule("__main__");
1554 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001555 return _Py_INIT_ERR("can't create __main__ module");
1556
Nick Coghland6009512014-11-20 21:39:37 +10001557 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001558 ann_dict = PyDict_New();
1559 if ((ann_dict == NULL) ||
1560 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001561 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001562 }
1563 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001564
Nick Coghland6009512014-11-20 21:39:37 +10001565 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1566 PyObject *bimod = PyImport_ImportModule("builtins");
1567 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001568 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001569 }
1570 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001571 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001572 }
1573 Py_DECREF(bimod);
1574 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001575
Nick Coghland6009512014-11-20 21:39:37 +10001576 /* Main is a little special - imp.is_builtin("__main__") will return
1577 * False, but BuiltinImporter is still the most appropriate initial
1578 * setting for its __loader__ attribute. A more suitable value will
1579 * be set if __main__ gets further initialized later in the startup
1580 * process.
1581 */
1582 loader = PyDict_GetItemString(d, "__loader__");
1583 if (loader == NULL || loader == Py_None) {
1584 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1585 "BuiltinImporter");
1586 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001587 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001588 }
1589 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001590 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001591 }
1592 Py_DECREF(loader);
1593 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001594 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001595}
1596
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001597static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001598initfsencoding(PyInterpreterState *interp)
1599{
1600 PyObject *codec;
1601
Steve Dowercc16be82016-09-08 10:35:16 -07001602#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001603 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001604 Py_FileSystemDefaultEncoding = "mbcs";
1605 Py_FileSystemDefaultEncodeErrors = "replace";
1606 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001607 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001608 Py_FileSystemDefaultEncoding = "utf-8";
1609 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1610 }
1611#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001612 if (Py_FileSystemDefaultEncoding == NULL &&
1613 interp->core_config.utf8_mode)
1614 {
1615 Py_FileSystemDefaultEncoding = "utf-8";
1616 Py_HasFileSystemDefaultEncoding = 1;
1617 }
1618 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001619 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001620 if (Py_FileSystemDefaultEncoding == NULL) {
1621 return _Py_INIT_ERR("Unable to get the locale encoding");
1622 }
Nick Coghland6009512014-11-20 21:39:37 +10001623
1624 Py_HasFileSystemDefaultEncoding = 0;
1625 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001626 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001627 }
Steve Dowercc16be82016-09-08 10:35:16 -07001628#endif
Nick Coghland6009512014-11-20 21:39:37 +10001629
1630 /* the encoding is mbcs, utf-8 or ascii */
1631 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1632 if (!codec) {
1633 /* Such error can only occurs in critical situations: no more
1634 * memory, import a module of the standard library failed,
1635 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001636 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001637 }
1638 Py_DECREF(codec);
1639 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001640 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001641}
1642
1643/* Import the site module (not into __main__ though) */
1644
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001645static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001646initsite(void)
1647{
1648 PyObject *m;
1649 m = PyImport_ImportModule("site");
1650 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001651 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001652 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001653 Py_DECREF(m);
1654 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001655}
1656
Victor Stinner874dbe82015-09-04 17:29:57 +02001657/* Check if a file descriptor is valid or not.
1658 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1659static int
1660is_valid_fd(int fd)
1661{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001662#ifdef __APPLE__
1663 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1664 and the other side of the pipe is closed, dup(1) succeed, whereas
1665 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1666 such error. */
1667 struct stat st;
1668 return (fstat(fd, &st) == 0);
1669#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001670 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001671 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001672 return 0;
1673 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001674 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1675 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1676 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001677 fd2 = dup(fd);
1678 if (fd2 >= 0)
1679 close(fd2);
1680 _Py_END_SUPPRESS_IPH
1681 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001682#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001683}
1684
1685/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001686static PyObject*
1687create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001688 int fd, int write_mode, const char* name,
1689 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001690{
1691 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1692 const char* mode;
1693 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001694 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001695 int buffering, isatty;
1696 _Py_IDENTIFIER(open);
1697 _Py_IDENTIFIER(isatty);
1698 _Py_IDENTIFIER(TextIOWrapper);
1699 _Py_IDENTIFIER(mode);
1700
Victor Stinner874dbe82015-09-04 17:29:57 +02001701 if (!is_valid_fd(fd))
1702 Py_RETURN_NONE;
1703
Nick Coghland6009512014-11-20 21:39:37 +10001704 /* stdin is always opened in buffered mode, first because it shouldn't
1705 make a difference in common use cases, second because TextIOWrapper
1706 depends on the presence of a read1() method which only exists on
1707 buffered streams.
1708 */
1709 if (Py_UnbufferedStdioFlag && write_mode)
1710 buffering = 0;
1711 else
1712 buffering = -1;
1713 if (write_mode)
1714 mode = "wb";
1715 else
1716 mode = "rb";
1717 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1718 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001719 Py_None, Py_None, /* encoding, errors */
1720 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001721 if (buf == NULL)
1722 goto error;
1723
1724 if (buffering) {
1725 _Py_IDENTIFIER(raw);
1726 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1727 if (raw == NULL)
1728 goto error;
1729 }
1730 else {
1731 raw = buf;
1732 Py_INCREF(raw);
1733 }
1734
Steve Dower39294992016-08-30 21:22:36 -07001735#ifdef MS_WINDOWS
1736 /* Windows console IO is always UTF-8 encoded */
1737 if (PyWindowsConsoleIO_Check(raw))
1738 encoding = "utf-8";
1739#endif
1740
Nick Coghland6009512014-11-20 21:39:37 +10001741 text = PyUnicode_FromString(name);
1742 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1743 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001744 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001745 if (res == NULL)
1746 goto error;
1747 isatty = PyObject_IsTrue(res);
1748 Py_DECREF(res);
1749 if (isatty == -1)
1750 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001751 if (Py_UnbufferedStdioFlag)
1752 write_through = Py_True;
1753 else
1754 write_through = Py_False;
1755 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001756 line_buffering = Py_True;
1757 else
1758 line_buffering = Py_False;
1759
1760 Py_CLEAR(raw);
1761 Py_CLEAR(text);
1762
1763#ifdef MS_WINDOWS
1764 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1765 newlines to "\n".
1766 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1767 newline = NULL;
1768#else
1769 /* sys.stdin: split lines at "\n".
1770 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1771 newline = "\n";
1772#endif
1773
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001774 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001775 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001776 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001777 Py_CLEAR(buf);
1778 if (stream == NULL)
1779 goto error;
1780
1781 if (write_mode)
1782 mode = "w";
1783 else
1784 mode = "r";
1785 text = PyUnicode_FromString(mode);
1786 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1787 goto error;
1788 Py_CLEAR(text);
1789 return stream;
1790
1791error:
1792 Py_XDECREF(buf);
1793 Py_XDECREF(stream);
1794 Py_XDECREF(text);
1795 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001796
Victor Stinner874dbe82015-09-04 17:29:57 +02001797 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1798 /* Issue #24891: the file descriptor was closed after the first
1799 is_valid_fd() check was called. Ignore the OSError and set the
1800 stream to None. */
1801 PyErr_Clear();
1802 Py_RETURN_NONE;
1803 }
1804 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001805}
1806
1807/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001808static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001809init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001810{
1811 PyObject *iomod = NULL, *wrapper;
1812 PyObject *bimod = NULL;
1813 PyObject *m;
1814 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001815 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001816 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001817 char *pythonioencoding = NULL;
1818 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001819 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001820
1821 /* Hack to avoid a nasty recursion issue when Python is invoked
1822 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1823 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1824 goto error;
1825 }
1826 Py_DECREF(m);
1827
1828 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1829 goto error;
1830 }
1831 Py_DECREF(m);
1832
1833 if (!(bimod = PyImport_ImportModule("builtins"))) {
1834 goto error;
1835 }
1836
1837 if (!(iomod = PyImport_ImportModule("io"))) {
1838 goto error;
1839 }
1840 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1841 goto error;
1842 }
1843
1844 /* Set builtins.open */
1845 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1846 Py_DECREF(wrapper);
1847 goto error;
1848 }
1849 Py_DECREF(wrapper);
1850
1851 encoding = _Py_StandardStreamEncoding;
1852 errors = _Py_StandardStreamErrors;
1853 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001854 char *opt = Py_GETENV("PYTHONIOENCODING");
1855 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001856 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001857 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001858 if (pythonioencoding == NULL) {
1859 PyErr_NoMemory();
1860 goto error;
1861 }
1862 err = strchr(pythonioencoding, ':');
1863 if (err) {
1864 *err = '\0';
1865 err++;
Victor Stinner0b9ea4b2018-08-29 11:01:33 +02001866 if (!err[0]) {
1867 err = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001868 }
1869 }
Victor Stinner0b9ea4b2018-08-29 11:01:33 +02001870
1871 /* Does PYTHONIOENCODING contain an encoding? */
1872 if (pythonioencoding[0]) {
1873 if (!encoding) {
1874 encoding = pythonioencoding;
1875 }
1876
1877 /* If the encoding is set but not the error handler,
1878 use "strict" error handler by default.
1879 PYTHONIOENCODING=latin1 behaves as
1880 PYTHONIOENCODING=latin1:strict. */
1881 if (!err) {
1882 err = "strict";
1883 }
1884 }
1885
1886 if (!errors && err != NULL) {
1887 errors = err;
Nick Coghland6009512014-11-20 21:39:37 +10001888 }
1889 }
Victor Stinner0b9ea4b2018-08-29 11:01:33 +02001890
1891 if (interp->core_config.utf8_mode) {
1892 if (!encoding) {
1893 encoding = "utf-8";
1894 }
1895 if (!errors) {
1896 errors = "surrogateescape";
1897 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001898 }
1899
Victor Stinner0b9ea4b2018-08-29 11:01:33 +02001900
1901 if (!errors) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001902 /* Choose the default error handler based on the current locale */
1903 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001904 }
Nick Coghland6009512014-11-20 21:39:37 +10001905 }
1906
1907 /* Set sys.stdin */
1908 fd = fileno(stdin);
1909 /* Under some conditions stdin, stdout and stderr may not be connected
1910 * and fileno() may point to an invalid file descriptor. For example
1911 * GUI apps don't have valid standard streams by default.
1912 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001913 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1914 if (std == NULL)
1915 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001916 PySys_SetObject("__stdin__", std);
1917 _PySys_SetObjectId(&PyId_stdin, std);
1918 Py_DECREF(std);
1919
1920 /* Set sys.stdout */
1921 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001922 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1923 if (std == NULL)
1924 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001925 PySys_SetObject("__stdout__", std);
1926 _PySys_SetObjectId(&PyId_stdout, std);
1927 Py_DECREF(std);
1928
1929#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1930 /* Set sys.stderr, replaces the preliminary stderr */
1931 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001932 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1933 if (std == NULL)
1934 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001935
1936 /* Same as hack above, pre-import stderr's codec to avoid recursion
1937 when import.c tries to write to stderr in verbose mode. */
1938 encoding_attr = PyObject_GetAttrString(std, "encoding");
1939 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001940 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001941 if (std_encoding != NULL) {
1942 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1943 Py_XDECREF(codec_info);
1944 }
1945 Py_DECREF(encoding_attr);
1946 }
1947 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1948
1949 if (PySys_SetObject("__stderr__", std) < 0) {
1950 Py_DECREF(std);
1951 goto error;
1952 }
1953 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1954 Py_DECREF(std);
1955 goto error;
1956 }
1957 Py_DECREF(std);
1958#endif
1959
Victor Stinnera7368ac2017-11-15 18:11:45 -08001960 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001961
Victor Stinnera7368ac2017-11-15 18:11:45 -08001962error:
1963 res = _Py_INIT_ERR("can't initialize sys standard streams");
1964
Victor Stinner31e99082017-12-20 23:41:38 +01001965 /* Use the same allocator than Py_SetStandardStreamEncoding() */
1966 PyMemAllocatorEx old_alloc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001967done:
Victor Stinner31e99082017-12-20 23:41:38 +01001968 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1969
Nick Coghland6009512014-11-20 21:39:37 +10001970 /* We won't need them anymore. */
1971 if (_Py_StandardStreamEncoding) {
1972 PyMem_RawFree(_Py_StandardStreamEncoding);
1973 _Py_StandardStreamEncoding = NULL;
1974 }
1975 if (_Py_StandardStreamErrors) {
1976 PyMem_RawFree(_Py_StandardStreamErrors);
1977 _Py_StandardStreamErrors = NULL;
1978 }
Victor Stinner31e99082017-12-20 23:41:38 +01001979
1980 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1981
Nick Coghland6009512014-11-20 21:39:37 +10001982 PyMem_Free(pythonioencoding);
1983 Py_XDECREF(bimod);
1984 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001985 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001986}
1987
1988
Victor Stinner10dc4842015-03-24 12:01:30 +01001989static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001990_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001991{
Victor Stinner10dc4842015-03-24 12:01:30 +01001992 fputc('\n', stderr);
1993 fflush(stderr);
1994
1995 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001996 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001997}
Victor Stinner791da1c2016-03-14 16:53:12 +01001998
1999/* Print the current exception (if an exception is set) with its traceback,
2000 or display the current Python stack.
2001
2002 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2003 called on catastrophic cases.
2004
2005 Return 1 if the traceback was displayed, 0 otherwise. */
2006
2007static int
2008_Py_FatalError_PrintExc(int fd)
2009{
2010 PyObject *ferr, *res;
2011 PyObject *exception, *v, *tb;
2012 int has_tb;
2013
2014 if (PyThreadState_GET() == NULL) {
2015 /* The GIL is released: trying to acquire it is likely to deadlock,
2016 just give up. */
2017 return 0;
2018 }
2019
2020 PyErr_Fetch(&exception, &v, &tb);
2021 if (exception == NULL) {
2022 /* No current exception */
2023 return 0;
2024 }
2025
2026 ferr = _PySys_GetObjectId(&PyId_stderr);
2027 if (ferr == NULL || ferr == Py_None) {
2028 /* sys.stderr is not set yet or set to None,
2029 no need to try to display the exception */
2030 return 0;
2031 }
2032
2033 PyErr_NormalizeException(&exception, &v, &tb);
2034 if (tb == NULL) {
2035 tb = Py_None;
2036 Py_INCREF(tb);
2037 }
2038 PyException_SetTraceback(v, tb);
2039 if (exception == NULL) {
2040 /* PyErr_NormalizeException() failed */
2041 return 0;
2042 }
2043
2044 has_tb = (tb != Py_None);
2045 PyErr_Display(exception, v, tb);
2046 Py_XDECREF(exception);
2047 Py_XDECREF(v);
2048 Py_XDECREF(tb);
2049
2050 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002051 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002052 if (res == NULL)
2053 PyErr_Clear();
2054 else
2055 Py_DECREF(res);
2056
2057 return has_tb;
2058}
2059
Nick Coghland6009512014-11-20 21:39:37 +10002060/* Print fatal error message and abort */
2061
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002062#ifdef MS_WINDOWS
2063static void
2064fatal_output_debug(const char *msg)
2065{
2066 /* buffer of 256 bytes allocated on the stack */
2067 WCHAR buffer[256 / sizeof(WCHAR)];
2068 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2069 size_t msglen;
2070
2071 OutputDebugStringW(L"Fatal Python error: ");
2072
2073 msglen = strlen(msg);
2074 while (msglen) {
2075 size_t i;
2076
2077 if (buflen > msglen) {
2078 buflen = msglen;
2079 }
2080
2081 /* Convert the message to wchar_t. This uses a simple one-to-one
2082 conversion, assuming that the this error message actually uses
2083 ASCII only. If this ceases to be true, we will have to convert. */
2084 for (i=0; i < buflen; ++i) {
2085 buffer[i] = msg[i];
2086 }
2087 buffer[i] = L'\0';
2088 OutputDebugStringW(buffer);
2089
2090 msg += buflen;
2091 msglen -= buflen;
2092 }
2093 OutputDebugStringW(L"\n");
2094}
2095#endif
2096
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002097static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002098fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002099{
2100 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002101 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002102
2103 if (reentrant) {
2104 /* Py_FatalError() caused a second fatal error.
2105 Example: flush_std_files() raises a recursion error. */
2106 goto exit;
2107 }
2108 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002109
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002110 fprintf(stderr, "Fatal Python error: ");
2111 if (prefix) {
2112 fputs(prefix, stderr);
2113 fputs(": ", stderr);
2114 }
2115 if (msg) {
2116 fputs(msg, stderr);
2117 }
2118 else {
2119 fprintf(stderr, "<message not set>");
2120 }
2121 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002122 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002123
Victor Stinnere0deff32015-03-24 13:46:18 +01002124 /* Print the exception (if an exception is set) with its traceback,
2125 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002126 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002127 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002128 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002129
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002130 /* The main purpose of faulthandler is to display the traceback.
2131 This function already did its best to display a traceback.
2132 Disable faulthandler to prevent writing a second traceback
2133 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002134 _PyFaulthandler_Fini();
2135
Victor Stinner791da1c2016-03-14 16:53:12 +01002136 /* Check if the current Python thread hold the GIL */
2137 if (PyThreadState_GET() != NULL) {
2138 /* Flush sys.stdout and sys.stderr */
2139 flush_std_files();
2140 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002141
Nick Coghland6009512014-11-20 21:39:37 +10002142#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002143 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002144#endif /* MS_WINDOWS */
2145
2146exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002147 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002148#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002149 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002150#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002151 abort();
2152 }
2153 else {
2154 exit(status);
2155 }
2156}
2157
Victor Stinner19760862017-12-20 01:41:59 +01002158void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002159Py_FatalError(const char *msg)
2160{
2161 fatal_error(NULL, msg, -1);
2162}
2163
Victor Stinner19760862017-12-20 01:41:59 +01002164void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002165_Py_FatalInitError(_PyInitError err)
2166{
2167 /* On "user" error: exit with status 1.
2168 For all other errors, call abort(). */
2169 int status = err.user_err ? 1 : -1;
2170 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002171}
2172
2173/* Clean up and exit */
2174
Victor Stinnerd7292b52016-06-17 12:29:00 +02002175# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002176
Nick Coghland6009512014-11-20 21:39:37 +10002177/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002178void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002179{
Marcel Plch776407f2017-12-20 11:17:58 +01002180 PyThreadState *ts;
2181 PyInterpreterState *is;
Victor Stinnerca719ac2017-12-20 18:00:19 +01002182
Marcel Plch776407f2017-12-20 11:17:58 +01002183 ts = PyThreadState_GET();
2184 is = ts->interp;
2185
Antoine Pitroufc5db952017-12-13 02:29:07 +01002186 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002187 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2188
2189 is->pyexitfunc = func;
2190 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002191}
2192
2193static void
Marcel Plch776407f2017-12-20 11:17:58 +01002194call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002195{
Marcel Plch776407f2017-12-20 11:17:58 +01002196 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002197 return;
2198
Marcel Plch776407f2017-12-20 11:17:58 +01002199 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002200 PyErr_Clear();
2201}
2202
2203/* Wait until threading._shutdown completes, provided
2204 the threading module was imported in the first place.
2205 The shutdown routine will wait until all non-daemon
2206 "threading" threads have completed. */
2207static void
2208wait_for_thread_shutdown(void)
2209{
Nick Coghland6009512014-11-20 21:39:37 +10002210 _Py_IDENTIFIER(_shutdown);
2211 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002212 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002213 if (threading == NULL) {
2214 /* threading not imported */
2215 PyErr_Clear();
2216 return;
2217 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002218 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002219 if (result == NULL) {
2220 PyErr_WriteUnraisable(threading);
2221 }
2222 else {
2223 Py_DECREF(result);
2224 }
2225 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002226}
2227
2228#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002229int Py_AtExit(void (*func)(void))
2230{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002231 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002232 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002233 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002234 return 0;
2235}
2236
2237static void
2238call_ll_exitfuncs(void)
2239{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002240 while (_PyRuntime.nexitfuncs > 0)
2241 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002242
2243 fflush(stdout);
2244 fflush(stderr);
2245}
2246
2247void
2248Py_Exit(int sts)
2249{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002250 if (Py_FinalizeEx() < 0) {
2251 sts = 120;
2252 }
Nick Coghland6009512014-11-20 21:39:37 +10002253
2254 exit(sts);
2255}
2256
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002257static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002258initsigs(void)
2259{
2260#ifdef SIGPIPE
2261 PyOS_setsig(SIGPIPE, SIG_IGN);
2262#endif
2263#ifdef SIGXFZ
2264 PyOS_setsig(SIGXFZ, SIG_IGN);
2265#endif
2266#ifdef SIGXFSZ
2267 PyOS_setsig(SIGXFSZ, SIG_IGN);
2268#endif
2269 PyOS_InitInterrupts(); /* May imply initsignal() */
2270 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002271 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002272 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002273 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002274}
2275
2276
2277/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2278 *
2279 * All of the code in this function must only use async-signal-safe functions,
2280 * listed at `man 7 signal` or
2281 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2282 */
2283void
2284_Py_RestoreSignals(void)
2285{
2286#ifdef SIGPIPE
2287 PyOS_setsig(SIGPIPE, SIG_DFL);
2288#endif
2289#ifdef SIGXFZ
2290 PyOS_setsig(SIGXFZ, SIG_DFL);
2291#endif
2292#ifdef SIGXFSZ
2293 PyOS_setsig(SIGXFSZ, SIG_DFL);
2294#endif
2295}
2296
2297
2298/*
2299 * The file descriptor fd is considered ``interactive'' if either
2300 * a) isatty(fd) is TRUE, or
2301 * b) the -i flag was given, and the filename associated with
2302 * the descriptor is NULL or "<stdin>" or "???".
2303 */
2304int
2305Py_FdIsInteractive(FILE *fp, const char *filename)
2306{
2307 if (isatty((int)fileno(fp)))
2308 return 1;
2309 if (!Py_InteractiveFlag)
2310 return 0;
2311 return (filename == NULL) ||
2312 (strcmp(filename, "<stdin>") == 0) ||
2313 (strcmp(filename, "???") == 0);
2314}
2315
2316
Nick Coghland6009512014-11-20 21:39:37 +10002317/* Wrappers around sigaction() or signal(). */
2318
2319PyOS_sighandler_t
2320PyOS_getsig(int sig)
2321{
2322#ifdef HAVE_SIGACTION
2323 struct sigaction context;
2324 if (sigaction(sig, NULL, &context) == -1)
2325 return SIG_ERR;
2326 return context.sa_handler;
2327#else
2328 PyOS_sighandler_t handler;
2329/* Special signal handling for the secure CRT in Visual Studio 2005 */
2330#if defined(_MSC_VER) && _MSC_VER >= 1400
2331 switch (sig) {
2332 /* Only these signals are valid */
2333 case SIGINT:
2334 case SIGILL:
2335 case SIGFPE:
2336 case SIGSEGV:
2337 case SIGTERM:
2338 case SIGBREAK:
2339 case SIGABRT:
2340 break;
2341 /* Don't call signal() with other values or it will assert */
2342 default:
2343 return SIG_ERR;
2344 }
2345#endif /* _MSC_VER && _MSC_VER >= 1400 */
2346 handler = signal(sig, SIG_IGN);
2347 if (handler != SIG_ERR)
2348 signal(sig, handler);
2349 return handler;
2350#endif
2351}
2352
2353/*
2354 * All of the code in this function must only use async-signal-safe functions,
2355 * listed at `man 7 signal` or
2356 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2357 */
2358PyOS_sighandler_t
2359PyOS_setsig(int sig, PyOS_sighandler_t handler)
2360{
2361#ifdef HAVE_SIGACTION
2362 /* Some code in Modules/signalmodule.c depends on sigaction() being
2363 * used here if HAVE_SIGACTION is defined. Fix that if this code
2364 * changes to invalidate that assumption.
2365 */
2366 struct sigaction context, ocontext;
2367 context.sa_handler = handler;
2368 sigemptyset(&context.sa_mask);
2369 context.sa_flags = 0;
2370 if (sigaction(sig, &context, &ocontext) == -1)
2371 return SIG_ERR;
2372 return ocontext.sa_handler;
2373#else
2374 PyOS_sighandler_t oldhandler;
2375 oldhandler = signal(sig, handler);
2376#ifdef HAVE_SIGINTERRUPT
2377 siginterrupt(sig, 1);
2378#endif
2379 return oldhandler;
2380#endif
2381}
2382
2383#ifdef __cplusplus
2384}
2385#endif