blob: 4b08c9c2b2ce85797a4328527e01e035d4b665d5 [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{
Victor Stinnerf6e323c2018-11-23 13:37:42 +0100526 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100527#ifdef __ANDROID__
528 const char *locale;
529 const char **pvar;
530#ifdef PY_COERCE_C_LOCALE
531 const char *coerce_c_locale;
532#endif
533 const char *utf8_locale = "C.UTF-8";
534 const char *env_var_set[] = {
535 "LC_ALL",
536 "LC_CTYPE",
537 "LANG",
538 NULL,
539 };
540
541 /* Android setlocale(category, "") doesn't check the environment variables
542 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
543 * check the environment variables listed in env_var_set. */
544 for (pvar=env_var_set; *pvar; pvar++) {
545 locale = getenv(*pvar);
546 if (locale != NULL && *locale != '\0') {
547 if (strcmp(locale, utf8_locale) == 0 ||
548 strcmp(locale, "en_US.UTF-8") == 0) {
549 return setlocale(category, utf8_locale);
550 }
551 return setlocale(category, "C");
552 }
553 }
554
555 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
556 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
557 * Quote from POSIX section "8.2 Internationalization Variables":
558 * "4. If the LANG environment variable is not set or is set to the empty
559 * string, the implementation-defined default locale shall be used." */
560
561#ifdef PY_COERCE_C_LOCALE
562 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
563 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
564 /* Some other ported code may check the environment variables (e.g. in
565 * extension modules), so we make sure that they match the locale
566 * configuration */
567 if (setenv("LC_CTYPE", utf8_locale, 1)) {
568 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
569 "environment variable to %s\n", utf8_locale);
570 }
571 }
572#endif
Victor Stinnerf6e323c2018-11-23 13:37:42 +0100573 res = setlocale(category, utf8_locale);
574#else /* !defined(__ANDROID__) */
575 res = setlocale(category, "");
576#endif
577 _Py_ResetForceASCII();
578 return res;
xdegaye1588be62017-11-12 12:45:59 +0100579}
580
Nick Coghlan6ea41862017-06-11 13:16:15 +1000581
Eric Snow1abcf672017-05-23 21:46:51 -0700582/* Global initializations. Can be undone by Py_Finalize(). Don't
583 call this twice without an intervening Py_Finalize() call.
584
585 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
586 must have a corresponding call to Py_Finalize.
587
588 Locking: you must hold the interpreter lock while calling these APIs.
589 (If the lock has not yet been initialized, that's equivalent to
590 having the lock, but you cannot use multiple threads.)
591
592*/
593
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200594static _PyInitError
595_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
596 const _PyCoreConfig *core_config)
597{
598 if (core_config->allocator != NULL) {
599 const char *allocator = _PyMem_GetAllocatorsName();
600 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
601 return _Py_INIT_USER_ERR("cannot modify memory allocator "
602 "after first Py_Initialize()");
603 }
604 }
605
606 _PyCoreConfig_SetGlobalConfig(core_config);
607
608 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
609 return _Py_INIT_ERR("failed to copy core config");
610 }
611 return _Py_INIT_OK();
612}
613
614
Eric Snow1abcf672017-05-23 21:46:51 -0700615/* Begin interpreter initialization
616 *
617 * On return, the first thread and interpreter state have been created,
618 * but the compiler, signal handling, multithreading and
619 * multiple interpreter support, and codec infrastructure are not yet
620 * available.
621 *
622 * The import system will support builtin and frozen modules only.
623 * The only supported io is writing to sys.stderr
624 *
625 * If any operation invoked by this function fails, a fatal error is
626 * issued and the function does not return.
627 *
628 * Any code invoked from this function should *not* assume it has access
629 * to the Python C API (unless the API is explicitly listed as being
630 * safe to call without calling Py_Initialize first)
631 */
632
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800633_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200634_Py_InitializeCore_impl(PyInterpreterState **interp_p,
635 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000636{
637 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800638 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000639
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200640 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
641 Py_Initialize() ignores the new configuration. */
642 if (_PyRuntime.core_initialized) {
643 PyThreadState *tstate = PyThreadState_GET();
644 if (!tstate) {
645 return _Py_INIT_ERR("no thread state found");
646 }
647
648 interp = tstate->interp;
649 if (interp == NULL) {
650 return _Py_INIT_ERR("no main interpreter found");
651 }
652 *interp_p = interp;
653
654 return _Py_Initialize_ReconfigureCore(interp, core_config);
655 }
656
657
658 _PyCoreConfig_SetGlobalConfig(core_config);
659
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800660 err = _PyRuntime_Initialize();
661 if (_Py_INIT_FAILED(err)) {
662 return err;
663 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600664
Victor Stinner31e99082017-12-20 23:41:38 +0100665 if (core_config->allocator != NULL) {
666 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
667 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
668 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800669 }
670
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600671 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800672 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700673 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600674 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800675 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700676 }
677
678 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
679 * threads behave a little more gracefully at interpreter shutdown.
680 * We clobber it here so the new interpreter can start with a clean
681 * slate.
682 *
683 * However, this may still lead to misbehaviour if there are daemon
684 * threads still hanging around from a previous Py_Initialize/Finalize
685 * pair :(
686 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600687 _PyRuntime.finalizing = NULL;
688
Nick Coghlan6ea41862017-06-11 13:16:15 +1000689#ifndef MS_WINDOWS
Victor Stinner94540602017-12-16 04:54:22 +0100690 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000691#endif
Nick Coghland6009512014-11-20 21:39:37 +1000692
Victor Stinnerda273412017-12-15 01:46:02 +0100693 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800694 if (_Py_INIT_FAILED(err)) {
695 return err;
696 }
697
Victor Stinnerda273412017-12-15 01:46:02 +0100698 if (!core_config->use_hash_seed || core_config->hash_seed) {
Eric Snow1abcf672017-05-23 21:46:51 -0700699 /* Random or non-zero hash seed */
700 Py_HashRandomizationFlag = 1;
701 }
Nick Coghland6009512014-11-20 21:39:37 +1000702
Victor Stinnera7368ac2017-11-15 18:11:45 -0800703 err = _PyInterpreterState_Enable(&_PyRuntime);
704 if (_Py_INIT_FAILED(err)) {
705 return err;
706 }
707
Nick Coghland6009512014-11-20 21:39:37 +1000708 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100709 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800710 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100711 }
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200712 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100713
714 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
715 return _Py_INIT_ERR("failed to copy core config");
716 }
Nick Coghland6009512014-11-20 21:39:37 +1000717
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200718 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000719 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800720 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000721 (void) PyThreadState_Swap(tstate);
722
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000723 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000724 destroying the GIL might fail when it is being referenced from
725 another running thread (see issue #9901).
726 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000727 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000728 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100729
Nick Coghland6009512014-11-20 21:39:37 +1000730 /* Auto-thread-state API */
731 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000732
Victor Stinner2914bb32018-01-29 11:57:45 +0100733 /* Create the GIL */
734 PyEval_InitThreads();
735
Nick Coghland6009512014-11-20 21:39:37 +1000736 _Py_ReadyTypes();
737
738 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800739 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000740
741 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800742 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000743
744 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800745 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000746
747 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800748 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000749
Eric Snowd393c1b2017-09-14 12:18:12 -0600750 PyObject *modules = PyDict_New();
751 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800752 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600753 interp->modules = modules;
754
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200755 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800756 err = _PySys_BeginInit(&sysmod);
757 if (_Py_INIT_FAILED(err)) {
758 return err;
759 }
760
Eric Snowd393c1b2017-09-14 12:18:12 -0600761 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800762 if (interp->sysdict == NULL) {
763 return _Py_INIT_ERR("can't initialize sys dict");
764 }
765
Eric Snowd393c1b2017-09-14 12:18:12 -0600766 Py_INCREF(interp->sysdict);
767 PyDict_SetItemString(interp->sysdict, "modules", modules);
768 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000769
770 /* Init Unicode implementation; relies on the codec registry */
771 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800772 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700773
Nick Coghland6009512014-11-20 21:39:37 +1000774 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800775 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000776
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200777 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000778 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800779 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600780 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000781 interp->builtins = PyModule_GetDict(bimod);
782 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800783 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000784 Py_INCREF(interp->builtins);
785
786 /* initialize builtin exceptions */
787 _PyExc_Init(bimod);
788
Nick Coghland6009512014-11-20 21:39:37 +1000789 /* Set up a preliminary stderr printer until we have enough
790 infrastructure for the io module in place. */
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200791 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000792 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800793 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000794 _PySys_SetObjectId(&PyId_stderr, pstderr);
795 PySys_SetObject("__stderr__", pstderr);
796 Py_DECREF(pstderr);
797
Victor Stinner672b6ba2017-12-06 17:25:50 +0100798 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800799 if (_Py_INIT_FAILED(err)) {
800 return err;
801 }
Nick Coghland6009512014-11-20 21:39:37 +1000802
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800803 err = _PyImportHooks_Init();
804 if (_Py_INIT_FAILED(err)) {
805 return err;
806 }
Nick Coghland6009512014-11-20 21:39:37 +1000807
808 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100809 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100810 return _Py_INIT_ERR("can't initialize warnings");
811 }
Nick Coghland6009512014-11-20 21:39:37 +1000812
Yury Selivanovf23746a2018-01-22 19:11:18 -0500813 if (!_PyContext_Init())
814 return _Py_INIT_ERR("can't init context");
815
Eric Snow1abcf672017-05-23 21:46:51 -0700816 /* This call sets up builtin and frozen import support */
817 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800818 err = initimport(interp, sysmod);
819 if (_Py_INIT_FAILED(err)) {
820 return err;
821 }
Eric Snow1abcf672017-05-23 21:46:51 -0700822 }
823
824 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600825 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800826 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700827}
828
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200829
830_PyInitError
831_Py_InitializeCore(PyInterpreterState **interp_p,
832 const _PyCoreConfig *src_config)
833{
834 assert(src_config != NULL);
835
836 PyMemAllocatorEx old_alloc;
837 _PyInitError err;
838
839 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
840 (and the input configuration is read only). */
841 _PyCoreConfig config = _PyCoreConfig_INIT;
842
Victor Stinner98c49c62018-08-29 01:13:29 +0200843#ifndef MS_WINDOWS
844 /* Set up the LC_CTYPE locale, so we can obtain the locale's charset
845 without having to switch locales. */
846 _Py_SetLocaleFromEnv(LC_CTYPE);
847#endif
848
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200849 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
850 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
851 err = _PyCoreConfig_Read(&config);
852 }
853 else {
854 err = _Py_INIT_ERR("failed to copy core config");
855 }
856 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
857
858 if (_Py_INIT_FAILED(err)) {
859 goto done;
860 }
861
862 err = _Py_InitializeCore_impl(interp_p, &config);
863
864done:
865 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
866 _PyCoreConfig_Clear(&config);
867 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
868
869 return err;
870}
871
Miss Islington (bot)03ec4df2018-07-20 17:16:22 -0700872/* Py_Initialize() has already been called: update the main interpreter
873 configuration. Example of bpo-34008: Py_Main() called after
874 Py_Initialize(). */
875static _PyInitError
876_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
877 const _PyMainInterpreterConfig *config)
878{
879 if (config->argv != NULL) {
880 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
881 if (res < 0) {
882 return _Py_INIT_ERR("fail to set sys.argv");
883 }
884 }
885 return _Py_INIT_OK();
886}
887
Eric Snowc7ec9982017-05-23 23:00:52 -0700888/* Update interpreter state based on supplied configuration settings
889 *
890 * After calling this function, most of the restrictions on the interpreter
891 * are lifted. The only remaining incomplete settings are those related
892 * to the main module (sys.argv[0], __main__ metadata)
893 *
894 * Calling this when the interpreter is not initializing, is already
895 * initialized or without a valid current thread state is a fatal error.
896 * Other errors should be reported as normal Python exceptions with a
897 * non-zero return code.
898 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800899_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200900_Py_InitializeMainInterpreter(PyInterpreterState *interp,
901 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700902{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800903 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700904
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600905 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800906 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700907 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700908
Eric Snow1abcf672017-05-23 21:46:51 -0700909 /* Now finish configuring the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100910 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
911 return _Py_INIT_ERR("failed to copy main interpreter config");
912 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700913
Miss Islington (bot)03ec4df2018-07-20 17:16:22 -0700914 if (_PyRuntime.initialized) {
915 return _Py_ReconfigureMainInterpreter(interp, config);
916 }
917
Eric Snow1abcf672017-05-23 21:46:51 -0700918 if (interp->core_config._disable_importlib) {
919 /* Special mode for freeze_importlib: run with no import system
920 *
921 * This means anything which needs support from extension modules
922 * or pure Python code in the standard library won't work.
923 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600924 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800925 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700926 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100927
Victor Stinner33c377e2017-12-05 15:12:41 +0100928 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800929 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100930 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200931
Victor Stinner41264f12017-12-15 02:05:29 +0100932 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800933 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100934 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800935
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800936 err = initexternalimport(interp);
937 if (_Py_INIT_FAILED(err)) {
938 return err;
939 }
Nick Coghland6009512014-11-20 21:39:37 +1000940
941 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800942 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800943 if (_Py_INIT_FAILED(err)) {
944 return err;
945 }
Nick Coghland6009512014-11-20 21:39:37 +1000946
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800947 err = initfsencoding(interp);
948 if (_Py_INIT_FAILED(err)) {
949 return err;
950 }
Nick Coghland6009512014-11-20 21:39:37 +1000951
Victor Stinner1f151112017-11-23 10:43:14 +0100952 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800953 err = initsigs(); /* Signal handling stuff, including initintr() */
954 if (_Py_INIT_FAILED(err)) {
955 return err;
956 }
957 }
Nick Coghland6009512014-11-20 21:39:37 +1000958
Victor Stinnera7368ac2017-11-15 18:11:45 -0800959 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800960 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000961
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800962 err = add_main_module(interp);
963 if (_Py_INIT_FAILED(err)) {
964 return err;
965 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800966
Victor Stinner91106cd2017-12-13 12:29:09 +0100967 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800968 if (_Py_INIT_FAILED(err)) {
969 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800970 }
Nick Coghland6009512014-11-20 21:39:37 +1000971
972 /* Initialize warnings. */
Victor Stinnera5194112018-11-22 16:11:15 +0100973 if (interp->config.warnoptions != NULL &&
974 PyList_Size(interp->config.warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100975 {
Nick Coghland6009512014-11-20 21:39:37 +1000976 PyObject *warnings_module = PyImport_ImportModule("warnings");
977 if (warnings_module == NULL) {
978 fprintf(stderr, "'import warnings' failed; traceback:\n");
979 PyErr_Print();
980 }
981 Py_XDECREF(warnings_module);
982 }
983
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600984 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700985
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800986 if (!Py_NoSiteFlag) {
987 err = initsite(); /* Module site */
988 if (_Py_INIT_FAILED(err)) {
989 return err;
990 }
991 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800992 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000993}
994
Eric Snowc7ec9982017-05-23 23:00:52 -0700995#undef _INIT_DEBUG_PRINT
996
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200997
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800998_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200999_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001000{
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001001 _Py_Initialize_ReadEnvVarsNoAlloc();
Miss Islington (bot)3747dd12018-06-22 10:33:48 -07001002
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001003 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001004 _PyInitError err;
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001005 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001006 if (_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001007 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001008 }
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001009 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001010
Victor Stinner9cfc0022017-12-20 19:36:46 +01001011 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001012 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +01001013 if (!_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001014 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001015 }
Victor Stinner9cfc0022017-12-20 19:36:46 +01001016 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001017 if (_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001018 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001019 }
1020
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001021 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001022}
1023
1024
1025void
Nick Coghland6009512014-11-20 21:39:37 +10001026Py_InitializeEx(int install_sigs)
1027{
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001028 if (_PyRuntime.initialized) {
1029 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1030 return;
1031 }
1032
1033 _PyInitError err;
1034 _PyCoreConfig config = _PyCoreConfig_INIT;
1035 config.install_signal_handlers = install_sigs;
1036
1037 err = _Py_InitializeFromConfig(&config);
1038 _PyCoreConfig_Clear(&config);
1039
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001040 if (_Py_INIT_FAILED(err)) {
1041 _Py_FatalInitError(err);
1042 }
Nick Coghland6009512014-11-20 21:39:37 +10001043}
1044
1045void
1046Py_Initialize(void)
1047{
1048 Py_InitializeEx(1);
1049}
1050
1051
1052#ifdef COUNT_ALLOCS
1053extern void dump_counts(FILE*);
1054#endif
1055
1056/* Flush stdout and stderr */
1057
1058static int
1059file_is_closed(PyObject *fobj)
1060{
1061 int r;
1062 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1063 if (tmp == NULL) {
1064 PyErr_Clear();
1065 return 0;
1066 }
1067 r = PyObject_IsTrue(tmp);
1068 Py_DECREF(tmp);
1069 if (r < 0)
1070 PyErr_Clear();
1071 return r > 0;
1072}
1073
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001074static int
Nick Coghland6009512014-11-20 21:39:37 +10001075flush_std_files(void)
1076{
1077 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1078 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1079 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001080 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001081
1082 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001083 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001084 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001085 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001086 status = -1;
1087 }
Nick Coghland6009512014-11-20 21:39:37 +10001088 else
1089 Py_DECREF(tmp);
1090 }
1091
1092 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001093 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001094 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001095 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001096 status = -1;
1097 }
Nick Coghland6009512014-11-20 21:39:37 +10001098 else
1099 Py_DECREF(tmp);
1100 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001101
1102 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001103}
1104
1105/* Undo the effect of Py_Initialize().
1106
1107 Beware: if multiple interpreter and/or thread states exist, these
1108 are not wiped out; only the current thread and interpreter state
1109 are deleted. But since everything else is deleted, those other
1110 interpreter and thread states should no longer be used.
1111
1112 (XXX We should do better, e.g. wipe out all interpreters and
1113 threads.)
1114
1115 Locking: as above.
1116
1117*/
1118
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001119int
1120Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001121{
1122 PyInterpreterState *interp;
1123 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001124 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001125
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001126 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001127 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001128
1129 wait_for_thread_shutdown();
1130
Marcel Plch776407f2017-12-20 11:17:58 +01001131 /* Get current thread state and interpreter pointer */
1132 tstate = PyThreadState_GET();
1133 interp = tstate->interp;
1134
Nick Coghland6009512014-11-20 21:39:37 +10001135 /* The interpreter is still entirely intact at this point, and the
1136 * exit funcs may be relying on that. In particular, if some thread
1137 * or exit func is still waiting to do an import, the import machinery
1138 * expects Py_IsInitialized() to return true. So don't say the
1139 * interpreter is uninitialized until after the exit funcs have run.
1140 * Note that Threading.py uses an exit func to do a join on all the
1141 * threads created thru it, so this also protects pending imports in
1142 * the threads created via Threading.
1143 */
Nick Coghland6009512014-11-20 21:39:37 +10001144
Marcel Plch776407f2017-12-20 11:17:58 +01001145 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001146
Victor Stinnerda273412017-12-15 01:46:02 +01001147 /* Copy the core config, PyInterpreterState_Delete() free
1148 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001149#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001150 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001151#endif
1152#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001153 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001154#endif
1155#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001156 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001157#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001158
Nick Coghland6009512014-11-20 21:39:37 +10001159 /* Remaining threads (e.g. daemon threads) will automatically exit
1160 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001161 _PyRuntime.finalizing = tstate;
1162 _PyRuntime.initialized = 0;
1163 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001164
Victor Stinnere0deff32015-03-24 13:46:18 +01001165 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001166 if (flush_std_files() < 0) {
1167 status = -1;
1168 }
Nick Coghland6009512014-11-20 21:39:37 +10001169
1170 /* Disable signal handling */
1171 PyOS_FiniInterrupts();
1172
1173 /* Collect garbage. This may call finalizers; it's nice to call these
1174 * before all modules are destroyed.
1175 * XXX If a __del__ or weakref callback is triggered here, and tries to
1176 * XXX import a module, bad things can happen, because Python no
1177 * XXX longer believes it's initialized.
1178 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1179 * XXX is easy to provoke that way. I've also seen, e.g.,
1180 * XXX Exception exceptions.ImportError: 'No module named sha'
1181 * XXX in <function callback at 0x008F5718> ignored
1182 * XXX but I'm unclear on exactly how that one happens. In any case,
1183 * XXX I haven't seen a real-life report of either of these.
1184 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001185 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001186#ifdef COUNT_ALLOCS
1187 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1188 each collection might release some types from the type
1189 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001190 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001191 /* nothing */;
1192#endif
Eric Snowdae02762017-09-14 00:35:58 -07001193
Nick Coghland6009512014-11-20 21:39:37 +10001194 /* Destroy all modules */
1195 PyImport_Cleanup();
1196
Victor Stinnere0deff32015-03-24 13:46:18 +01001197 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001198 if (flush_std_files() < 0) {
1199 status = -1;
1200 }
Nick Coghland6009512014-11-20 21:39:37 +10001201
1202 /* Collect final garbage. This disposes of cycles created by
1203 * class definitions, for example.
1204 * XXX This is disabled because it caused too many problems. If
1205 * XXX a __del__ or weakref callback triggers here, Python code has
1206 * XXX a hard time running, because even the sys module has been
1207 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1208 * XXX One symptom is a sequence of information-free messages
1209 * XXX coming from threads (if a __del__ or callback is invoked,
1210 * XXX other threads can execute too, and any exception they encounter
1211 * XXX triggers a comedy of errors as subsystem after subsystem
1212 * XXX fails to find what it *expects* to find in sys to help report
1213 * XXX the exception and consequent unexpected failures). I've also
1214 * XXX seen segfaults then, after adding print statements to the
1215 * XXX Python code getting called.
1216 */
1217#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001218 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001219#endif
1220
1221 /* Disable tracemalloc after all Python objects have been destroyed,
1222 so it is possible to use tracemalloc in objects destructor. */
1223 _PyTraceMalloc_Fini();
1224
1225 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1226 _PyImport_Fini();
1227
1228 /* Cleanup typeobject.c's internal caches. */
1229 _PyType_Fini();
1230
1231 /* unload faulthandler module */
1232 _PyFaulthandler_Fini();
1233
1234 /* Debugging stuff */
1235#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001236 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001237#endif
1238 /* dump hash stats */
1239 _PyHash_Fini();
1240
Eric Snowdae02762017-09-14 00:35:58 -07001241#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001242 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001243 _PyDebug_PrintTotalRefs();
1244 }
Eric Snowdae02762017-09-14 00:35:58 -07001245#endif
Nick Coghland6009512014-11-20 21:39:37 +10001246
1247#ifdef Py_TRACE_REFS
1248 /* Display all objects still alive -- this can invoke arbitrary
1249 * __repr__ overrides, so requires a mostly-intact interpreter.
1250 * Alas, a lot of stuff may still be alive now that will be cleaned
1251 * up later.
1252 */
Victor Stinnerda273412017-12-15 01:46:02 +01001253 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001254 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001255 }
Nick Coghland6009512014-11-20 21:39:37 +10001256#endif /* Py_TRACE_REFS */
1257
1258 /* Clear interpreter state and all thread states. */
1259 PyInterpreterState_Clear(interp);
1260
1261 /* Now we decref the exception classes. After this point nothing
1262 can raise an exception. That's okay, because each Fini() method
1263 below has been checked to make sure no exceptions are ever
1264 raised.
1265 */
1266
1267 _PyExc_Fini();
1268
1269 /* Sundry finalizers */
1270 PyMethod_Fini();
1271 PyFrame_Fini();
1272 PyCFunction_Fini();
1273 PyTuple_Fini();
1274 PyList_Fini();
1275 PySet_Fini();
1276 PyBytes_Fini();
1277 PyByteArray_Fini();
1278 PyLong_Fini();
1279 PyFloat_Fini();
1280 PyDict_Fini();
1281 PySlice_Fini();
1282 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001283 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001284 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001285 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001286 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001287
1288 /* Cleanup Unicode implementation */
1289 _PyUnicode_Fini();
1290
1291 /* reset file system default encoding */
1292 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1293 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1294 Py_FileSystemDefaultEncoding = NULL;
1295 }
1296
1297 /* XXX Still allocated:
1298 - various static ad-hoc pointers to interned strings
1299 - int and float free list blocks
1300 - whatever various modules and libraries allocate
1301 */
1302
1303 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1304
1305 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001306 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001307
1308 /* Delete current thread. After this, many C API calls become crashy. */
1309 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001310
Nick Coghland6009512014-11-20 21:39:37 +10001311 PyInterpreterState_Delete(interp);
1312
1313#ifdef Py_TRACE_REFS
1314 /* Display addresses (& refcnts) of all objects still alive.
1315 * An address can be used to find the repr of the object, printed
1316 * above by _Py_PrintReferences.
1317 */
Victor Stinnerda273412017-12-15 01:46:02 +01001318 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001319 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001320 }
Nick Coghland6009512014-11-20 21:39:37 +10001321#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001322#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001323 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001324 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001325 }
Nick Coghland6009512014-11-20 21:39:37 +10001326#endif
1327
1328 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001329
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001330 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001331 return status;
1332}
1333
1334void
1335Py_Finalize(void)
1336{
1337 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001338}
1339
1340/* Create and initialize a new interpreter and thread, and return the
1341 new thread. This requires that Py_Initialize() has been called
1342 first.
1343
1344 Unsuccessful initialization yields a NULL pointer. Note that *no*
1345 exception information is available even in this case -- the
1346 exception information is held in the thread, and there is no
1347 thread.
1348
1349 Locking: as above.
1350
1351*/
1352
Victor Stinnera7368ac2017-11-15 18:11:45 -08001353static _PyInitError
1354new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001355{
1356 PyInterpreterState *interp;
1357 PyThreadState *tstate, *save_tstate;
1358 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001359 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001360
Victor Stinnera7368ac2017-11-15 18:11:45 -08001361 if (!_PyRuntime.initialized) {
1362 return _Py_INIT_ERR("Py_Initialize must be called first");
1363 }
Nick Coghland6009512014-11-20 21:39:37 +10001364
Victor Stinner8a1be612016-03-14 22:07:55 +01001365 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1366 interpreters: disable PyGILState_Check(). */
1367 _PyGILState_check_enabled = 0;
1368
Nick Coghland6009512014-11-20 21:39:37 +10001369 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001370 if (interp == NULL) {
1371 *tstate_p = NULL;
1372 return _Py_INIT_OK();
1373 }
Nick Coghland6009512014-11-20 21:39:37 +10001374
1375 tstate = PyThreadState_New(interp);
1376 if (tstate == NULL) {
1377 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001378 *tstate_p = NULL;
1379 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001380 }
1381
1382 save_tstate = PyThreadState_Swap(tstate);
1383
Eric Snow1abcf672017-05-23 21:46:51 -07001384 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001385 _PyCoreConfig *core_config;
1386 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001387 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001388 core_config = &save_tstate->interp->core_config;
1389 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001390 } else {
1391 /* No current thread state, copy from the main interpreter */
1392 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001393 core_config = &main_interp->core_config;
1394 config = &main_interp->config;
1395 }
1396
1397 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1398 return _Py_INIT_ERR("failed to copy core config");
1399 }
1400 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1401 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001402 }
1403
Nick Coghland6009512014-11-20 21:39:37 +10001404 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001405 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001406 if (modules == NULL) {
1407 return _Py_INIT_ERR("can't make modules dictionary");
1408 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001409 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001410
Eric Snowd393c1b2017-09-14 12:18:12 -06001411 sysmod = _PyImport_FindBuiltin("sys", modules);
1412 if (sysmod != NULL) {
1413 interp->sysdict = PyModule_GetDict(sysmod);
1414 if (interp->sysdict == NULL)
1415 goto handle_error;
1416 Py_INCREF(interp->sysdict);
1417 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001418 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001419 }
1420
1421 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001422 if (bimod != NULL) {
1423 interp->builtins = PyModule_GetDict(bimod);
1424 if (interp->builtins == NULL)
1425 goto handle_error;
1426 Py_INCREF(interp->builtins);
1427 }
1428
1429 /* initialize builtin exceptions */
1430 _PyExc_Init(bimod);
1431
Nick Coghland6009512014-11-20 21:39:37 +10001432 if (bimod != NULL && sysmod != NULL) {
1433 PyObject *pstderr;
1434
Nick Coghland6009512014-11-20 21:39:37 +10001435 /* Set up a preliminary stderr printer until we have enough
1436 infrastructure for the io module in place. */
1437 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001438 if (pstderr == NULL) {
1439 return _Py_INIT_ERR("can't set preliminary stderr");
1440 }
Nick Coghland6009512014-11-20 21:39:37 +10001441 _PySys_SetObjectId(&PyId_stderr, pstderr);
1442 PySys_SetObject("__stderr__", pstderr);
1443 Py_DECREF(pstderr);
1444
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001445 err = _PyImportHooks_Init();
1446 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001447 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001448 }
Nick Coghland6009512014-11-20 21:39:37 +10001449
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001450 err = initimport(interp, sysmod);
1451 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001452 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001453 }
Nick Coghland6009512014-11-20 21:39:37 +10001454
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001455 err = initexternalimport(interp);
1456 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001457 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001458 }
Nick Coghland6009512014-11-20 21:39:37 +10001459
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001460 err = initfsencoding(interp);
1461 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001462 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001463 }
1464
Victor Stinner91106cd2017-12-13 12:29:09 +01001465 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001466 if (_Py_INIT_FAILED(err)) {
1467 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001468 }
1469
1470 err = add_main_module(interp);
1471 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001472 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001473 }
1474
1475 if (!Py_NoSiteFlag) {
1476 err = initsite();
1477 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001478 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001479 }
1480 }
Nick Coghland6009512014-11-20 21:39:37 +10001481 }
1482
Victor Stinnera7368ac2017-11-15 18:11:45 -08001483 if (PyErr_Occurred()) {
1484 goto handle_error;
1485 }
Nick Coghland6009512014-11-20 21:39:37 +10001486
Victor Stinnera7368ac2017-11-15 18:11:45 -08001487 *tstate_p = tstate;
1488 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001489
Nick Coghland6009512014-11-20 21:39:37 +10001490handle_error:
1491 /* Oops, it didn't work. Undo it all. */
1492
1493 PyErr_PrintEx(0);
1494 PyThreadState_Clear(tstate);
1495 PyThreadState_Swap(save_tstate);
1496 PyThreadState_Delete(tstate);
1497 PyInterpreterState_Delete(interp);
1498
Victor Stinnera7368ac2017-11-15 18:11:45 -08001499 *tstate_p = NULL;
1500 return _Py_INIT_OK();
1501}
1502
1503PyThreadState *
1504Py_NewInterpreter(void)
1505{
1506 PyThreadState *tstate;
1507 _PyInitError err = new_interpreter(&tstate);
1508 if (_Py_INIT_FAILED(err)) {
1509 _Py_FatalInitError(err);
1510 }
1511 return tstate;
1512
Nick Coghland6009512014-11-20 21:39:37 +10001513}
1514
1515/* Delete an interpreter and its last thread. This requires that the
1516 given thread state is current, that the thread has no remaining
1517 frames, and that it is its interpreter's only remaining thread.
1518 It is a fatal error to violate these constraints.
1519
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001520 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001521 everything, regardless.)
1522
1523 Locking: as above.
1524
1525*/
1526
1527void
1528Py_EndInterpreter(PyThreadState *tstate)
1529{
1530 PyInterpreterState *interp = tstate->interp;
1531
1532 if (tstate != PyThreadState_GET())
1533 Py_FatalError("Py_EndInterpreter: thread is not current");
1534 if (tstate->frame != NULL)
1535 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1536
1537 wait_for_thread_shutdown();
1538
Marcel Plch776407f2017-12-20 11:17:58 +01001539 call_py_exitfuncs(interp);
1540
Nick Coghland6009512014-11-20 21:39:37 +10001541 if (tstate != interp->tstate_head || tstate->next != NULL)
1542 Py_FatalError("Py_EndInterpreter: not the last thread");
1543
1544 PyImport_Cleanup();
1545 PyInterpreterState_Clear(interp);
1546 PyThreadState_Swap(NULL);
1547 PyInterpreterState_Delete(interp);
1548}
1549
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001550/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001551
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001552static _PyInitError
1553add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001554{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001555 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001556 m = PyImport_AddModule("__main__");
1557 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001558 return _Py_INIT_ERR("can't create __main__ module");
1559
Nick Coghland6009512014-11-20 21:39:37 +10001560 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001561 ann_dict = PyDict_New();
1562 if ((ann_dict == NULL) ||
1563 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001564 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001565 }
1566 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001567
Nick Coghland6009512014-11-20 21:39:37 +10001568 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1569 PyObject *bimod = PyImport_ImportModule("builtins");
1570 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001571 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001572 }
1573 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001574 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001575 }
1576 Py_DECREF(bimod);
1577 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001578
Nick Coghland6009512014-11-20 21:39:37 +10001579 /* Main is a little special - imp.is_builtin("__main__") will return
1580 * False, but BuiltinImporter is still the most appropriate initial
1581 * setting for its __loader__ attribute. A more suitable value will
1582 * be set if __main__ gets further initialized later in the startup
1583 * process.
1584 */
1585 loader = PyDict_GetItemString(d, "__loader__");
1586 if (loader == NULL || loader == Py_None) {
1587 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1588 "BuiltinImporter");
1589 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001590 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001591 }
1592 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001593 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001594 }
1595 Py_DECREF(loader);
1596 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001597 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001598}
1599
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001600static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001601initfsencoding(PyInterpreterState *interp)
1602{
1603 PyObject *codec;
1604
Steve Dowercc16be82016-09-08 10:35:16 -07001605#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001606 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001607 Py_FileSystemDefaultEncoding = "mbcs";
1608 Py_FileSystemDefaultEncodeErrors = "replace";
1609 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001610 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001611 Py_FileSystemDefaultEncoding = "utf-8";
1612 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1613 }
1614#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001615 if (Py_FileSystemDefaultEncoding == NULL &&
1616 interp->core_config.utf8_mode)
1617 {
1618 Py_FileSystemDefaultEncoding = "utf-8";
1619 Py_HasFileSystemDefaultEncoding = 1;
1620 }
Victor Stinner21220bb2018-10-30 12:59:20 +01001621 else if (_Py_GetForceASCII()) {
1622 Py_FileSystemDefaultEncoding = "ascii";
1623 Py_HasFileSystemDefaultEncoding = 1;
1624 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001625 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001626 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001627 if (Py_FileSystemDefaultEncoding == NULL) {
1628 return _Py_INIT_ERR("Unable to get the locale encoding");
1629 }
Nick Coghland6009512014-11-20 21:39:37 +10001630
1631 Py_HasFileSystemDefaultEncoding = 0;
1632 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001633 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001634 }
Steve Dowercc16be82016-09-08 10:35:16 -07001635#endif
Nick Coghland6009512014-11-20 21:39:37 +10001636
1637 /* the encoding is mbcs, utf-8 or ascii */
1638 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1639 if (!codec) {
1640 /* Such error can only occurs in critical situations: no more
1641 * memory, import a module of the standard library failed,
1642 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001643 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001644 }
1645 Py_DECREF(codec);
1646 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001647 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001648}
1649
1650/* Import the site module (not into __main__ though) */
1651
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001652static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001653initsite(void)
1654{
1655 PyObject *m;
1656 m = PyImport_ImportModule("site");
1657 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001658 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001659 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001660 Py_DECREF(m);
1661 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001662}
1663
Victor Stinner874dbe82015-09-04 17:29:57 +02001664/* Check if a file descriptor is valid or not.
1665 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1666static int
1667is_valid_fd(int fd)
1668{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001669#ifdef __APPLE__
1670 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1671 and the other side of the pipe is closed, dup(1) succeed, whereas
1672 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1673 such error. */
1674 struct stat st;
1675 return (fstat(fd, &st) == 0);
1676#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001677 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001678 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001679 return 0;
1680 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001681 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1682 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1683 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001684 fd2 = dup(fd);
1685 if (fd2 >= 0)
1686 close(fd2);
1687 _Py_END_SUPPRESS_IPH
1688 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001689#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001690}
1691
1692/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001693static PyObject*
1694create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001695 int fd, int write_mode, const char* name,
1696 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001697{
1698 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1699 const char* mode;
1700 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001701 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001702 int buffering, isatty;
1703 _Py_IDENTIFIER(open);
1704 _Py_IDENTIFIER(isatty);
1705 _Py_IDENTIFIER(TextIOWrapper);
1706 _Py_IDENTIFIER(mode);
1707
Victor Stinner874dbe82015-09-04 17:29:57 +02001708 if (!is_valid_fd(fd))
1709 Py_RETURN_NONE;
1710
Nick Coghland6009512014-11-20 21:39:37 +10001711 /* stdin is always opened in buffered mode, first because it shouldn't
1712 make a difference in common use cases, second because TextIOWrapper
1713 depends on the presence of a read1() method which only exists on
1714 buffered streams.
1715 */
1716 if (Py_UnbufferedStdioFlag && write_mode)
1717 buffering = 0;
1718 else
1719 buffering = -1;
1720 if (write_mode)
1721 mode = "wb";
1722 else
1723 mode = "rb";
1724 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1725 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001726 Py_None, Py_None, /* encoding, errors */
1727 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001728 if (buf == NULL)
1729 goto error;
1730
1731 if (buffering) {
1732 _Py_IDENTIFIER(raw);
1733 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1734 if (raw == NULL)
1735 goto error;
1736 }
1737 else {
1738 raw = buf;
1739 Py_INCREF(raw);
1740 }
1741
Steve Dower39294992016-08-30 21:22:36 -07001742#ifdef MS_WINDOWS
1743 /* Windows console IO is always UTF-8 encoded */
1744 if (PyWindowsConsoleIO_Check(raw))
1745 encoding = "utf-8";
1746#endif
1747
Nick Coghland6009512014-11-20 21:39:37 +10001748 text = PyUnicode_FromString(name);
1749 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1750 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001751 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001752 if (res == NULL)
1753 goto error;
1754 isatty = PyObject_IsTrue(res);
1755 Py_DECREF(res);
1756 if (isatty == -1)
1757 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001758 if (Py_UnbufferedStdioFlag)
1759 write_through = Py_True;
1760 else
1761 write_through = Py_False;
1762 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001763 line_buffering = Py_True;
1764 else
1765 line_buffering = Py_False;
1766
1767 Py_CLEAR(raw);
1768 Py_CLEAR(text);
1769
1770#ifdef MS_WINDOWS
1771 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1772 newlines to "\n".
1773 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1774 newline = NULL;
1775#else
1776 /* sys.stdin: split lines at "\n".
1777 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1778 newline = "\n";
1779#endif
1780
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001781 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001782 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001783 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001784 Py_CLEAR(buf);
1785 if (stream == NULL)
1786 goto error;
1787
1788 if (write_mode)
1789 mode = "w";
1790 else
1791 mode = "r";
1792 text = PyUnicode_FromString(mode);
1793 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1794 goto error;
1795 Py_CLEAR(text);
1796 return stream;
1797
1798error:
1799 Py_XDECREF(buf);
1800 Py_XDECREF(stream);
1801 Py_XDECREF(text);
1802 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001803
Victor Stinner874dbe82015-09-04 17:29:57 +02001804 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1805 /* Issue #24891: the file descriptor was closed after the first
1806 is_valid_fd() check was called. Ignore the OSError and set the
1807 stream to None. */
1808 PyErr_Clear();
1809 Py_RETURN_NONE;
1810 }
1811 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001812}
1813
1814/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001815static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001816init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001817{
1818 PyObject *iomod = NULL, *wrapper;
1819 PyObject *bimod = NULL;
1820 PyObject *m;
1821 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001822 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001823 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001824 char *pythonioencoding = NULL;
1825 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001826 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001827
1828 /* Hack to avoid a nasty recursion issue when Python is invoked
1829 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1830 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1831 goto error;
1832 }
1833 Py_DECREF(m);
1834
1835 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1836 goto error;
1837 }
1838 Py_DECREF(m);
1839
1840 if (!(bimod = PyImport_ImportModule("builtins"))) {
1841 goto error;
1842 }
1843
1844 if (!(iomod = PyImport_ImportModule("io"))) {
1845 goto error;
1846 }
1847 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1848 goto error;
1849 }
1850
1851 /* Set builtins.open */
1852 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1853 Py_DECREF(wrapper);
1854 goto error;
1855 }
1856 Py_DECREF(wrapper);
1857
1858 encoding = _Py_StandardStreamEncoding;
1859 errors = _Py_StandardStreamErrors;
1860 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001861 char *opt = Py_GETENV("PYTHONIOENCODING");
1862 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001863 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001864 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001865 if (pythonioencoding == NULL) {
1866 PyErr_NoMemory();
1867 goto error;
1868 }
1869 err = strchr(pythonioencoding, ':');
1870 if (err) {
1871 *err = '\0';
1872 err++;
Victor Stinner0b9ea4b2018-08-29 11:01:33 +02001873 if (!err[0]) {
1874 err = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001875 }
1876 }
Victor Stinner0b9ea4b2018-08-29 11:01:33 +02001877
1878 /* Does PYTHONIOENCODING contain an encoding? */
1879 if (pythonioencoding[0]) {
1880 if (!encoding) {
1881 encoding = pythonioencoding;
1882 }
1883
1884 /* If the encoding is set but not the error handler,
1885 use "strict" error handler by default.
1886 PYTHONIOENCODING=latin1 behaves as
1887 PYTHONIOENCODING=latin1:strict. */
1888 if (!err) {
1889 err = "strict";
1890 }
1891 }
1892
1893 if (!errors && err != NULL) {
1894 errors = err;
Nick Coghland6009512014-11-20 21:39:37 +10001895 }
1896 }
Victor Stinner0b9ea4b2018-08-29 11:01:33 +02001897
1898 if (interp->core_config.utf8_mode) {
1899 if (!encoding) {
1900 encoding = "utf-8";
1901 }
1902 if (!errors) {
1903 errors = "surrogateescape";
1904 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001905 }
1906
Victor Stinner0b9ea4b2018-08-29 11:01:33 +02001907
1908 if (!errors) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001909 /* Choose the default error handler based on the current locale */
1910 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001911 }
Nick Coghland6009512014-11-20 21:39:37 +10001912 }
1913
1914 /* Set sys.stdin */
1915 fd = fileno(stdin);
1916 /* Under some conditions stdin, stdout and stderr may not be connected
1917 * and fileno() may point to an invalid file descriptor. For example
1918 * GUI apps don't have valid standard streams by default.
1919 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001920 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1921 if (std == NULL)
1922 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001923 PySys_SetObject("__stdin__", std);
1924 _PySys_SetObjectId(&PyId_stdin, std);
1925 Py_DECREF(std);
1926
1927 /* Set sys.stdout */
1928 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001929 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1930 if (std == NULL)
1931 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001932 PySys_SetObject("__stdout__", std);
1933 _PySys_SetObjectId(&PyId_stdout, std);
1934 Py_DECREF(std);
1935
1936#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1937 /* Set sys.stderr, replaces the preliminary stderr */
1938 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001939 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1940 if (std == NULL)
1941 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001942
1943 /* Same as hack above, pre-import stderr's codec to avoid recursion
1944 when import.c tries to write to stderr in verbose mode. */
1945 encoding_attr = PyObject_GetAttrString(std, "encoding");
1946 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001947 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001948 if (std_encoding != NULL) {
1949 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1950 Py_XDECREF(codec_info);
1951 }
1952 Py_DECREF(encoding_attr);
1953 }
1954 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1955
1956 if (PySys_SetObject("__stderr__", std) < 0) {
1957 Py_DECREF(std);
1958 goto error;
1959 }
1960 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1961 Py_DECREF(std);
1962 goto error;
1963 }
1964 Py_DECREF(std);
1965#endif
1966
Victor Stinnera7368ac2017-11-15 18:11:45 -08001967 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001968
Victor Stinnera7368ac2017-11-15 18:11:45 -08001969error:
1970 res = _Py_INIT_ERR("can't initialize sys standard streams");
1971
Victor Stinner31e99082017-12-20 23:41:38 +01001972 /* Use the same allocator than Py_SetStandardStreamEncoding() */
1973 PyMemAllocatorEx old_alloc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001974done:
Victor Stinner31e99082017-12-20 23:41:38 +01001975 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1976
Nick Coghland6009512014-11-20 21:39:37 +10001977 /* We won't need them anymore. */
1978 if (_Py_StandardStreamEncoding) {
1979 PyMem_RawFree(_Py_StandardStreamEncoding);
1980 _Py_StandardStreamEncoding = NULL;
1981 }
1982 if (_Py_StandardStreamErrors) {
1983 PyMem_RawFree(_Py_StandardStreamErrors);
1984 _Py_StandardStreamErrors = NULL;
1985 }
Victor Stinner31e99082017-12-20 23:41:38 +01001986
1987 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1988
Nick Coghland6009512014-11-20 21:39:37 +10001989 PyMem_Free(pythonioencoding);
1990 Py_XDECREF(bimod);
1991 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001992 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001993}
1994
1995
Victor Stinner10dc4842015-03-24 12:01:30 +01001996static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001997_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001998{
Victor Stinner10dc4842015-03-24 12:01:30 +01001999 fputc('\n', stderr);
2000 fflush(stderr);
2001
2002 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01002003 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01002004}
Victor Stinner791da1c2016-03-14 16:53:12 +01002005
2006/* Print the current exception (if an exception is set) with its traceback,
2007 or display the current Python stack.
2008
2009 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
2010 called on catastrophic cases.
2011
2012 Return 1 if the traceback was displayed, 0 otherwise. */
2013
2014static int
2015_Py_FatalError_PrintExc(int fd)
2016{
2017 PyObject *ferr, *res;
2018 PyObject *exception, *v, *tb;
2019 int has_tb;
2020
Victor Stinner791da1c2016-03-14 16:53:12 +01002021 PyErr_Fetch(&exception, &v, &tb);
2022 if (exception == NULL) {
2023 /* No current exception */
2024 return 0;
2025 }
2026
2027 ferr = _PySys_GetObjectId(&PyId_stderr);
2028 if (ferr == NULL || ferr == Py_None) {
2029 /* sys.stderr is not set yet or set to None,
2030 no need to try to display the exception */
2031 return 0;
2032 }
2033
2034 PyErr_NormalizeException(&exception, &v, &tb);
2035 if (tb == NULL) {
2036 tb = Py_None;
2037 Py_INCREF(tb);
2038 }
2039 PyException_SetTraceback(v, tb);
2040 if (exception == NULL) {
2041 /* PyErr_NormalizeException() failed */
2042 return 0;
2043 }
2044
2045 has_tb = (tb != Py_None);
2046 PyErr_Display(exception, v, tb);
2047 Py_XDECREF(exception);
2048 Py_XDECREF(v);
2049 Py_XDECREF(tb);
2050
2051 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002052 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002053 if (res == NULL)
2054 PyErr_Clear();
2055 else
2056 Py_DECREF(res);
2057
2058 return has_tb;
2059}
2060
Nick Coghland6009512014-11-20 21:39:37 +10002061/* Print fatal error message and abort */
2062
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002063#ifdef MS_WINDOWS
2064static void
2065fatal_output_debug(const char *msg)
2066{
2067 /* buffer of 256 bytes allocated on the stack */
2068 WCHAR buffer[256 / sizeof(WCHAR)];
2069 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2070 size_t msglen;
2071
2072 OutputDebugStringW(L"Fatal Python error: ");
2073
2074 msglen = strlen(msg);
2075 while (msglen) {
2076 size_t i;
2077
2078 if (buflen > msglen) {
2079 buflen = msglen;
2080 }
2081
2082 /* Convert the message to wchar_t. This uses a simple one-to-one
2083 conversion, assuming that the this error message actually uses
2084 ASCII only. If this ceases to be true, we will have to convert. */
2085 for (i=0; i < buflen; ++i) {
2086 buffer[i] = msg[i];
2087 }
2088 buffer[i] = L'\0';
2089 OutputDebugStringW(buffer);
2090
2091 msg += buflen;
2092 msglen -= buflen;
2093 }
2094 OutputDebugStringW(L"\n");
2095}
2096#endif
2097
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002098static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002099fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002100{
2101 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002102 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002103
2104 if (reentrant) {
2105 /* Py_FatalError() caused a second fatal error.
2106 Example: flush_std_files() raises a recursion error. */
2107 goto exit;
2108 }
2109 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002110
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002111 fprintf(stderr, "Fatal Python error: ");
2112 if (prefix) {
2113 fputs(prefix, stderr);
2114 fputs(": ", stderr);
2115 }
2116 if (msg) {
2117 fputs(msg, stderr);
2118 }
2119 else {
2120 fprintf(stderr, "<message not set>");
2121 }
2122 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002123 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002124
Miss Islington (bot)192c5472018-10-31 16:45:42 -07002125 /* Check if the current thread has a Python thread state
2126 and holds the GIL */
2127 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2128 if (tss_tstate != NULL) {
2129 PyThreadState *tstate = PyThreadState_GET();
2130 if (tss_tstate != tstate) {
2131 /* The Python thread does not hold the GIL */
2132 tss_tstate = NULL;
2133 }
2134 }
2135 else {
2136 /* Py_FatalError() has been called from a C thread
2137 which has no Python thread state. */
2138 }
2139 int has_tstate_and_gil = (tss_tstate != NULL);
2140
2141 if (has_tstate_and_gil) {
2142 /* If an exception is set, print the exception with its traceback */
2143 if (!_Py_FatalError_PrintExc(fd)) {
2144 /* No exception is set, or an exception is set without traceback */
2145 _Py_FatalError_DumpTracebacks(fd);
2146 }
2147 }
2148 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002149 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002150 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002151
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002152 /* The main purpose of faulthandler is to display the traceback.
2153 This function already did its best to display a traceback.
2154 Disable faulthandler to prevent writing a second traceback
2155 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002156 _PyFaulthandler_Fini();
2157
Victor Stinner791da1c2016-03-14 16:53:12 +01002158 /* Check if the current Python thread hold the GIL */
Miss Islington (bot)192c5472018-10-31 16:45:42 -07002159 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002160 /* Flush sys.stdout and sys.stderr */
2161 flush_std_files();
2162 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002163
Nick Coghland6009512014-11-20 21:39:37 +10002164#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002165 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002166#endif /* MS_WINDOWS */
2167
2168exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002169 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002170#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002171 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002172#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002173 abort();
2174 }
2175 else {
2176 exit(status);
2177 }
2178}
2179
Victor Stinner19760862017-12-20 01:41:59 +01002180void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002181Py_FatalError(const char *msg)
2182{
2183 fatal_error(NULL, msg, -1);
2184}
2185
Victor Stinner19760862017-12-20 01:41:59 +01002186void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002187_Py_FatalInitError(_PyInitError err)
2188{
2189 /* On "user" error: exit with status 1.
2190 For all other errors, call abort(). */
2191 int status = err.user_err ? 1 : -1;
2192 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002193}
2194
2195/* Clean up and exit */
2196
Victor Stinnerd7292b52016-06-17 12:29:00 +02002197# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002198
Nick Coghland6009512014-11-20 21:39:37 +10002199/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002200void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002201{
Marcel Plch776407f2017-12-20 11:17:58 +01002202 PyThreadState *ts;
2203 PyInterpreterState *is;
Victor Stinnerca719ac2017-12-20 18:00:19 +01002204
Marcel Plch776407f2017-12-20 11:17:58 +01002205 ts = PyThreadState_GET();
2206 is = ts->interp;
2207
Antoine Pitroufc5db952017-12-13 02:29:07 +01002208 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002209 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2210
2211 is->pyexitfunc = func;
2212 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002213}
2214
2215static void
Marcel Plch776407f2017-12-20 11:17:58 +01002216call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002217{
Marcel Plch776407f2017-12-20 11:17:58 +01002218 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002219 return;
2220
Marcel Plch776407f2017-12-20 11:17:58 +01002221 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002222 PyErr_Clear();
2223}
2224
2225/* Wait until threading._shutdown completes, provided
2226 the threading module was imported in the first place.
2227 The shutdown routine will wait until all non-daemon
2228 "threading" threads have completed. */
2229static void
2230wait_for_thread_shutdown(void)
2231{
Nick Coghland6009512014-11-20 21:39:37 +10002232 _Py_IDENTIFIER(_shutdown);
2233 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002234 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002235 if (threading == NULL) {
2236 /* threading not imported */
2237 PyErr_Clear();
2238 return;
2239 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002240 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002241 if (result == NULL) {
2242 PyErr_WriteUnraisable(threading);
2243 }
2244 else {
2245 Py_DECREF(result);
2246 }
2247 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002248}
2249
2250#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002251int Py_AtExit(void (*func)(void))
2252{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002253 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002254 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002255 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002256 return 0;
2257}
2258
2259static void
2260call_ll_exitfuncs(void)
2261{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002262 while (_PyRuntime.nexitfuncs > 0)
2263 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002264
2265 fflush(stdout);
2266 fflush(stderr);
2267}
2268
2269void
2270Py_Exit(int sts)
2271{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002272 if (Py_FinalizeEx() < 0) {
2273 sts = 120;
2274 }
Nick Coghland6009512014-11-20 21:39:37 +10002275
2276 exit(sts);
2277}
2278
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002279static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002280initsigs(void)
2281{
2282#ifdef SIGPIPE
2283 PyOS_setsig(SIGPIPE, SIG_IGN);
2284#endif
2285#ifdef SIGXFZ
2286 PyOS_setsig(SIGXFZ, SIG_IGN);
2287#endif
2288#ifdef SIGXFSZ
2289 PyOS_setsig(SIGXFSZ, SIG_IGN);
2290#endif
2291 PyOS_InitInterrupts(); /* May imply initsignal() */
2292 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002293 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002294 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002295 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002296}
2297
2298
2299/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2300 *
2301 * All of the code in this function must only use async-signal-safe functions,
2302 * listed at `man 7 signal` or
2303 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2304 */
2305void
2306_Py_RestoreSignals(void)
2307{
2308#ifdef SIGPIPE
2309 PyOS_setsig(SIGPIPE, SIG_DFL);
2310#endif
2311#ifdef SIGXFZ
2312 PyOS_setsig(SIGXFZ, SIG_DFL);
2313#endif
2314#ifdef SIGXFSZ
2315 PyOS_setsig(SIGXFSZ, SIG_DFL);
2316#endif
2317}
2318
2319
2320/*
2321 * The file descriptor fd is considered ``interactive'' if either
2322 * a) isatty(fd) is TRUE, or
2323 * b) the -i flag was given, and the filename associated with
2324 * the descriptor is NULL or "<stdin>" or "???".
2325 */
2326int
2327Py_FdIsInteractive(FILE *fp, const char *filename)
2328{
2329 if (isatty((int)fileno(fp)))
2330 return 1;
2331 if (!Py_InteractiveFlag)
2332 return 0;
2333 return (filename == NULL) ||
2334 (strcmp(filename, "<stdin>") == 0) ||
2335 (strcmp(filename, "???") == 0);
2336}
2337
2338
Nick Coghland6009512014-11-20 21:39:37 +10002339/* Wrappers around sigaction() or signal(). */
2340
2341PyOS_sighandler_t
2342PyOS_getsig(int sig)
2343{
2344#ifdef HAVE_SIGACTION
2345 struct sigaction context;
2346 if (sigaction(sig, NULL, &context) == -1)
2347 return SIG_ERR;
2348 return context.sa_handler;
2349#else
2350 PyOS_sighandler_t handler;
2351/* Special signal handling for the secure CRT in Visual Studio 2005 */
2352#if defined(_MSC_VER) && _MSC_VER >= 1400
2353 switch (sig) {
2354 /* Only these signals are valid */
2355 case SIGINT:
2356 case SIGILL:
2357 case SIGFPE:
2358 case SIGSEGV:
2359 case SIGTERM:
2360 case SIGBREAK:
2361 case SIGABRT:
2362 break;
2363 /* Don't call signal() with other values or it will assert */
2364 default:
2365 return SIG_ERR;
2366 }
2367#endif /* _MSC_VER && _MSC_VER >= 1400 */
2368 handler = signal(sig, SIG_IGN);
2369 if (handler != SIG_ERR)
2370 signal(sig, handler);
2371 return handler;
2372#endif
2373}
2374
2375/*
2376 * All of the code in this function must only use async-signal-safe functions,
2377 * listed at `man 7 signal` or
2378 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2379 */
2380PyOS_sighandler_t
2381PyOS_setsig(int sig, PyOS_sighandler_t handler)
2382{
2383#ifdef HAVE_SIGACTION
2384 /* Some code in Modules/signalmodule.c depends on sigaction() being
2385 * used here if HAVE_SIGACTION is defined. Fix that if this code
2386 * changes to invalidate that assumption.
2387 */
2388 struct sigaction context, ocontext;
2389 context.sa_handler = handler;
2390 sigemptyset(&context.sa_mask);
2391 context.sa_flags = 0;
2392 if (sigaction(sig, &context, &ocontext) == -1)
2393 return SIG_ERR;
2394 return ocontext.sa_handler;
2395#else
2396 PyOS_sighandler_t oldhandler;
2397 oldhandler = signal(sig, handler);
2398#ifdef HAVE_SIGINTERRUPT
2399 siginterrupt(sig, 1);
2400#endif
2401 return oldhandler;
2402#endif
2403}
2404
2405#ifdef __cplusplus
2406}
2407#endif