blob: 8817be1c4113f51ac7bb84b70f5bbee277b312f6 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06007#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +10008#include "grammar.h"
9#include "node.h"
10#include "token.h"
11#include "parsetok.h"
12#include "errcode.h"
13#include "code.h"
14#include "symtable.h"
15#include "ast.h"
16#include "marshal.h"
17#include "osdefs.h"
18#include <locale.h>
19
20#ifdef HAVE_SIGNAL_H
21#include <signal.h>
22#endif
23
24#ifdef MS_WINDOWS
25#include "malloc.h" /* for alloca */
26#endif
27
28#ifdef HAVE_LANGINFO_H
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTE
34#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
36extern PyTypeObject PyWindowsConsoleIO_Type;
37#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
40_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
51extern wchar_t *Py_GetPath(void);
52
53extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
56static void initmain(PyInterpreterState *interp);
57static int initfsencoding(PyInterpreterState *interp);
58static void initsite(void);
59static int initstdio(void);
60static void initsigs(void);
61static void call_py_exitfuncs(void);
62static 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);
69extern int _PyFaulthandler_Init(void);
70extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
72extern int _PyTraceMalloc_Init(void);
73extern 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
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079_PyRuntimeState _PyRuntime = {0, 0};
80
81void
82_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;
91 if (initialized)
92 return;
93 initialized = 1;
94 _PyRuntimeState_Init(&_PyRuntime);
95}
96
97void
98_PyRuntime_Finalize(void)
99{
100 _PyRuntimeState_Fini(&_PyRuntime);
101}
102
103int
104_Py_IsFinalizing(void)
105{
106 return _PyRuntime.finalizing != NULL;
107}
108
Nick Coghland6009512014-11-20 21:39:37 +1000109/* Global configuration variable declarations are in pydebug.h */
110/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
111int Py_DebugFlag; /* Needed by parser.c */
112int Py_VerboseFlag; /* Needed by import.c */
113int Py_QuietFlag; /* Needed by sysmodule.c */
114int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
115int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
116int Py_OptimizeFlag = 0; /* Needed by compile.c */
117int Py_NoSiteFlag; /* Suppress 'import site' */
118int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
119int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
120int Py_FrozenFlag; /* Needed by getpath.c */
121int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800122int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000123int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
124int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
125int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
126int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700127#ifdef MS_WINDOWS
128int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700129int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700130#endif
Nick Coghland6009512014-11-20 21:39:37 +1000131
Nick Coghland6009512014-11-20 21:39:37 +1000132/* Hack to force loading of object files */
133int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
134 PyOS_mystrnicmp; /* Python/pystrcmp.o */
135
136/* PyModule_GetWarningsModule is no longer necessary as of 2.6
137since _warnings is builtin. This API should not be used. */
138PyObject *
139PyModule_GetWarningsModule(void)
140{
141 return PyImport_ImportModule("warnings");
142}
143
Eric Snowc7ec9982017-05-23 23:00:52 -0700144
Eric Snow1abcf672017-05-23 21:46:51 -0700145/* APIs to access the initialization flags
146 *
147 * Can be called prior to Py_Initialize.
148 */
Nick Coghland6009512014-11-20 21:39:37 +1000149
Eric Snow1abcf672017-05-23 21:46:51 -0700150int
151_Py_IsCoreInitialized(void)
152{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600153 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700154}
Nick Coghland6009512014-11-20 21:39:37 +1000155
156int
157Py_IsInitialized(void)
158{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600159 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000160}
161
162/* Helper to allow an embedding application to override the normal
163 * mechanism that attempts to figure out an appropriate IO encoding
164 */
165
166static char *_Py_StandardStreamEncoding = NULL;
167static char *_Py_StandardStreamErrors = NULL;
168
169int
170Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
171{
172 if (Py_IsInitialized()) {
173 /* This is too late to have any effect */
174 return -1;
175 }
176 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
177 * initialised yet.
178 *
179 * However, the raw memory allocators are initialised appropriately
180 * as C static variables, so _PyMem_RawStrdup is OK even though
181 * Py_Initialize hasn't been called yet.
182 */
183 if (encoding) {
184 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
185 if (!_Py_StandardStreamEncoding) {
186 return -2;
187 }
188 }
189 if (errors) {
190 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
191 if (!_Py_StandardStreamErrors) {
192 if (_Py_StandardStreamEncoding) {
193 PyMem_RawFree(_Py_StandardStreamEncoding);
194 }
195 return -3;
196 }
197 }
Steve Dower39294992016-08-30 21:22:36 -0700198#ifdef MS_WINDOWS
199 if (_Py_StandardStreamEncoding) {
200 /* Overriding the stream encoding implies legacy streams */
201 Py_LegacyWindowsStdioFlag = 1;
202 }
203#endif
Nick Coghland6009512014-11-20 21:39:37 +1000204 return 0;
205}
206
Nick Coghlan6ea41862017-06-11 13:16:15 +1000207
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000208/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
209 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000210 initializations fail, a fatal error is issued and the function does
211 not return. On return, the first thread and interpreter state have
212 been created.
213
214 Locking: you must hold the interpreter lock while calling this.
215 (If the lock has not yet been initialized, that's equivalent to
216 having the lock, but you cannot use multiple threads.)
217
218*/
219
Nick Coghland7ac0612017-10-25 12:11:26 +1000220static void
221set_flag(int *flag, const char *envs)
Nick Coghland6009512014-11-20 21:39:37 +1000222{
Nick Coghland7ac0612017-10-25 12:11:26 +1000223 /* Helper to set flag variables from environment variables:
224 * - uses the higher of the two values if they're both set
225 * - otherwise sets the flag to 1
226 */
Nick Coghland6009512014-11-20 21:39:37 +1000227 int env = atoi(envs);
Nick Coghland7ac0612017-10-25 12:11:26 +1000228 if (*flag < env)
229 *flag = env;
230 if (*flag < 1)
231 *flag = 1;
Nick Coghland6009512014-11-20 21:39:37 +1000232}
233
234static char*
235get_codec_name(const char *encoding)
236{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200237 const char *name_utf8;
238 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000239 PyObject *codec, *name = NULL;
240
241 codec = _PyCodec_Lookup(encoding);
242 if (!codec)
243 goto error;
244
245 name = _PyObject_GetAttrId(codec, &PyId_name);
246 Py_CLEAR(codec);
247 if (!name)
248 goto error;
249
Serhiy Storchaka06515832016-11-20 09:13:07 +0200250 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000251 if (name_utf8 == NULL)
252 goto error;
253 name_str = _PyMem_RawStrdup(name_utf8);
254 Py_DECREF(name);
255 if (name_str == NULL) {
256 PyErr_NoMemory();
257 return NULL;
258 }
259 return name_str;
260
261error:
262 Py_XDECREF(codec);
263 Py_XDECREF(name);
264 return NULL;
265}
266
267static char*
268get_locale_encoding(void)
269{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700270#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000271 char* codeset = nl_langinfo(CODESET);
272 if (!codeset || codeset[0] == '\0') {
273 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
274 return NULL;
275 }
276 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200277#elif defined(__ANDROID__)
278 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000279#else
280 PyErr_SetNone(PyExc_NotImplementedError);
281 return NULL;
282#endif
283}
284
285static void
Eric Snow1abcf672017-05-23 21:46:51 -0700286initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000287{
288 PyObject *importlib;
289 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000290 PyObject *value;
291
292 /* Import _importlib through its frozen version, _frozen_importlib. */
293 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
294 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
295 }
296 else if (Py_VerboseFlag) {
297 PySys_FormatStderr("import _frozen_importlib # frozen\n");
298 }
299 importlib = PyImport_AddModule("_frozen_importlib");
300 if (importlib == NULL) {
301 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
302 "sys.modules");
303 }
304 interp->importlib = importlib;
305 Py_INCREF(interp->importlib);
306
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300307 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
308 if (interp->import_func == NULL)
309 Py_FatalError("Py_Initialize: __import__ not found");
310 Py_INCREF(interp->import_func);
311
Victor Stinnercd6e6942015-09-18 09:11:57 +0200312 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000313 impmod = PyInit_imp();
314 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200315 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000316 }
317 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200318 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000319 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600320 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Nick Coghland6009512014-11-20 21:39:37 +1000321 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
322 }
323
Victor Stinnercd6e6942015-09-18 09:11:57 +0200324 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000325 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200326 if (value != NULL) {
327 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700328 value = PyObject_CallMethod(importlib,
329 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200330 }
Nick Coghland6009512014-11-20 21:39:37 +1000331 if (value == NULL) {
332 PyErr_Print();
333 Py_FatalError("Py_Initialize: importlib install failed");
334 }
335 Py_DECREF(value);
336 Py_DECREF(impmod);
337
338 _PyImportZip_Init();
339}
340
Eric Snow1abcf672017-05-23 21:46:51 -0700341static void
342initexternalimport(PyInterpreterState *interp)
343{
344 PyObject *value;
345 value = PyObject_CallMethod(interp->importlib,
346 "_install_external_importers", "");
347 if (value == NULL) {
348 PyErr_Print();
349 Py_FatalError("Py_EndInitialization: external importer setup failed");
350 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200351 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700352}
Nick Coghland6009512014-11-20 21:39:37 +1000353
Nick Coghlan6ea41862017-06-11 13:16:15 +1000354/* Helper functions to better handle the legacy C locale
355 *
356 * The legacy C locale assumes ASCII as the default text encoding, which
357 * causes problems not only for the CPython runtime, but also other
358 * components like GNU readline.
359 *
360 * Accordingly, when the CLI detects it, it attempts to coerce it to a
361 * more capable UTF-8 based alternative as follows:
362 *
363 * if (_Py_LegacyLocaleDetected()) {
364 * _Py_CoerceLegacyLocale();
365 * }
366 *
367 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
368 *
369 * Locale coercion also impacts the default error handler for the standard
370 * streams: while the usual default is "strict", the default for the legacy
371 * C locale and for any of the coercion target locales is "surrogateescape".
372 */
373
374int
375_Py_LegacyLocaleDetected(void)
376{
377#ifndef MS_WINDOWS
378 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000379 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
380 * the POSIX locale as a simple alias for the C locale, so
381 * we may also want to check for that explicitly.
382 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000383 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
384 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
385#else
386 /* Windows uses code pages instead of locales, so no locale is legacy */
387 return 0;
388#endif
389}
390
Nick Coghlaneb817952017-06-18 12:29:42 +1000391static const char *_C_LOCALE_WARNING =
392 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
393 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
394 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
395 "locales is recommended.\n";
396
397static int
398_legacy_locale_warnings_enabled(void)
399{
400 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
401 return (coerce_c_locale != NULL &&
402 strncmp(coerce_c_locale, "warn", 5) == 0);
403}
404
405static void
406_emit_stderr_warning_for_legacy_locale(void)
407{
408 if (_legacy_locale_warnings_enabled()) {
409 if (_Py_LegacyLocaleDetected()) {
410 fprintf(stderr, "%s", _C_LOCALE_WARNING);
411 }
412 }
413}
414
Nick Coghlan6ea41862017-06-11 13:16:15 +1000415typedef struct _CandidateLocale {
416 const char *locale_name; /* The locale to try as a coercion target */
417} _LocaleCoercionTarget;
418
419static _LocaleCoercionTarget _TARGET_LOCALES[] = {
420 {"C.UTF-8"},
421 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000422 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000423 {NULL}
424};
425
426static char *
427get_default_standard_stream_error_handler(void)
428{
429 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
430 if (ctype_loc != NULL) {
431 /* "surrogateescape" is the default in the legacy C locale */
432 if (strcmp(ctype_loc, "C") == 0) {
433 return "surrogateescape";
434 }
435
436#ifdef PY_COERCE_C_LOCALE
437 /* "surrogateescape" is the default in locale coercion target locales */
438 const _LocaleCoercionTarget *target = NULL;
439 for (target = _TARGET_LOCALES; target->locale_name; target++) {
440 if (strcmp(ctype_loc, target->locale_name) == 0) {
441 return "surrogateescape";
442 }
443 }
444#endif
445 }
446
447 /* Otherwise return NULL to request the typical default error handler */
448 return NULL;
449}
450
451#ifdef PY_COERCE_C_LOCALE
452static const char *_C_LOCALE_COERCION_WARNING =
453 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
454 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
455
456static void
457_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
458{
459 const char *newloc = target->locale_name;
460
461 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100462 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000463
464 /* Set the relevant locale environment variable */
465 if (setenv("LC_CTYPE", newloc, 1)) {
466 fprintf(stderr,
467 "Error setting LC_CTYPE, skipping C locale coercion\n");
468 return;
469 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000470 if (_legacy_locale_warnings_enabled()) {
471 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
472 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000473
474 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100475 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000476}
477#endif
478
479void
480_Py_CoerceLegacyLocale(void)
481{
482#ifdef PY_COERCE_C_LOCALE
483 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
484 * the locale settings *before* we try to do anything with the command
485 * line arguments. For cross-platform debugging purposes, we also need
486 * to give end users a way to force even scripts that are otherwise
487 * isolated from their environment to use the legacy ASCII-centric C
488 * locale.
489 *
490 * Ignoring -E and -I is safe from a security perspective, as we only use
491 * the setting to turn *off* the implicit locale coercion, and anyone with
492 * access to the process environment already has the ability to set
493 * `LC_ALL=C` to override the C level locale settings anyway.
494 */
495 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
496 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
497 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
498 const char *locale_override = getenv("LC_ALL");
499 if (locale_override == NULL || *locale_override == '\0') {
500 /* LC_ALL is also not set (or is set to an empty string) */
501 const _LocaleCoercionTarget *target = NULL;
502 for (target = _TARGET_LOCALES; target->locale_name; target++) {
503 const char *new_locale = setlocale(LC_CTYPE,
504 target->locale_name);
505 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100506#if !defined(__APPLE__) && !defined(__ANDROID__) && \
507 defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghlan18974c32017-06-30 00:48:14 +1000508 /* Also ensure that nl_langinfo works in this locale */
509 char *codeset = nl_langinfo(CODESET);
510 if (!codeset || *codeset == '\0') {
511 /* CODESET is not set or empty, so skip coercion */
512 new_locale = NULL;
xdegaye1588be62017-11-12 12:45:59 +0100513 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlan18974c32017-06-30 00:48:14 +1000514 continue;
515 }
516#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000517 /* Successfully configured locale, so make it the default */
518 _coerce_default_locale_settings(target);
519 return;
520 }
521 }
522 }
523 }
524 /* No C locale warning here, as Py_Initialize will emit one later */
525#endif
526}
527
xdegaye1588be62017-11-12 12:45:59 +0100528/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
529 * isolate the idiosyncrasies of different libc implementations. It reads the
530 * appropriate environment variable and uses its value to select the locale for
531 * 'category'. */
532char *
533_Py_SetLocaleFromEnv(int category)
534{
535#ifdef __ANDROID__
536 const char *locale;
537 const char **pvar;
538#ifdef PY_COERCE_C_LOCALE
539 const char *coerce_c_locale;
540#endif
541 const char *utf8_locale = "C.UTF-8";
542 const char *env_var_set[] = {
543 "LC_ALL",
544 "LC_CTYPE",
545 "LANG",
546 NULL,
547 };
548
549 /* Android setlocale(category, "") doesn't check the environment variables
550 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
551 * check the environment variables listed in env_var_set. */
552 for (pvar=env_var_set; *pvar; pvar++) {
553 locale = getenv(*pvar);
554 if (locale != NULL && *locale != '\0') {
555 if (strcmp(locale, utf8_locale) == 0 ||
556 strcmp(locale, "en_US.UTF-8") == 0) {
557 return setlocale(category, utf8_locale);
558 }
559 return setlocale(category, "C");
560 }
561 }
562
563 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
564 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
565 * Quote from POSIX section "8.2 Internationalization Variables":
566 * "4. If the LANG environment variable is not set or is set to the empty
567 * string, the implementation-defined default locale shall be used." */
568
569#ifdef PY_COERCE_C_LOCALE
570 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
571 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
572 /* Some other ported code may check the environment variables (e.g. in
573 * extension modules), so we make sure that they match the locale
574 * configuration */
575 if (setenv("LC_CTYPE", utf8_locale, 1)) {
576 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
577 "environment variable to %s\n", utf8_locale);
578 }
579 }
580#endif
581 return setlocale(category, utf8_locale);
582#else /* __ANDROID__ */
583 return setlocale(category, "");
584#endif /* __ANDROID__ */
585}
586
Nick Coghlan6ea41862017-06-11 13:16:15 +1000587
Eric Snow1abcf672017-05-23 21:46:51 -0700588/* Global initializations. Can be undone by Py_Finalize(). Don't
589 call this twice without an intervening Py_Finalize() call.
590
591 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
592 must have a corresponding call to Py_Finalize.
593
594 Locking: you must hold the interpreter lock while calling these APIs.
595 (If the lock has not yet been initialized, that's equivalent to
596 having the lock, but you cannot use multiple threads.)
597
598*/
599
600/* Begin interpreter initialization
601 *
602 * On return, the first thread and interpreter state have been created,
603 * but the compiler, signal handling, multithreading and
604 * multiple interpreter support, and codec infrastructure are not yet
605 * available.
606 *
607 * The import system will support builtin and frozen modules only.
608 * The only supported io is writing to sys.stderr
609 *
610 * If any operation invoked by this function fails, a fatal error is
611 * issued and the function does not return.
612 *
613 * Any code invoked from this function should *not* assume it has access
614 * to the Python C API (unless the API is explicitly listed as being
615 * safe to call without calling Py_Initialize first)
616 */
617
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200618/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700619 * Py_ReadConfig and Py_EndInitialization
620 */
621
622void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000623{
624 PyInterpreterState *interp;
625 PyThreadState *tstate;
626 PyObject *bimod, *sysmod, *pstderr;
627 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700628 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700629 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000630
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600631 _PyRuntime_Initialize();
632
Eric Snow1abcf672017-05-23 21:46:51 -0700633 if (config != NULL) {
634 core_config = *config;
635 }
636
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600637 if (_PyRuntime.initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700638 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
639 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600640 if (_PyRuntime.core_initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700641 Py_FatalError("Py_InitializeCore: runtime core already initialized");
642 }
643
644 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
645 * threads behave a little more gracefully at interpreter shutdown.
646 * We clobber it here so the new interpreter can start with a clean
647 * slate.
648 *
649 * However, this may still lead to misbehaviour if there are daemon
650 * threads still hanging around from a previous Py_Initialize/Finalize
651 * pair :(
652 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600653 _PyRuntime.finalizing = NULL;
654
655 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
656 fprintf(stderr,
657 "Error in PYTHONMALLOC: unknown allocator \"%s\"!\n",
658 core_config.allocator);
659 exit(1);
660 }
Nick Coghland6009512014-11-20 21:39:37 +1000661
Nick Coghlan6ea41862017-06-11 13:16:15 +1000662#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000663 /* Set up the LC_CTYPE locale, so we can obtain
664 the locale's charset without having to switch
665 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100666 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlaneb817952017-06-18 12:29:42 +1000667 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000668#endif
Nick Coghland6009512014-11-20 21:39:37 +1000669
670 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000671 set_flag(&Py_DebugFlag, p);
Nick Coghland6009512014-11-20 21:39:37 +1000672 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000673 set_flag(&Py_VerboseFlag, p);
Nick Coghland6009512014-11-20 21:39:37 +1000674 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000675 set_flag(&Py_OptimizeFlag, p);
676 if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
677 set_flag(&Py_InspectFlag, p);
Nick Coghland6009512014-11-20 21:39:37 +1000678 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000679 set_flag(&Py_DontWriteBytecodeFlag, p);
680 if ((p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
681 set_flag(&Py_NoUserSiteDirectory, p);
682 if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
683 set_flag(&Py_UnbufferedStdioFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700684 /* The variable is only tested for existence here;
685 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000686 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000687 set_flag(&Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700688#ifdef MS_WINDOWS
689 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000690 set_flag(&Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700691 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000692 set_flag(&Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700693#endif
Nick Coghland6009512014-11-20 21:39:37 +1000694
Eric Snow1abcf672017-05-23 21:46:51 -0700695 _Py_HashRandomization_Init(&core_config);
696 if (!core_config.use_hash_seed || core_config.hash_seed) {
697 /* Random or non-zero hash seed */
698 Py_HashRandomizationFlag = 1;
699 }
Nick Coghland6009512014-11-20 21:39:37 +1000700
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600701 _PyInterpreterState_Enable(&_PyRuntime);
Nick Coghland6009512014-11-20 21:39:37 +1000702 interp = PyInterpreterState_New();
703 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700704 Py_FatalError("Py_InitializeCore: can't make main interpreter");
705 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700706 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000707
708 tstate = PyThreadState_New(interp);
709 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700710 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000711 (void) PyThreadState_Swap(tstate);
712
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000713 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000714 destroying the GIL might fail when it is being referenced from
715 another running thread (see issue #9901).
716 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000717 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000718 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000719 /* Auto-thread-state API */
720 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000721
722 _Py_ReadyTypes();
723
724 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700725 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000726
727 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700728 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000729
730 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700731 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000732
733 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700734 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000735
Eric Snowd393c1b2017-09-14 12:18:12 -0600736 PyObject *modules = PyDict_New();
737 if (modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700738 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600739 interp->modules = modules;
740
741 sysmod = _PySys_BeginInit();
742 if (sysmod == NULL)
743 Py_FatalError("Py_InitializeCore: can't initialize sys");
744 interp->sysdict = PyModule_GetDict(sysmod);
745 if (interp->sysdict == NULL)
746 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
747 Py_INCREF(interp->sysdict);
748 PyDict_SetItemString(interp->sysdict, "modules", modules);
749 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000750
751 /* Init Unicode implementation; relies on the codec registry */
752 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700753 Py_FatalError("Py_InitializeCore: can't initialize unicode");
754
Nick Coghland6009512014-11-20 21:39:37 +1000755 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700756 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000757
758 bimod = _PyBuiltin_Init();
759 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700760 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600761 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000762 interp->builtins = PyModule_GetDict(bimod);
763 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700764 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000765 Py_INCREF(interp->builtins);
766
767 /* initialize builtin exceptions */
768 _PyExc_Init(bimod);
769
Nick Coghland6009512014-11-20 21:39:37 +1000770 /* Set up a preliminary stderr printer until we have enough
771 infrastructure for the io module in place. */
772 pstderr = PyFile_NewStdPrinter(fileno(stderr));
773 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700774 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000775 _PySys_SetObjectId(&PyId_stderr, pstderr);
776 PySys_SetObject("__stderr__", pstderr);
777 Py_DECREF(pstderr);
778
779 _PyImport_Init();
780
781 _PyImportHooks_Init();
782
783 /* Initialize _warnings. */
784 _PyWarnings_Init();
785
Eric Snow1abcf672017-05-23 21:46:51 -0700786 /* This call sets up builtin and frozen import support */
787 if (!interp->core_config._disable_importlib) {
788 initimport(interp, sysmod);
789 }
790
791 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600792 _PyRuntime.core_initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700793}
794
Eric Snowc7ec9982017-05-23 23:00:52 -0700795/* Read configuration settings from standard locations
796 *
797 * This function doesn't make any changes to the interpreter state - it
798 * merely populates any missing configuration settings. This allows an
799 * embedding application to completely override a config option by
800 * setting it before calling this function, or else modify the default
801 * setting before passing the fully populated config to Py_EndInitialization.
802 *
803 * More advanced selective initialization tricks are possible by calling
804 * this function multiple times with various preconfigured settings.
805 */
806
807int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
808{
809 /* Signal handlers are installed by default */
810 if (config->install_signal_handlers < 0) {
811 config->install_signal_handlers = 1;
812 }
813
814 return 0;
815}
816
817/* Update interpreter state based on supplied configuration settings
818 *
819 * After calling this function, most of the restrictions on the interpreter
820 * are lifted. The only remaining incomplete settings are those related
821 * to the main module (sys.argv[0], __main__ metadata)
822 *
823 * Calling this when the interpreter is not initializing, is already
824 * initialized or without a valid current thread state is a fatal error.
825 * Other errors should be reported as normal Python exceptions with a
826 * non-zero return code.
827 */
828int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700829{
830 PyInterpreterState *interp;
831 PyThreadState *tstate;
832
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600833 if (!_PyRuntime.core_initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700834 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
835 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600836 if (_PyRuntime.initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700837 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
838 }
839
Eric Snow1abcf672017-05-23 21:46:51 -0700840 /* Get current thread state and interpreter pointer */
841 tstate = PyThreadState_GET();
842 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700843 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700844 interp = tstate->interp;
845 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700846 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700847
848 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700849 interp->config = *config;
850
Eric Snow1abcf672017-05-23 21:46:51 -0700851 if (interp->core_config._disable_importlib) {
852 /* Special mode for freeze_importlib: run with no import system
853 *
854 * This means anything which needs support from extension modules
855 * or pure Python code in the standard library won't work.
856 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600857 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700858 return 0;
859 }
860 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000861
Victor Stinner13019fd2015-04-03 13:10:54 +0200862 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700863 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200864
Eric Snow1abcf672017-05-23 21:46:51 -0700865 /* Finish setting up the sys module and import system */
866 /* GetPath may initialize state that _PySys_EndInit locks
867 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700868 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700869 PySys_SetPath(Py_GetPath());
870 if (_PySys_EndInit(interp->sysdict) < 0)
871 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700872 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000873
874 /* initialize the faulthandler module */
875 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700876 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000877
Nick Coghland6009512014-11-20 21:39:37 +1000878 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700879 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000880
Eric Snowc7ec9982017-05-23 23:00:52 -0700881 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000882 initsigs(); /* Signal handling stuff, including initintr() */
883
884 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700885 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000886
887 initmain(interp); /* Module __main__ */
888 if (initstdio() < 0)
889 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700890 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000891
892 /* Initialize warnings. */
893 if (PySys_HasWarnOptions()) {
894 PyObject *warnings_module = PyImport_ImportModule("warnings");
895 if (warnings_module == NULL) {
896 fprintf(stderr, "'import warnings' failed; traceback:\n");
897 PyErr_Print();
898 }
899 Py_XDECREF(warnings_module);
900 }
901
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600902 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700903
Nick Coghland6009512014-11-20 21:39:37 +1000904 if (!Py_NoSiteFlag)
905 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700906
Eric Snowc7ec9982017-05-23 23:00:52 -0700907 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000908}
909
Eric Snowc7ec9982017-05-23 23:00:52 -0700910#undef _INIT_DEBUG_PRINT
911
Nick Coghland6009512014-11-20 21:39:37 +1000912void
Eric Snow1abcf672017-05-23 21:46:51 -0700913_Py_InitializeEx_Private(int install_sigs, int install_importlib)
914{
915 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700916 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700917
918 /* TODO: Moar config options! */
919 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
920 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700921 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700922 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700923 /* TODO: Print any exceptions raised by these operations */
924 if (_Py_ReadMainInterpreterConfig(&config))
925 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
926 if (_Py_InitializeMainInterpreter(&config))
927 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700928}
929
930
931void
Nick Coghland6009512014-11-20 21:39:37 +1000932Py_InitializeEx(int install_sigs)
933{
934 _Py_InitializeEx_Private(install_sigs, 1);
935}
936
937void
938Py_Initialize(void)
939{
940 Py_InitializeEx(1);
941}
942
943
944#ifdef COUNT_ALLOCS
945extern void dump_counts(FILE*);
946#endif
947
948/* Flush stdout and stderr */
949
950static int
951file_is_closed(PyObject *fobj)
952{
953 int r;
954 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
955 if (tmp == NULL) {
956 PyErr_Clear();
957 return 0;
958 }
959 r = PyObject_IsTrue(tmp);
960 Py_DECREF(tmp);
961 if (r < 0)
962 PyErr_Clear();
963 return r > 0;
964}
965
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000966static int
Nick Coghland6009512014-11-20 21:39:37 +1000967flush_std_files(void)
968{
969 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
970 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
971 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000972 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000973
974 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700975 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000976 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000977 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000978 status = -1;
979 }
Nick Coghland6009512014-11-20 21:39:37 +1000980 else
981 Py_DECREF(tmp);
982 }
983
984 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700985 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000986 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000987 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000988 status = -1;
989 }
Nick Coghland6009512014-11-20 21:39:37 +1000990 else
991 Py_DECREF(tmp);
992 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000993
994 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000995}
996
997/* Undo the effect of Py_Initialize().
998
999 Beware: if multiple interpreter and/or thread states exist, these
1000 are not wiped out; only the current thread and interpreter state
1001 are deleted. But since everything else is deleted, those other
1002 interpreter and thread states should no longer be used.
1003
1004 (XXX We should do better, e.g. wipe out all interpreters and
1005 threads.)
1006
1007 Locking: as above.
1008
1009*/
1010
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001011int
1012Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001013{
1014 PyInterpreterState *interp;
1015 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001016 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001017
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001018 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001019 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001020
1021 wait_for_thread_shutdown();
1022
1023 /* The interpreter is still entirely intact at this point, and the
1024 * exit funcs may be relying on that. In particular, if some thread
1025 * or exit func is still waiting to do an import, the import machinery
1026 * expects Py_IsInitialized() to return true. So don't say the
1027 * interpreter is uninitialized until after the exit funcs have run.
1028 * Note that Threading.py uses an exit func to do a join on all the
1029 * threads created thru it, so this also protects pending imports in
1030 * the threads created via Threading.
1031 */
1032 call_py_exitfuncs();
1033
1034 /* Get current thread state and interpreter pointer */
1035 tstate = PyThreadState_GET();
1036 interp = tstate->interp;
1037
1038 /* Remaining threads (e.g. daemon threads) will automatically exit
1039 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001040 _PyRuntime.finalizing = tstate;
1041 _PyRuntime.initialized = 0;
1042 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001043
Victor Stinnere0deff32015-03-24 13:46:18 +01001044 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001045 if (flush_std_files() < 0) {
1046 status = -1;
1047 }
Nick Coghland6009512014-11-20 21:39:37 +10001048
1049 /* Disable signal handling */
1050 PyOS_FiniInterrupts();
1051
1052 /* Collect garbage. This may call finalizers; it's nice to call these
1053 * before all modules are destroyed.
1054 * XXX If a __del__ or weakref callback is triggered here, and tries to
1055 * XXX import a module, bad things can happen, because Python no
1056 * XXX longer believes it's initialized.
1057 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1058 * XXX is easy to provoke that way. I've also seen, e.g.,
1059 * XXX Exception exceptions.ImportError: 'No module named sha'
1060 * XXX in <function callback at 0x008F5718> ignored
1061 * XXX but I'm unclear on exactly how that one happens. In any case,
1062 * XXX I haven't seen a real-life report of either of these.
1063 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001064 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001065#ifdef COUNT_ALLOCS
1066 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1067 each collection might release some types from the type
1068 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001069 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001070 /* nothing */;
1071#endif
Eric Snowdae02762017-09-14 00:35:58 -07001072
1073#ifdef Py_REF_DEBUG
1074 PyObject *showrefcount = _PyDebug_XOptionShowRefCount();
1075#endif
1076
Nick Coghland6009512014-11-20 21:39:37 +10001077 /* Destroy all modules */
1078 PyImport_Cleanup();
1079
Victor Stinnere0deff32015-03-24 13:46:18 +01001080 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001081 if (flush_std_files() < 0) {
1082 status = -1;
1083 }
Nick Coghland6009512014-11-20 21:39:37 +10001084
1085 /* Collect final garbage. This disposes of cycles created by
1086 * class definitions, for example.
1087 * XXX This is disabled because it caused too many problems. If
1088 * XXX a __del__ or weakref callback triggers here, Python code has
1089 * XXX a hard time running, because even the sys module has been
1090 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1091 * XXX One symptom is a sequence of information-free messages
1092 * XXX coming from threads (if a __del__ or callback is invoked,
1093 * XXX other threads can execute too, and any exception they encounter
1094 * XXX triggers a comedy of errors as subsystem after subsystem
1095 * XXX fails to find what it *expects* to find in sys to help report
1096 * XXX the exception and consequent unexpected failures). I've also
1097 * XXX seen segfaults then, after adding print statements to the
1098 * XXX Python code getting called.
1099 */
1100#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001101 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001102#endif
1103
1104 /* Disable tracemalloc after all Python objects have been destroyed,
1105 so it is possible to use tracemalloc in objects destructor. */
1106 _PyTraceMalloc_Fini();
1107
1108 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1109 _PyImport_Fini();
1110
1111 /* Cleanup typeobject.c's internal caches. */
1112 _PyType_Fini();
1113
1114 /* unload faulthandler module */
1115 _PyFaulthandler_Fini();
1116
1117 /* Debugging stuff */
1118#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001119 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001120#endif
1121 /* dump hash stats */
1122 _PyHash_Fini();
1123
Eric Snowdae02762017-09-14 00:35:58 -07001124#ifdef Py_REF_DEBUG
1125 if (showrefcount == Py_True)
1126 _PyDebug_PrintTotalRefs();
1127#endif
Nick Coghland6009512014-11-20 21:39:37 +10001128
1129#ifdef Py_TRACE_REFS
1130 /* Display all objects still alive -- this can invoke arbitrary
1131 * __repr__ overrides, so requires a mostly-intact interpreter.
1132 * Alas, a lot of stuff may still be alive now that will be cleaned
1133 * up later.
1134 */
1135 if (Py_GETENV("PYTHONDUMPREFS"))
1136 _Py_PrintReferences(stderr);
1137#endif /* Py_TRACE_REFS */
1138
1139 /* Clear interpreter state and all thread states. */
1140 PyInterpreterState_Clear(interp);
1141
1142 /* Now we decref the exception classes. After this point nothing
1143 can raise an exception. That's okay, because each Fini() method
1144 below has been checked to make sure no exceptions are ever
1145 raised.
1146 */
1147
1148 _PyExc_Fini();
1149
1150 /* Sundry finalizers */
1151 PyMethod_Fini();
1152 PyFrame_Fini();
1153 PyCFunction_Fini();
1154 PyTuple_Fini();
1155 PyList_Fini();
1156 PySet_Fini();
1157 PyBytes_Fini();
1158 PyByteArray_Fini();
1159 PyLong_Fini();
1160 PyFloat_Fini();
1161 PyDict_Fini();
1162 PySlice_Fini();
1163 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001164 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001165 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001166 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001167
1168 /* Cleanup Unicode implementation */
1169 _PyUnicode_Fini();
1170
1171 /* reset file system default encoding */
1172 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1173 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1174 Py_FileSystemDefaultEncoding = NULL;
1175 }
1176
1177 /* XXX Still allocated:
1178 - various static ad-hoc pointers to interned strings
1179 - int and float free list blocks
1180 - whatever various modules and libraries allocate
1181 */
1182
1183 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1184
1185 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001186 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001187
1188 /* Delete current thread. After this, many C API calls become crashy. */
1189 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001190
Nick Coghland6009512014-11-20 21:39:37 +10001191 PyInterpreterState_Delete(interp);
1192
1193#ifdef Py_TRACE_REFS
1194 /* Display addresses (& refcnts) of all objects still alive.
1195 * An address can be used to find the repr of the object, printed
1196 * above by _Py_PrintReferences.
1197 */
1198 if (Py_GETENV("PYTHONDUMPREFS"))
1199 _Py_PrintReferenceAddresses(stderr);
1200#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001201#ifdef WITH_PYMALLOC
1202 if (_PyMem_PymallocEnabled()) {
1203 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1204 if (opt != NULL && *opt != '\0')
1205 _PyObject_DebugMallocStats(stderr);
1206 }
Nick Coghland6009512014-11-20 21:39:37 +10001207#endif
1208
1209 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001210 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001211 return status;
1212}
1213
1214void
1215Py_Finalize(void)
1216{
1217 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001218}
1219
1220/* Create and initialize a new interpreter and thread, and return the
1221 new thread. This requires that Py_Initialize() has been called
1222 first.
1223
1224 Unsuccessful initialization yields a NULL pointer. Note that *no*
1225 exception information is available even in this case -- the
1226 exception information is held in the thread, and there is no
1227 thread.
1228
1229 Locking: as above.
1230
1231*/
1232
1233PyThreadState *
1234Py_NewInterpreter(void)
1235{
1236 PyInterpreterState *interp;
1237 PyThreadState *tstate, *save_tstate;
1238 PyObject *bimod, *sysmod;
1239
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001240 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001241 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1242
Victor Stinner8a1be612016-03-14 22:07:55 +01001243 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1244 interpreters: disable PyGILState_Check(). */
1245 _PyGILState_check_enabled = 0;
1246
Nick Coghland6009512014-11-20 21:39:37 +10001247 interp = PyInterpreterState_New();
1248 if (interp == NULL)
1249 return NULL;
1250
1251 tstate = PyThreadState_New(interp);
1252 if (tstate == NULL) {
1253 PyInterpreterState_Delete(interp);
1254 return NULL;
1255 }
1256
1257 save_tstate = PyThreadState_Swap(tstate);
1258
Eric Snow1abcf672017-05-23 21:46:51 -07001259 /* Copy the current interpreter config into the new interpreter */
1260 if (save_tstate != NULL) {
1261 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001262 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001263 } else {
1264 /* No current thread state, copy from the main interpreter */
1265 PyInterpreterState *main_interp = PyInterpreterState_Main();
1266 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001267 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001268 }
1269
Nick Coghland6009512014-11-20 21:39:37 +10001270 /* XXX The following is lax in error checking */
1271
Eric Snowd393c1b2017-09-14 12:18:12 -06001272 PyObject *modules = PyDict_New();
1273 if (modules == NULL)
1274 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
1275 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001276
Eric Snowd393c1b2017-09-14 12:18:12 -06001277 sysmod = _PyImport_FindBuiltin("sys", modules);
1278 if (sysmod != NULL) {
1279 interp->sysdict = PyModule_GetDict(sysmod);
1280 if (interp->sysdict == NULL)
1281 goto handle_error;
1282 Py_INCREF(interp->sysdict);
1283 PyDict_SetItemString(interp->sysdict, "modules", modules);
1284 PySys_SetPath(Py_GetPath());
1285 _PySys_EndInit(interp->sysdict);
1286 }
1287
1288 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001289 if (bimod != NULL) {
1290 interp->builtins = PyModule_GetDict(bimod);
1291 if (interp->builtins == NULL)
1292 goto handle_error;
1293 Py_INCREF(interp->builtins);
1294 }
1295
1296 /* initialize builtin exceptions */
1297 _PyExc_Init(bimod);
1298
Nick Coghland6009512014-11-20 21:39:37 +10001299 if (bimod != NULL && sysmod != NULL) {
1300 PyObject *pstderr;
1301
Nick Coghland6009512014-11-20 21:39:37 +10001302 /* Set up a preliminary stderr printer until we have enough
1303 infrastructure for the io module in place. */
1304 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1305 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001306 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001307 _PySys_SetObjectId(&PyId_stderr, pstderr);
1308 PySys_SetObject("__stderr__", pstderr);
1309 Py_DECREF(pstderr);
1310
1311 _PyImportHooks_Init();
1312
Eric Snow1abcf672017-05-23 21:46:51 -07001313 initimport(interp, sysmod);
1314 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001315
1316 if (initfsencoding(interp) < 0)
1317 goto handle_error;
1318
1319 if (initstdio() < 0)
1320 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001321 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001322 initmain(interp);
1323 if (!Py_NoSiteFlag)
1324 initsite();
1325 }
1326
1327 if (!PyErr_Occurred())
1328 return tstate;
1329
1330handle_error:
1331 /* Oops, it didn't work. Undo it all. */
1332
1333 PyErr_PrintEx(0);
1334 PyThreadState_Clear(tstate);
1335 PyThreadState_Swap(save_tstate);
1336 PyThreadState_Delete(tstate);
1337 PyInterpreterState_Delete(interp);
1338
1339 return NULL;
1340}
1341
1342/* Delete an interpreter and its last thread. This requires that the
1343 given thread state is current, that the thread has no remaining
1344 frames, and that it is its interpreter's only remaining thread.
1345 It is a fatal error to violate these constraints.
1346
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001347 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001348 everything, regardless.)
1349
1350 Locking: as above.
1351
1352*/
1353
1354void
1355Py_EndInterpreter(PyThreadState *tstate)
1356{
1357 PyInterpreterState *interp = tstate->interp;
1358
1359 if (tstate != PyThreadState_GET())
1360 Py_FatalError("Py_EndInterpreter: thread is not current");
1361 if (tstate->frame != NULL)
1362 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1363
1364 wait_for_thread_shutdown();
1365
1366 if (tstate != interp->tstate_head || tstate->next != NULL)
1367 Py_FatalError("Py_EndInterpreter: not the last thread");
1368
1369 PyImport_Cleanup();
1370 PyInterpreterState_Clear(interp);
1371 PyThreadState_Swap(NULL);
1372 PyInterpreterState_Delete(interp);
1373}
1374
1375#ifdef MS_WINDOWS
1376static wchar_t *progname = L"python";
1377#else
1378static wchar_t *progname = L"python3";
1379#endif
1380
1381void
1382Py_SetProgramName(wchar_t *pn)
1383{
1384 if (pn && *pn)
1385 progname = pn;
1386}
1387
1388wchar_t *
1389Py_GetProgramName(void)
1390{
1391 return progname;
1392}
1393
1394static wchar_t *default_home = NULL;
1395static wchar_t env_home[MAXPATHLEN+1];
1396
1397void
1398Py_SetPythonHome(wchar_t *home)
1399{
1400 default_home = home;
1401}
1402
1403wchar_t *
1404Py_GetPythonHome(void)
1405{
1406 wchar_t *home = default_home;
1407 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1408 char* chome = Py_GETENV("PYTHONHOME");
1409 if (chome) {
1410 size_t size = Py_ARRAY_LENGTH(env_home);
1411 size_t r = mbstowcs(env_home, chome, size);
1412 if (r != (size_t)-1 && r < size)
1413 home = env_home;
1414 }
1415
1416 }
1417 return home;
1418}
1419
1420/* Create __main__ module */
1421
1422static void
1423initmain(PyInterpreterState *interp)
1424{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001425 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001426 m = PyImport_AddModule("__main__");
1427 if (m == NULL)
1428 Py_FatalError("can't create __main__ module");
1429 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001430 ann_dict = PyDict_New();
1431 if ((ann_dict == NULL) ||
1432 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1433 Py_FatalError("Failed to initialize __main__.__annotations__");
1434 }
1435 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001436 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1437 PyObject *bimod = PyImport_ImportModule("builtins");
1438 if (bimod == NULL) {
1439 Py_FatalError("Failed to retrieve builtins module");
1440 }
1441 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1442 Py_FatalError("Failed to initialize __main__.__builtins__");
1443 }
1444 Py_DECREF(bimod);
1445 }
1446 /* Main is a little special - imp.is_builtin("__main__") will return
1447 * False, but BuiltinImporter is still the most appropriate initial
1448 * setting for its __loader__ attribute. A more suitable value will
1449 * be set if __main__ gets further initialized later in the startup
1450 * process.
1451 */
1452 loader = PyDict_GetItemString(d, "__loader__");
1453 if (loader == NULL || loader == Py_None) {
1454 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1455 "BuiltinImporter");
1456 if (loader == NULL) {
1457 Py_FatalError("Failed to retrieve BuiltinImporter");
1458 }
1459 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1460 Py_FatalError("Failed to initialize __main__.__loader__");
1461 }
1462 Py_DECREF(loader);
1463 }
1464}
1465
1466static int
1467initfsencoding(PyInterpreterState *interp)
1468{
1469 PyObject *codec;
1470
Steve Dowercc16be82016-09-08 10:35:16 -07001471#ifdef MS_WINDOWS
1472 if (Py_LegacyWindowsFSEncodingFlag)
1473 {
1474 Py_FileSystemDefaultEncoding = "mbcs";
1475 Py_FileSystemDefaultEncodeErrors = "replace";
1476 }
1477 else
1478 {
1479 Py_FileSystemDefaultEncoding = "utf-8";
1480 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1481 }
1482#else
Nick Coghland6009512014-11-20 21:39:37 +10001483 if (Py_FileSystemDefaultEncoding == NULL)
1484 {
1485 Py_FileSystemDefaultEncoding = get_locale_encoding();
1486 if (Py_FileSystemDefaultEncoding == NULL)
1487 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1488
1489 Py_HasFileSystemDefaultEncoding = 0;
1490 interp->fscodec_initialized = 1;
1491 return 0;
1492 }
Steve Dowercc16be82016-09-08 10:35:16 -07001493#endif
Nick Coghland6009512014-11-20 21:39:37 +10001494
1495 /* the encoding is mbcs, utf-8 or ascii */
1496 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1497 if (!codec) {
1498 /* Such error can only occurs in critical situations: no more
1499 * memory, import a module of the standard library failed,
1500 * etc. */
1501 return -1;
1502 }
1503 Py_DECREF(codec);
1504 interp->fscodec_initialized = 1;
1505 return 0;
1506}
1507
1508/* Import the site module (not into __main__ though) */
1509
1510static void
1511initsite(void)
1512{
1513 PyObject *m;
1514 m = PyImport_ImportModule("site");
1515 if (m == NULL) {
1516 fprintf(stderr, "Failed to import the site module\n");
1517 PyErr_Print();
1518 Py_Finalize();
1519 exit(1);
1520 }
1521 else {
1522 Py_DECREF(m);
1523 }
1524}
1525
Victor Stinner874dbe82015-09-04 17:29:57 +02001526/* Check if a file descriptor is valid or not.
1527 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1528static int
1529is_valid_fd(int fd)
1530{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001531#ifdef __APPLE__
1532 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1533 and the other side of the pipe is closed, dup(1) succeed, whereas
1534 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1535 such error. */
1536 struct stat st;
1537 return (fstat(fd, &st) == 0);
1538#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001539 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001540 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001541 return 0;
1542 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001543 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1544 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1545 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001546 fd2 = dup(fd);
1547 if (fd2 >= 0)
1548 close(fd2);
1549 _Py_END_SUPPRESS_IPH
1550 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001551#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001552}
1553
1554/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001555static PyObject*
1556create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001557 int fd, int write_mode, const char* name,
1558 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001559{
1560 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1561 const char* mode;
1562 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001563 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001564 int buffering, isatty;
1565 _Py_IDENTIFIER(open);
1566 _Py_IDENTIFIER(isatty);
1567 _Py_IDENTIFIER(TextIOWrapper);
1568 _Py_IDENTIFIER(mode);
1569
Victor Stinner874dbe82015-09-04 17:29:57 +02001570 if (!is_valid_fd(fd))
1571 Py_RETURN_NONE;
1572
Nick Coghland6009512014-11-20 21:39:37 +10001573 /* stdin is always opened in buffered mode, first because it shouldn't
1574 make a difference in common use cases, second because TextIOWrapper
1575 depends on the presence of a read1() method which only exists on
1576 buffered streams.
1577 */
1578 if (Py_UnbufferedStdioFlag && write_mode)
1579 buffering = 0;
1580 else
1581 buffering = -1;
1582 if (write_mode)
1583 mode = "wb";
1584 else
1585 mode = "rb";
1586 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1587 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001588 Py_None, Py_None, /* encoding, errors */
1589 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001590 if (buf == NULL)
1591 goto error;
1592
1593 if (buffering) {
1594 _Py_IDENTIFIER(raw);
1595 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1596 if (raw == NULL)
1597 goto error;
1598 }
1599 else {
1600 raw = buf;
1601 Py_INCREF(raw);
1602 }
1603
Steve Dower39294992016-08-30 21:22:36 -07001604#ifdef MS_WINDOWS
1605 /* Windows console IO is always UTF-8 encoded */
1606 if (PyWindowsConsoleIO_Check(raw))
1607 encoding = "utf-8";
1608#endif
1609
Nick Coghland6009512014-11-20 21:39:37 +10001610 text = PyUnicode_FromString(name);
1611 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1612 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001613 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001614 if (res == NULL)
1615 goto error;
1616 isatty = PyObject_IsTrue(res);
1617 Py_DECREF(res);
1618 if (isatty == -1)
1619 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001620 if (Py_UnbufferedStdioFlag)
1621 write_through = Py_True;
1622 else
1623 write_through = Py_False;
1624 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001625 line_buffering = Py_True;
1626 else
1627 line_buffering = Py_False;
1628
1629 Py_CLEAR(raw);
1630 Py_CLEAR(text);
1631
1632#ifdef MS_WINDOWS
1633 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1634 newlines to "\n".
1635 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1636 newline = NULL;
1637#else
1638 /* sys.stdin: split lines at "\n".
1639 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1640 newline = "\n";
1641#endif
1642
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001643 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001644 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001645 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001646 Py_CLEAR(buf);
1647 if (stream == NULL)
1648 goto error;
1649
1650 if (write_mode)
1651 mode = "w";
1652 else
1653 mode = "r";
1654 text = PyUnicode_FromString(mode);
1655 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1656 goto error;
1657 Py_CLEAR(text);
1658 return stream;
1659
1660error:
1661 Py_XDECREF(buf);
1662 Py_XDECREF(stream);
1663 Py_XDECREF(text);
1664 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001665
Victor Stinner874dbe82015-09-04 17:29:57 +02001666 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1667 /* Issue #24891: the file descriptor was closed after the first
1668 is_valid_fd() check was called. Ignore the OSError and set the
1669 stream to None. */
1670 PyErr_Clear();
1671 Py_RETURN_NONE;
1672 }
1673 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001674}
1675
1676/* Initialize sys.stdin, stdout, stderr and builtins.open */
1677static int
1678initstdio(void)
1679{
1680 PyObject *iomod = NULL, *wrapper;
1681 PyObject *bimod = NULL;
1682 PyObject *m;
1683 PyObject *std = NULL;
1684 int status = 0, fd;
1685 PyObject * encoding_attr;
1686 char *pythonioencoding = NULL, *encoding, *errors;
1687
1688 /* Hack to avoid a nasty recursion issue when Python is invoked
1689 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1690 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1691 goto error;
1692 }
1693 Py_DECREF(m);
1694
1695 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1696 goto error;
1697 }
1698 Py_DECREF(m);
1699
1700 if (!(bimod = PyImport_ImportModule("builtins"))) {
1701 goto error;
1702 }
1703
1704 if (!(iomod = PyImport_ImportModule("io"))) {
1705 goto error;
1706 }
1707 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1708 goto error;
1709 }
1710
1711 /* Set builtins.open */
1712 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1713 Py_DECREF(wrapper);
1714 goto error;
1715 }
1716 Py_DECREF(wrapper);
1717
1718 encoding = _Py_StandardStreamEncoding;
1719 errors = _Py_StandardStreamErrors;
1720 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001721 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1722 if (pythonioencoding) {
1723 char *err;
1724 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1725 if (pythonioencoding == NULL) {
1726 PyErr_NoMemory();
1727 goto error;
1728 }
1729 err = strchr(pythonioencoding, ':');
1730 if (err) {
1731 *err = '\0';
1732 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001733 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001734 errors = err;
1735 }
1736 }
1737 if (*pythonioencoding && !encoding) {
1738 encoding = pythonioencoding;
1739 }
1740 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001741 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001742 /* Choose the default error handler based on the current locale */
1743 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001744 }
Nick Coghland6009512014-11-20 21:39:37 +10001745 }
1746
1747 /* Set sys.stdin */
1748 fd = fileno(stdin);
1749 /* Under some conditions stdin, stdout and stderr may not be connected
1750 * and fileno() may point to an invalid file descriptor. For example
1751 * GUI apps don't have valid standard streams by default.
1752 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001753 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1754 if (std == NULL)
1755 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001756 PySys_SetObject("__stdin__", std);
1757 _PySys_SetObjectId(&PyId_stdin, std);
1758 Py_DECREF(std);
1759
1760 /* Set sys.stdout */
1761 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001762 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1763 if (std == NULL)
1764 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001765 PySys_SetObject("__stdout__", std);
1766 _PySys_SetObjectId(&PyId_stdout, std);
1767 Py_DECREF(std);
1768
1769#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1770 /* Set sys.stderr, replaces the preliminary stderr */
1771 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001772 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1773 if (std == NULL)
1774 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001775
1776 /* Same as hack above, pre-import stderr's codec to avoid recursion
1777 when import.c tries to write to stderr in verbose mode. */
1778 encoding_attr = PyObject_GetAttrString(std, "encoding");
1779 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001780 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001781 if (std_encoding != NULL) {
1782 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1783 Py_XDECREF(codec_info);
1784 }
1785 Py_DECREF(encoding_attr);
1786 }
1787 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1788
1789 if (PySys_SetObject("__stderr__", std) < 0) {
1790 Py_DECREF(std);
1791 goto error;
1792 }
1793 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1794 Py_DECREF(std);
1795 goto error;
1796 }
1797 Py_DECREF(std);
1798#endif
1799
1800 if (0) {
1801 error:
1802 status = -1;
1803 }
1804
1805 /* We won't need them anymore. */
1806 if (_Py_StandardStreamEncoding) {
1807 PyMem_RawFree(_Py_StandardStreamEncoding);
1808 _Py_StandardStreamEncoding = NULL;
1809 }
1810 if (_Py_StandardStreamErrors) {
1811 PyMem_RawFree(_Py_StandardStreamErrors);
1812 _Py_StandardStreamErrors = NULL;
1813 }
1814 PyMem_Free(pythonioencoding);
1815 Py_XDECREF(bimod);
1816 Py_XDECREF(iomod);
1817 return status;
1818}
1819
1820
Victor Stinner10dc4842015-03-24 12:01:30 +01001821static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001822_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001823{
Victor Stinner10dc4842015-03-24 12:01:30 +01001824 fputc('\n', stderr);
1825 fflush(stderr);
1826
1827 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001828 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001829}
Victor Stinner791da1c2016-03-14 16:53:12 +01001830
1831/* Print the current exception (if an exception is set) with its traceback,
1832 or display the current Python stack.
1833
1834 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1835 called on catastrophic cases.
1836
1837 Return 1 if the traceback was displayed, 0 otherwise. */
1838
1839static int
1840_Py_FatalError_PrintExc(int fd)
1841{
1842 PyObject *ferr, *res;
1843 PyObject *exception, *v, *tb;
1844 int has_tb;
1845
1846 if (PyThreadState_GET() == NULL) {
1847 /* The GIL is released: trying to acquire it is likely to deadlock,
1848 just give up. */
1849 return 0;
1850 }
1851
1852 PyErr_Fetch(&exception, &v, &tb);
1853 if (exception == NULL) {
1854 /* No current exception */
1855 return 0;
1856 }
1857
1858 ferr = _PySys_GetObjectId(&PyId_stderr);
1859 if (ferr == NULL || ferr == Py_None) {
1860 /* sys.stderr is not set yet or set to None,
1861 no need to try to display the exception */
1862 return 0;
1863 }
1864
1865 PyErr_NormalizeException(&exception, &v, &tb);
1866 if (tb == NULL) {
1867 tb = Py_None;
1868 Py_INCREF(tb);
1869 }
1870 PyException_SetTraceback(v, tb);
1871 if (exception == NULL) {
1872 /* PyErr_NormalizeException() failed */
1873 return 0;
1874 }
1875
1876 has_tb = (tb != Py_None);
1877 PyErr_Display(exception, v, tb);
1878 Py_XDECREF(exception);
1879 Py_XDECREF(v);
1880 Py_XDECREF(tb);
1881
1882 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001883 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001884 if (res == NULL)
1885 PyErr_Clear();
1886 else
1887 Py_DECREF(res);
1888
1889 return has_tb;
1890}
1891
Nick Coghland6009512014-11-20 21:39:37 +10001892/* Print fatal error message and abort */
1893
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001894#ifdef MS_WINDOWS
1895static void
1896fatal_output_debug(const char *msg)
1897{
1898 /* buffer of 256 bytes allocated on the stack */
1899 WCHAR buffer[256 / sizeof(WCHAR)];
1900 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1901 size_t msglen;
1902
1903 OutputDebugStringW(L"Fatal Python error: ");
1904
1905 msglen = strlen(msg);
1906 while (msglen) {
1907 size_t i;
1908
1909 if (buflen > msglen) {
1910 buflen = msglen;
1911 }
1912
1913 /* Convert the message to wchar_t. This uses a simple one-to-one
1914 conversion, assuming that the this error message actually uses
1915 ASCII only. If this ceases to be true, we will have to convert. */
1916 for (i=0; i < buflen; ++i) {
1917 buffer[i] = msg[i];
1918 }
1919 buffer[i] = L'\0';
1920 OutputDebugStringW(buffer);
1921
1922 msg += buflen;
1923 msglen -= buflen;
1924 }
1925 OutputDebugStringW(L"\n");
1926}
1927#endif
1928
Nick Coghland6009512014-11-20 21:39:37 +10001929void
1930Py_FatalError(const char *msg)
1931{
1932 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001933 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001934
1935 if (reentrant) {
1936 /* Py_FatalError() caused a second fatal error.
1937 Example: flush_std_files() raises a recursion error. */
1938 goto exit;
1939 }
1940 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001941
1942 fprintf(stderr, "Fatal Python error: %s\n", msg);
1943 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001944
Victor Stinnere0deff32015-03-24 13:46:18 +01001945 /* Print the exception (if an exception is set) with its traceback,
1946 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001947 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001948 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001949 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001950
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001951 /* The main purpose of faulthandler is to display the traceback.
1952 This function already did its best to display a traceback.
1953 Disable faulthandler to prevent writing a second traceback
1954 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001955 _PyFaulthandler_Fini();
1956
Victor Stinner791da1c2016-03-14 16:53:12 +01001957 /* Check if the current Python thread hold the GIL */
1958 if (PyThreadState_GET() != NULL) {
1959 /* Flush sys.stdout and sys.stderr */
1960 flush_std_files();
1961 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001962
Nick Coghland6009512014-11-20 21:39:37 +10001963#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001964 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001965#endif /* MS_WINDOWS */
1966
1967exit:
1968#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001969 DebugBreak();
1970#endif
Nick Coghland6009512014-11-20 21:39:37 +10001971 abort();
1972}
1973
1974/* Clean up and exit */
1975
Victor Stinnerd7292b52016-06-17 12:29:00 +02001976# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001977
Nick Coghland6009512014-11-20 21:39:37 +10001978/* For the atexit module. */
1979void _Py_PyAtExit(void (*func)(void))
1980{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001981 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001982}
1983
1984static void
1985call_py_exitfuncs(void)
1986{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001987 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001988 return;
1989
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001990 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001991 PyErr_Clear();
1992}
1993
1994/* Wait until threading._shutdown completes, provided
1995 the threading module was imported in the first place.
1996 The shutdown routine will wait until all non-daemon
1997 "threading" threads have completed. */
1998static void
1999wait_for_thread_shutdown(void)
2000{
Nick Coghland6009512014-11-20 21:39:37 +10002001 _Py_IDENTIFIER(_shutdown);
2002 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002003 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002004 if (threading == NULL) {
2005 /* threading not imported */
2006 PyErr_Clear();
2007 return;
2008 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002009 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002010 if (result == NULL) {
2011 PyErr_WriteUnraisable(threading);
2012 }
2013 else {
2014 Py_DECREF(result);
2015 }
2016 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002017}
2018
2019#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002020int Py_AtExit(void (*func)(void))
2021{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002022 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002023 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002024 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002025 return 0;
2026}
2027
2028static void
2029call_ll_exitfuncs(void)
2030{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002031 while (_PyRuntime.nexitfuncs > 0)
2032 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002033
2034 fflush(stdout);
2035 fflush(stderr);
2036}
2037
2038void
2039Py_Exit(int sts)
2040{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002041 if (Py_FinalizeEx() < 0) {
2042 sts = 120;
2043 }
Nick Coghland6009512014-11-20 21:39:37 +10002044
2045 exit(sts);
2046}
2047
2048static void
2049initsigs(void)
2050{
2051#ifdef SIGPIPE
2052 PyOS_setsig(SIGPIPE, SIG_IGN);
2053#endif
2054#ifdef SIGXFZ
2055 PyOS_setsig(SIGXFZ, SIG_IGN);
2056#endif
2057#ifdef SIGXFSZ
2058 PyOS_setsig(SIGXFSZ, SIG_IGN);
2059#endif
2060 PyOS_InitInterrupts(); /* May imply initsignal() */
2061 if (PyErr_Occurred()) {
2062 Py_FatalError("Py_Initialize: can't import signal");
2063 }
2064}
2065
2066
2067/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2068 *
2069 * All of the code in this function must only use async-signal-safe functions,
2070 * listed at `man 7 signal` or
2071 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2072 */
2073void
2074_Py_RestoreSignals(void)
2075{
2076#ifdef SIGPIPE
2077 PyOS_setsig(SIGPIPE, SIG_DFL);
2078#endif
2079#ifdef SIGXFZ
2080 PyOS_setsig(SIGXFZ, SIG_DFL);
2081#endif
2082#ifdef SIGXFSZ
2083 PyOS_setsig(SIGXFSZ, SIG_DFL);
2084#endif
2085}
2086
2087
2088/*
2089 * The file descriptor fd is considered ``interactive'' if either
2090 * a) isatty(fd) is TRUE, or
2091 * b) the -i flag was given, and the filename associated with
2092 * the descriptor is NULL or "<stdin>" or "???".
2093 */
2094int
2095Py_FdIsInteractive(FILE *fp, const char *filename)
2096{
2097 if (isatty((int)fileno(fp)))
2098 return 1;
2099 if (!Py_InteractiveFlag)
2100 return 0;
2101 return (filename == NULL) ||
2102 (strcmp(filename, "<stdin>") == 0) ||
2103 (strcmp(filename, "???") == 0);
2104}
2105
2106
Nick Coghland6009512014-11-20 21:39:37 +10002107/* Wrappers around sigaction() or signal(). */
2108
2109PyOS_sighandler_t
2110PyOS_getsig(int sig)
2111{
2112#ifdef HAVE_SIGACTION
2113 struct sigaction context;
2114 if (sigaction(sig, NULL, &context) == -1)
2115 return SIG_ERR;
2116 return context.sa_handler;
2117#else
2118 PyOS_sighandler_t handler;
2119/* Special signal handling for the secure CRT in Visual Studio 2005 */
2120#if defined(_MSC_VER) && _MSC_VER >= 1400
2121 switch (sig) {
2122 /* Only these signals are valid */
2123 case SIGINT:
2124 case SIGILL:
2125 case SIGFPE:
2126 case SIGSEGV:
2127 case SIGTERM:
2128 case SIGBREAK:
2129 case SIGABRT:
2130 break;
2131 /* Don't call signal() with other values or it will assert */
2132 default:
2133 return SIG_ERR;
2134 }
2135#endif /* _MSC_VER && _MSC_VER >= 1400 */
2136 handler = signal(sig, SIG_IGN);
2137 if (handler != SIG_ERR)
2138 signal(sig, handler);
2139 return handler;
2140#endif
2141}
2142
2143/*
2144 * All of the code in this function must only use async-signal-safe functions,
2145 * listed at `man 7 signal` or
2146 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2147 */
2148PyOS_sighandler_t
2149PyOS_setsig(int sig, PyOS_sighandler_t handler)
2150{
2151#ifdef HAVE_SIGACTION
2152 /* Some code in Modules/signalmodule.c depends on sigaction() being
2153 * used here if HAVE_SIGACTION is defined. Fix that if this code
2154 * changes to invalidate that assumption.
2155 */
2156 struct sigaction context, ocontext;
2157 context.sa_handler = handler;
2158 sigemptyset(&context.sa_mask);
2159 context.sa_flags = 0;
2160 if (sigaction(sig, &context, &ocontext) == -1)
2161 return SIG_ERR;
2162 return ocontext.sa_handler;
2163#else
2164 PyOS_sighandler_t oldhandler;
2165 oldhandler = signal(sig, handler);
2166#ifdef HAVE_SIGINTERRUPT
2167 siginterrupt(sig, 1);
2168#endif
2169 return oldhandler;
2170#endif
2171}
2172
2173#ifdef __cplusplus
2174}
2175#endif