Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1 | /* 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 */ |
| 7 | #include "grammar.h" |
| 8 | #include "node.h" |
| 9 | #include "token.h" |
| 10 | #include "parsetok.h" |
| 11 | #include "errcode.h" |
| 12 | #include "code.h" |
| 13 | #include "symtable.h" |
| 14 | #include "ast.h" |
| 15 | #include "marshal.h" |
| 16 | #include "osdefs.h" |
| 17 | #include <locale.h> |
| 18 | |
| 19 | #ifdef HAVE_SIGNAL_H |
| 20 | #include <signal.h> |
| 21 | #endif |
| 22 | |
| 23 | #ifdef MS_WINDOWS |
| 24 | #include "malloc.h" /* for alloca */ |
| 25 | #endif |
| 26 | |
| 27 | #ifdef HAVE_LANGINFO_H |
| 28 | #include <langinfo.h> |
| 29 | #endif |
| 30 | |
| 31 | #ifdef MS_WINDOWS |
| 32 | #undef BYTE |
| 33 | #include "windows.h" |
Steve Dower | 3929499 | 2016-08-30 21:22:36 -0700 | [diff] [blame] | 34 | |
| 35 | extern PyTypeObject PyWindowsConsoleIO_Type; |
| 36 | #define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type)) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 37 | #endif |
| 38 | |
| 39 | _Py_IDENTIFIER(flush); |
| 40 | _Py_IDENTIFIER(name); |
| 41 | _Py_IDENTIFIER(stdin); |
| 42 | _Py_IDENTIFIER(stdout); |
| 43 | _Py_IDENTIFIER(stderr); |
| 44 | |
| 45 | #ifdef __cplusplus |
| 46 | extern "C" { |
| 47 | #endif |
| 48 | |
| 49 | extern wchar_t *Py_GetPath(void); |
| 50 | |
| 51 | extern grammar _PyParser_Grammar; /* From graminit.c */ |
| 52 | |
| 53 | /* Forward */ |
| 54 | static void initmain(PyInterpreterState *interp); |
| 55 | static int initfsencoding(PyInterpreterState *interp); |
| 56 | static void initsite(void); |
| 57 | static int initstdio(void); |
| 58 | static void initsigs(void); |
| 59 | static void call_py_exitfuncs(void); |
| 60 | static void wait_for_thread_shutdown(void); |
| 61 | static void call_ll_exitfuncs(void); |
| 62 | extern int _PyUnicode_Init(void); |
| 63 | extern int _PyStructSequence_Init(void); |
| 64 | extern void _PyUnicode_Fini(void); |
| 65 | extern int _PyLong_Init(void); |
| 66 | extern void PyLong_Fini(void); |
| 67 | extern int _PyFaulthandler_Init(void); |
| 68 | extern void _PyFaulthandler_Fini(void); |
| 69 | extern void _PyHash_Fini(void); |
| 70 | extern int _PyTraceMalloc_Init(void); |
| 71 | extern int _PyTraceMalloc_Fini(void); |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 72 | extern void _Py_ReadyTypes(void); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 73 | |
| 74 | #ifdef WITH_THREAD |
| 75 | extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *); |
| 76 | extern void _PyGILState_Fini(void); |
| 77 | #endif /* WITH_THREAD */ |
| 78 | |
| 79 | /* Global configuration variable declarations are in pydebug.h */ |
| 80 | /* XXX (ncoghlan): move those declarations to pylifecycle.h? */ |
| 81 | int Py_DebugFlag; /* Needed by parser.c */ |
| 82 | int Py_VerboseFlag; /* Needed by import.c */ |
| 83 | int Py_QuietFlag; /* Needed by sysmodule.c */ |
| 84 | int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */ |
| 85 | int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */ |
| 86 | int Py_OptimizeFlag = 0; /* Needed by compile.c */ |
| 87 | int Py_NoSiteFlag; /* Suppress 'import site' */ |
| 88 | int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */ |
| 89 | int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */ |
| 90 | int Py_FrozenFlag; /* Needed by getpath.c */ |
| 91 | int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */ |
Xiang Zhang | 0710d75 | 2017-03-11 13:02:52 +0800 | [diff] [blame] | 92 | int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 93 | int Py_NoUserSiteDirectory = 0; /* for -s and site.py */ |
| 94 | int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */ |
| 95 | int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */ |
| 96 | int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */ |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 97 | #ifdef MS_WINDOWS |
| 98 | int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */ |
Steve Dower | 3929499 | 2016-08-30 21:22:36 -0700 | [diff] [blame] | 99 | int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */ |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 100 | #endif |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 101 | |
| 102 | PyThreadState *_Py_Finalizing = NULL; |
| 103 | |
| 104 | /* Hack to force loading of object files */ |
| 105 | int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \ |
| 106 | PyOS_mystrnicmp; /* Python/pystrcmp.o */ |
| 107 | |
| 108 | /* PyModule_GetWarningsModule is no longer necessary as of 2.6 |
| 109 | since _warnings is builtin. This API should not be used. */ |
| 110 | PyObject * |
| 111 | PyModule_GetWarningsModule(void) |
| 112 | { |
| 113 | return PyImport_ImportModule("warnings"); |
| 114 | } |
| 115 | |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 116 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 117 | /* APIs to access the initialization flags |
| 118 | * |
| 119 | * Can be called prior to Py_Initialize. |
| 120 | */ |
| 121 | int _Py_CoreInitialized = 0; |
| 122 | int _Py_Initialized = 0; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 123 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 124 | int |
| 125 | _Py_IsCoreInitialized(void) |
| 126 | { |
| 127 | return _Py_CoreInitialized; |
| 128 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 129 | |
| 130 | int |
| 131 | Py_IsInitialized(void) |
| 132 | { |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 133 | return _Py_Initialized; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 134 | } |
| 135 | |
| 136 | /* Helper to allow an embedding application to override the normal |
| 137 | * mechanism that attempts to figure out an appropriate IO encoding |
| 138 | */ |
| 139 | |
| 140 | static char *_Py_StandardStreamEncoding = NULL; |
| 141 | static char *_Py_StandardStreamErrors = NULL; |
| 142 | |
| 143 | int |
| 144 | Py_SetStandardStreamEncoding(const char *encoding, const char *errors) |
| 145 | { |
| 146 | if (Py_IsInitialized()) { |
| 147 | /* This is too late to have any effect */ |
| 148 | return -1; |
| 149 | } |
| 150 | /* Can't call PyErr_NoMemory() on errors, as Python hasn't been |
| 151 | * initialised yet. |
| 152 | * |
| 153 | * However, the raw memory allocators are initialised appropriately |
| 154 | * as C static variables, so _PyMem_RawStrdup is OK even though |
| 155 | * Py_Initialize hasn't been called yet. |
| 156 | */ |
| 157 | if (encoding) { |
| 158 | _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding); |
| 159 | if (!_Py_StandardStreamEncoding) { |
| 160 | return -2; |
| 161 | } |
| 162 | } |
| 163 | if (errors) { |
| 164 | _Py_StandardStreamErrors = _PyMem_RawStrdup(errors); |
| 165 | if (!_Py_StandardStreamErrors) { |
| 166 | if (_Py_StandardStreamEncoding) { |
| 167 | PyMem_RawFree(_Py_StandardStreamEncoding); |
| 168 | } |
| 169 | return -3; |
| 170 | } |
| 171 | } |
Steve Dower | 3929499 | 2016-08-30 21:22:36 -0700 | [diff] [blame] | 172 | #ifdef MS_WINDOWS |
| 173 | if (_Py_StandardStreamEncoding) { |
| 174 | /* Overriding the stream encoding implies legacy streams */ |
| 175 | Py_LegacyWindowsStdioFlag = 1; |
| 176 | } |
| 177 | #endif |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 178 | return 0; |
| 179 | } |
| 180 | |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 181 | |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 182 | /* Global initializations. Can be undone by Py_FinalizeEx(). Don't |
| 183 | call this twice without an intervening Py_FinalizeEx() call. When |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 184 | initializations fail, a fatal error is issued and the function does |
| 185 | not return. On return, the first thread and interpreter state have |
| 186 | been created. |
| 187 | |
| 188 | Locking: you must hold the interpreter lock while calling this. |
| 189 | (If the lock has not yet been initialized, that's equivalent to |
| 190 | having the lock, but you cannot use multiple threads.) |
| 191 | |
| 192 | */ |
| 193 | |
| 194 | static int |
| 195 | add_flag(int flag, const char *envs) |
| 196 | { |
| 197 | int env = atoi(envs); |
| 198 | if (flag < env) |
| 199 | flag = env; |
| 200 | if (flag < 1) |
| 201 | flag = 1; |
| 202 | return flag; |
| 203 | } |
| 204 | |
| 205 | static char* |
| 206 | get_codec_name(const char *encoding) |
| 207 | { |
Serhiy Storchaka | 85b0f5b | 2016-11-20 10:16:47 +0200 | [diff] [blame] | 208 | const char *name_utf8; |
| 209 | char *name_str; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 210 | PyObject *codec, *name = NULL; |
| 211 | |
| 212 | codec = _PyCodec_Lookup(encoding); |
| 213 | if (!codec) |
| 214 | goto error; |
| 215 | |
| 216 | name = _PyObject_GetAttrId(codec, &PyId_name); |
| 217 | Py_CLEAR(codec); |
| 218 | if (!name) |
| 219 | goto error; |
| 220 | |
Serhiy Storchaka | 0651583 | 2016-11-20 09:13:07 +0200 | [diff] [blame] | 221 | name_utf8 = PyUnicode_AsUTF8(name); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 222 | if (name_utf8 == NULL) |
| 223 | goto error; |
| 224 | name_str = _PyMem_RawStrdup(name_utf8); |
| 225 | Py_DECREF(name); |
| 226 | if (name_str == NULL) { |
| 227 | PyErr_NoMemory(); |
| 228 | return NULL; |
| 229 | } |
| 230 | return name_str; |
| 231 | |
| 232 | error: |
| 233 | Py_XDECREF(codec); |
| 234 | Py_XDECREF(name); |
| 235 | return NULL; |
| 236 | } |
| 237 | |
| 238 | static char* |
| 239 | get_locale_encoding(void) |
| 240 | { |
| 241 | #ifdef MS_WINDOWS |
| 242 | char codepage[100]; |
| 243 | PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP()); |
| 244 | return get_codec_name(codepage); |
| 245 | #elif defined(HAVE_LANGINFO_H) && defined(CODESET) |
| 246 | char* codeset = nl_langinfo(CODESET); |
| 247 | if (!codeset || codeset[0] == '\0') { |
| 248 | PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty"); |
| 249 | return NULL; |
| 250 | } |
| 251 | return get_codec_name(codeset); |
Stefan Krah | 144da4e | 2016-04-26 01:56:50 +0200 | [diff] [blame] | 252 | #elif defined(__ANDROID__) |
| 253 | return get_codec_name("UTF-8"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 254 | #else |
| 255 | PyErr_SetNone(PyExc_NotImplementedError); |
| 256 | return NULL; |
| 257 | #endif |
| 258 | } |
| 259 | |
| 260 | static void |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 261 | initimport(PyInterpreterState *interp, PyObject *sysmod) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 262 | { |
| 263 | PyObject *importlib; |
| 264 | PyObject *impmod; |
| 265 | PyObject *sys_modules; |
| 266 | PyObject *value; |
| 267 | |
| 268 | /* Import _importlib through its frozen version, _frozen_importlib. */ |
| 269 | if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) { |
| 270 | Py_FatalError("Py_Initialize: can't import _frozen_importlib"); |
| 271 | } |
| 272 | else if (Py_VerboseFlag) { |
| 273 | PySys_FormatStderr("import _frozen_importlib # frozen\n"); |
| 274 | } |
| 275 | importlib = PyImport_AddModule("_frozen_importlib"); |
| 276 | if (importlib == NULL) { |
| 277 | Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from " |
| 278 | "sys.modules"); |
| 279 | } |
| 280 | interp->importlib = importlib; |
| 281 | Py_INCREF(interp->importlib); |
| 282 | |
Serhiy Storchaka | 133138a | 2016-08-02 22:51:21 +0300 | [diff] [blame] | 283 | interp->import_func = PyDict_GetItemString(interp->builtins, "__import__"); |
| 284 | if (interp->import_func == NULL) |
| 285 | Py_FatalError("Py_Initialize: __import__ not found"); |
| 286 | Py_INCREF(interp->import_func); |
| 287 | |
Victor Stinner | cd6e694 | 2015-09-18 09:11:57 +0200 | [diff] [blame] | 288 | /* Import the _imp module */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 289 | impmod = PyInit_imp(); |
| 290 | if (impmod == NULL) { |
Victor Stinner | cd6e694 | 2015-09-18 09:11:57 +0200 | [diff] [blame] | 291 | Py_FatalError("Py_Initialize: can't import _imp"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 292 | } |
| 293 | else if (Py_VerboseFlag) { |
Victor Stinner | cd6e694 | 2015-09-18 09:11:57 +0200 | [diff] [blame] | 294 | PySys_FormatStderr("import _imp # builtin\n"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 295 | } |
| 296 | sys_modules = PyImport_GetModuleDict(); |
| 297 | if (Py_VerboseFlag) { |
| 298 | PySys_FormatStderr("import sys # builtin\n"); |
| 299 | } |
| 300 | if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) { |
| 301 | Py_FatalError("Py_Initialize: can't save _imp to sys.modules"); |
| 302 | } |
| 303 | |
Victor Stinner | cd6e694 | 2015-09-18 09:11:57 +0200 | [diff] [blame] | 304 | /* Install importlib as the implementation of import */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 305 | value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod); |
Stéphane Wirtel | ab1cb80 | 2017-06-08 13:13:20 +0200 | [diff] [blame] | 306 | if (value != NULL) { |
| 307 | Py_DECREF(value); |
Eric Snow | 6b4be19 | 2017-05-22 21:36:03 -0700 | [diff] [blame] | 308 | value = PyObject_CallMethod(importlib, |
| 309 | "_install_external_importers", ""); |
Stéphane Wirtel | ab1cb80 | 2017-06-08 13:13:20 +0200 | [diff] [blame] | 310 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 311 | if (value == NULL) { |
| 312 | PyErr_Print(); |
| 313 | Py_FatalError("Py_Initialize: importlib install failed"); |
| 314 | } |
| 315 | Py_DECREF(value); |
| 316 | Py_DECREF(impmod); |
| 317 | |
| 318 | _PyImportZip_Init(); |
| 319 | } |
| 320 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 321 | static void |
| 322 | initexternalimport(PyInterpreterState *interp) |
| 323 | { |
| 324 | PyObject *value; |
| 325 | value = PyObject_CallMethod(interp->importlib, |
| 326 | "_install_external_importers", ""); |
| 327 | if (value == NULL) { |
| 328 | PyErr_Print(); |
| 329 | Py_FatalError("Py_EndInitialization: external importer setup failed"); |
| 330 | } |
Stéphane Wirtel | ab1cb80 | 2017-06-08 13:13:20 +0200 | [diff] [blame] | 331 | Py_DECREF(value); |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 332 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 333 | |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 334 | /* Helper functions to better handle the legacy C locale |
| 335 | * |
| 336 | * The legacy C locale assumes ASCII as the default text encoding, which |
| 337 | * causes problems not only for the CPython runtime, but also other |
| 338 | * components like GNU readline. |
| 339 | * |
| 340 | * Accordingly, when the CLI detects it, it attempts to coerce it to a |
| 341 | * more capable UTF-8 based alternative as follows: |
| 342 | * |
| 343 | * if (_Py_LegacyLocaleDetected()) { |
| 344 | * _Py_CoerceLegacyLocale(); |
| 345 | * } |
| 346 | * |
| 347 | * See the documentation of the PYTHONCOERCECLOCALE setting for more details. |
| 348 | * |
| 349 | * Locale coercion also impacts the default error handler for the standard |
| 350 | * streams: while the usual default is "strict", the default for the legacy |
| 351 | * C locale and for any of the coercion target locales is "surrogateescape". |
| 352 | */ |
| 353 | |
| 354 | int |
| 355 | _Py_LegacyLocaleDetected(void) |
| 356 | { |
| 357 | #ifndef MS_WINDOWS |
| 358 | /* On non-Windows systems, the C locale is considered a legacy locale */ |
Nick Coghlan | eb81795 | 2017-06-18 12:29:42 +1000 | [diff] [blame] | 359 | /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat |
| 360 | * the POSIX locale as a simple alias for the C locale, so |
| 361 | * we may also want to check for that explicitly. |
| 362 | */ |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 363 | const char *ctype_loc = setlocale(LC_CTYPE, NULL); |
| 364 | return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0; |
| 365 | #else |
| 366 | /* Windows uses code pages instead of locales, so no locale is legacy */ |
| 367 | return 0; |
| 368 | #endif |
| 369 | } |
| 370 | |
Nick Coghlan | eb81795 | 2017-06-18 12:29:42 +1000 | [diff] [blame] | 371 | static const char *_C_LOCALE_WARNING = |
| 372 | "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII " |
| 373 | "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, " |
| 374 | "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible " |
| 375 | "locales is recommended.\n"; |
| 376 | |
| 377 | static int |
| 378 | _legacy_locale_warnings_enabled(void) |
| 379 | { |
| 380 | const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE"); |
| 381 | return (coerce_c_locale != NULL && |
| 382 | strncmp(coerce_c_locale, "warn", 5) == 0); |
| 383 | } |
| 384 | |
| 385 | static void |
| 386 | _emit_stderr_warning_for_legacy_locale(void) |
| 387 | { |
| 388 | if (_legacy_locale_warnings_enabled()) { |
| 389 | if (_Py_LegacyLocaleDetected()) { |
| 390 | fprintf(stderr, "%s", _C_LOCALE_WARNING); |
| 391 | } |
| 392 | } |
| 393 | } |
| 394 | |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 395 | typedef struct _CandidateLocale { |
| 396 | const char *locale_name; /* The locale to try as a coercion target */ |
| 397 | } _LocaleCoercionTarget; |
| 398 | |
| 399 | static _LocaleCoercionTarget _TARGET_LOCALES[] = { |
| 400 | {"C.UTF-8"}, |
| 401 | {"C.utf8"}, |
Nick Coghlan | 18974c3 | 2017-06-30 00:48:14 +1000 | [diff] [blame] | 402 | {"UTF-8"}, |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 403 | {NULL} |
| 404 | }; |
| 405 | |
| 406 | static char * |
| 407 | get_default_standard_stream_error_handler(void) |
| 408 | { |
| 409 | const char *ctype_loc = setlocale(LC_CTYPE, NULL); |
| 410 | if (ctype_loc != NULL) { |
| 411 | /* "surrogateescape" is the default in the legacy C locale */ |
| 412 | if (strcmp(ctype_loc, "C") == 0) { |
| 413 | return "surrogateescape"; |
| 414 | } |
| 415 | |
| 416 | #ifdef PY_COERCE_C_LOCALE |
| 417 | /* "surrogateescape" is the default in locale coercion target locales */ |
| 418 | const _LocaleCoercionTarget *target = NULL; |
| 419 | for (target = _TARGET_LOCALES; target->locale_name; target++) { |
| 420 | if (strcmp(ctype_loc, target->locale_name) == 0) { |
| 421 | return "surrogateescape"; |
| 422 | } |
| 423 | } |
| 424 | #endif |
| 425 | } |
| 426 | |
| 427 | /* Otherwise return NULL to request the typical default error handler */ |
| 428 | return NULL; |
| 429 | } |
| 430 | |
| 431 | #ifdef PY_COERCE_C_LOCALE |
| 432 | static const char *_C_LOCALE_COERCION_WARNING = |
| 433 | "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale " |
| 434 | "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n"; |
| 435 | |
| 436 | static void |
| 437 | _coerce_default_locale_settings(const _LocaleCoercionTarget *target) |
| 438 | { |
| 439 | const char *newloc = target->locale_name; |
| 440 | |
| 441 | /* Reset locale back to currently configured defaults */ |
| 442 | setlocale(LC_ALL, ""); |
| 443 | |
| 444 | /* Set the relevant locale environment variable */ |
| 445 | if (setenv("LC_CTYPE", newloc, 1)) { |
| 446 | fprintf(stderr, |
| 447 | "Error setting LC_CTYPE, skipping C locale coercion\n"); |
| 448 | return; |
| 449 | } |
Nick Coghlan | eb81795 | 2017-06-18 12:29:42 +1000 | [diff] [blame] | 450 | if (_legacy_locale_warnings_enabled()) { |
| 451 | fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc); |
| 452 | } |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 453 | |
| 454 | /* Reconfigure with the overridden environment variables */ |
| 455 | setlocale(LC_ALL, ""); |
| 456 | } |
| 457 | #endif |
| 458 | |
| 459 | void |
| 460 | _Py_CoerceLegacyLocale(void) |
| 461 | { |
| 462 | #ifdef PY_COERCE_C_LOCALE |
| 463 | /* We ignore the Python -E and -I flags here, as the CLI needs to sort out |
| 464 | * the locale settings *before* we try to do anything with the command |
| 465 | * line arguments. For cross-platform debugging purposes, we also need |
| 466 | * to give end users a way to force even scripts that are otherwise |
| 467 | * isolated from their environment to use the legacy ASCII-centric C |
| 468 | * locale. |
| 469 | * |
| 470 | * Ignoring -E and -I is safe from a security perspective, as we only use |
| 471 | * the setting to turn *off* the implicit locale coercion, and anyone with |
| 472 | * access to the process environment already has the ability to set |
| 473 | * `LC_ALL=C` to override the C level locale settings anyway. |
| 474 | */ |
| 475 | const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE"); |
| 476 | if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) { |
| 477 | /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */ |
| 478 | const char *locale_override = getenv("LC_ALL"); |
| 479 | if (locale_override == NULL || *locale_override == '\0') { |
| 480 | /* LC_ALL is also not set (or is set to an empty string) */ |
| 481 | const _LocaleCoercionTarget *target = NULL; |
| 482 | for (target = _TARGET_LOCALES; target->locale_name; target++) { |
| 483 | const char *new_locale = setlocale(LC_CTYPE, |
| 484 | target->locale_name); |
| 485 | if (new_locale != NULL) { |
Nick Coghlan | 18974c3 | 2017-06-30 00:48:14 +1000 | [diff] [blame] | 486 | #if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET) |
| 487 | /* Also ensure that nl_langinfo works in this locale */ |
| 488 | char *codeset = nl_langinfo(CODESET); |
| 489 | if (!codeset || *codeset == '\0') { |
| 490 | /* CODESET is not set or empty, so skip coercion */ |
| 491 | new_locale = NULL; |
| 492 | setlocale(LC_CTYPE, ""); |
| 493 | continue; |
| 494 | } |
| 495 | #endif |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 496 | /* Successfully configured locale, so make it the default */ |
| 497 | _coerce_default_locale_settings(target); |
| 498 | return; |
| 499 | } |
| 500 | } |
| 501 | } |
| 502 | } |
| 503 | /* No C locale warning here, as Py_Initialize will emit one later */ |
| 504 | #endif |
| 505 | } |
| 506 | |
| 507 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 508 | /* Global initializations. Can be undone by Py_Finalize(). Don't |
| 509 | call this twice without an intervening Py_Finalize() call. |
| 510 | |
| 511 | Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx |
| 512 | must have a corresponding call to Py_Finalize. |
| 513 | |
| 514 | Locking: you must hold the interpreter lock while calling these APIs. |
| 515 | (If the lock has not yet been initialized, that's equivalent to |
| 516 | having the lock, but you cannot use multiple threads.) |
| 517 | |
| 518 | */ |
| 519 | |
| 520 | /* Begin interpreter initialization |
| 521 | * |
| 522 | * On return, the first thread and interpreter state have been created, |
| 523 | * but the compiler, signal handling, multithreading and |
| 524 | * multiple interpreter support, and codec infrastructure are not yet |
| 525 | * available. |
| 526 | * |
| 527 | * The import system will support builtin and frozen modules only. |
| 528 | * The only supported io is writing to sys.stderr |
| 529 | * |
| 530 | * If any operation invoked by this function fails, a fatal error is |
| 531 | * issued and the function does not return. |
| 532 | * |
| 533 | * Any code invoked from this function should *not* assume it has access |
| 534 | * to the Python C API (unless the API is explicitly listed as being |
| 535 | * safe to call without calling Py_Initialize first) |
| 536 | */ |
| 537 | |
Stéphane Wirtel | ccfdb60 | 2017-07-25 14:32:08 +0200 | [diff] [blame] | 538 | /* TODO: Progressively move functionality from Py_BeginInitialization to |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 539 | * Py_ReadConfig and Py_EndInitialization |
| 540 | */ |
| 541 | |
| 542 | void _Py_InitializeCore(const _PyCoreConfig *config) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 543 | { |
| 544 | PyInterpreterState *interp; |
| 545 | PyThreadState *tstate; |
| 546 | PyObject *bimod, *sysmod, *pstderr; |
| 547 | char *p; |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 548 | _PyCoreConfig core_config = _PyCoreConfig_INIT; |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 549 | _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 550 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 551 | if (config != NULL) { |
| 552 | core_config = *config; |
| 553 | } |
| 554 | |
| 555 | if (_Py_Initialized) { |
| 556 | Py_FatalError("Py_InitializeCore: main interpreter already initialized"); |
| 557 | } |
| 558 | if (_Py_CoreInitialized) { |
| 559 | Py_FatalError("Py_InitializeCore: runtime core already initialized"); |
| 560 | } |
| 561 | |
| 562 | /* Py_Finalize leaves _Py_Finalizing set in order to help daemon |
| 563 | * threads behave a little more gracefully at interpreter shutdown. |
| 564 | * We clobber it here so the new interpreter can start with a clean |
| 565 | * slate. |
| 566 | * |
| 567 | * However, this may still lead to misbehaviour if there are daemon |
| 568 | * threads still hanging around from a previous Py_Initialize/Finalize |
| 569 | * pair :( |
| 570 | */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 571 | _Py_Finalizing = NULL; |
| 572 | |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 573 | #ifdef __ANDROID__ |
| 574 | /* Passing "" to setlocale() on Android requests the C locale rather |
| 575 | * than checking environment variables, so request C.UTF-8 explicitly |
| 576 | */ |
| 577 | setlocale(LC_CTYPE, "C.UTF-8"); |
| 578 | #else |
| 579 | #ifndef MS_WINDOWS |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 580 | /* Set up the LC_CTYPE locale, so we can obtain |
| 581 | the locale's charset without having to switch |
| 582 | locales. */ |
| 583 | setlocale(LC_CTYPE, ""); |
Nick Coghlan | eb81795 | 2017-06-18 12:29:42 +1000 | [diff] [blame] | 584 | _emit_stderr_warning_for_legacy_locale(); |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 585 | #endif |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 586 | #endif |
| 587 | |
| 588 | if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') |
| 589 | Py_DebugFlag = add_flag(Py_DebugFlag, p); |
| 590 | if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') |
| 591 | Py_VerboseFlag = add_flag(Py_VerboseFlag, p); |
| 592 | if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') |
| 593 | Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); |
| 594 | if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') |
| 595 | Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); |
Eric Snow | 6b4be19 | 2017-05-22 21:36:03 -0700 | [diff] [blame] | 596 | /* The variable is only tested for existence here; |
| 597 | _Py_HashRandomization_Init will check its value further. */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 598 | if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0') |
| 599 | Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p); |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 600 | #ifdef MS_WINDOWS |
| 601 | if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0') |
| 602 | Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p); |
Steve Dower | 3929499 | 2016-08-30 21:22:36 -0700 | [diff] [blame] | 603 | if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0') |
| 604 | Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p); |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 605 | #endif |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 606 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 607 | _Py_HashRandomization_Init(&core_config); |
| 608 | if (!core_config.use_hash_seed || core_config.hash_seed) { |
| 609 | /* Random or non-zero hash seed */ |
| 610 | Py_HashRandomizationFlag = 1; |
| 611 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 612 | |
Eric Snow | e377416 | 2017-05-22 19:46:40 -0700 | [diff] [blame] | 613 | _PyInterpreterState_Init(); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 614 | interp = PyInterpreterState_New(); |
| 615 | if (interp == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 616 | Py_FatalError("Py_InitializeCore: can't make main interpreter"); |
| 617 | interp->core_config = core_config; |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 618 | interp->config = preinit_config; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 619 | |
| 620 | tstate = PyThreadState_New(interp); |
| 621 | if (tstate == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 622 | Py_FatalError("Py_InitializeCore: can't make first thread"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 623 | (void) PyThreadState_Swap(tstate); |
| 624 | |
| 625 | #ifdef WITH_THREAD |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 626 | /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 627 | destroying the GIL might fail when it is being referenced from |
| 628 | another running thread (see issue #9901). |
| 629 | Instead we destroy the previously created GIL here, which ensures |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 630 | that we can call Py_Initialize / Py_FinalizeEx multiple times. */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 631 | _PyEval_FiniThreads(); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 632 | /* Auto-thread-state API */ |
| 633 | _PyGILState_Init(interp, tstate); |
| 634 | #endif /* WITH_THREAD */ |
| 635 | |
| 636 | _Py_ReadyTypes(); |
| 637 | |
| 638 | if (!_PyFrame_Init()) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 639 | Py_FatalError("Py_InitializeCore: can't init frames"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 640 | |
| 641 | if (!_PyLong_Init()) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 642 | Py_FatalError("Py_InitializeCore: can't init longs"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 643 | |
| 644 | if (!PyByteArray_Init()) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 645 | Py_FatalError("Py_InitializeCore: can't init bytearray"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 646 | |
| 647 | if (!_PyFloat_Init()) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 648 | Py_FatalError("Py_InitializeCore: can't init float"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 649 | |
| 650 | interp->modules = PyDict_New(); |
| 651 | if (interp->modules == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 652 | Py_FatalError("Py_InitializeCore: can't make modules dictionary"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 653 | |
| 654 | /* Init Unicode implementation; relies on the codec registry */ |
| 655 | if (_PyUnicode_Init() < 0) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 656 | Py_FatalError("Py_InitializeCore: can't initialize unicode"); |
| 657 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 658 | if (_PyStructSequence_Init() < 0) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 659 | Py_FatalError("Py_InitializeCore: can't initialize structseq"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 660 | |
| 661 | bimod = _PyBuiltin_Init(); |
| 662 | if (bimod == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 663 | Py_FatalError("Py_InitializeCore: can't initialize builtins modules"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 664 | _PyImport_FixupBuiltin(bimod, "builtins"); |
| 665 | interp->builtins = PyModule_GetDict(bimod); |
| 666 | if (interp->builtins == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 667 | Py_FatalError("Py_InitializeCore: can't initialize builtins dict"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 668 | Py_INCREF(interp->builtins); |
| 669 | |
| 670 | /* initialize builtin exceptions */ |
| 671 | _PyExc_Init(bimod); |
| 672 | |
Eric Snow | 6b4be19 | 2017-05-22 21:36:03 -0700 | [diff] [blame] | 673 | sysmod = _PySys_BeginInit(); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 674 | if (sysmod == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 675 | Py_FatalError("Py_InitializeCore: can't initialize sys"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 676 | interp->sysdict = PyModule_GetDict(sysmod); |
| 677 | if (interp->sysdict == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 678 | Py_FatalError("Py_InitializeCore: can't initialize sys dict"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 679 | Py_INCREF(interp->sysdict); |
| 680 | _PyImport_FixupBuiltin(sysmod, "sys"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 681 | PyDict_SetItemString(interp->sysdict, "modules", |
| 682 | interp->modules); |
| 683 | |
| 684 | /* Set up a preliminary stderr printer until we have enough |
| 685 | infrastructure for the io module in place. */ |
| 686 | pstderr = PyFile_NewStdPrinter(fileno(stderr)); |
| 687 | if (pstderr == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 688 | Py_FatalError("Py_InitializeCore: can't set preliminary stderr"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 689 | _PySys_SetObjectId(&PyId_stderr, pstderr); |
| 690 | PySys_SetObject("__stderr__", pstderr); |
| 691 | Py_DECREF(pstderr); |
| 692 | |
| 693 | _PyImport_Init(); |
| 694 | |
| 695 | _PyImportHooks_Init(); |
| 696 | |
| 697 | /* Initialize _warnings. */ |
| 698 | _PyWarnings_Init(); |
| 699 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 700 | /* This call sets up builtin and frozen import support */ |
| 701 | if (!interp->core_config._disable_importlib) { |
| 702 | initimport(interp, sysmod); |
| 703 | } |
| 704 | |
| 705 | /* Only when we get here is the runtime core fully initialized */ |
| 706 | _Py_CoreInitialized = 1; |
| 707 | } |
| 708 | |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 709 | /* Read configuration settings from standard locations |
| 710 | * |
| 711 | * This function doesn't make any changes to the interpreter state - it |
| 712 | * merely populates any missing configuration settings. This allows an |
| 713 | * embedding application to completely override a config option by |
| 714 | * setting it before calling this function, or else modify the default |
| 715 | * setting before passing the fully populated config to Py_EndInitialization. |
| 716 | * |
| 717 | * More advanced selective initialization tricks are possible by calling |
| 718 | * this function multiple times with various preconfigured settings. |
| 719 | */ |
| 720 | |
| 721 | int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config) |
| 722 | { |
| 723 | /* Signal handlers are installed by default */ |
| 724 | if (config->install_signal_handlers < 0) { |
| 725 | config->install_signal_handlers = 1; |
| 726 | } |
| 727 | |
| 728 | return 0; |
| 729 | } |
| 730 | |
| 731 | /* Update interpreter state based on supplied configuration settings |
| 732 | * |
| 733 | * After calling this function, most of the restrictions on the interpreter |
| 734 | * are lifted. The only remaining incomplete settings are those related |
| 735 | * to the main module (sys.argv[0], __main__ metadata) |
| 736 | * |
| 737 | * Calling this when the interpreter is not initializing, is already |
| 738 | * initialized or without a valid current thread state is a fatal error. |
| 739 | * Other errors should be reported as normal Python exceptions with a |
| 740 | * non-zero return code. |
| 741 | */ |
| 742 | int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 743 | { |
| 744 | PyInterpreterState *interp; |
| 745 | PyThreadState *tstate; |
| 746 | |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 747 | if (!_Py_CoreInitialized) { |
| 748 | Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized"); |
| 749 | } |
| 750 | if (_Py_Initialized) { |
| 751 | Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized"); |
| 752 | } |
| 753 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 754 | /* Get current thread state and interpreter pointer */ |
| 755 | tstate = PyThreadState_GET(); |
| 756 | if (!tstate) |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 757 | Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state"); |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 758 | interp = tstate->interp; |
| 759 | if (!interp) |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 760 | Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter"); |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 761 | |
| 762 | /* Now finish configuring the main interpreter */ |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 763 | interp->config = *config; |
| 764 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 765 | if (interp->core_config._disable_importlib) { |
| 766 | /* Special mode for freeze_importlib: run with no import system |
| 767 | * |
| 768 | * This means anything which needs support from extension modules |
| 769 | * or pure Python code in the standard library won't work. |
| 770 | */ |
| 771 | _Py_Initialized = 1; |
| 772 | return 0; |
| 773 | } |
| 774 | /* TODO: Report exceptions rather than fatal errors below here */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 775 | |
Victor Stinner | 13019fd | 2015-04-03 13:10:54 +0200 | [diff] [blame] | 776 | if (_PyTime_Init() < 0) |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 777 | Py_FatalError("Py_InitializeMainInterpreter: can't initialize time"); |
Victor Stinner | 13019fd | 2015-04-03 13:10:54 +0200 | [diff] [blame] | 778 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 779 | /* Finish setting up the sys module and import system */ |
| 780 | /* GetPath may initialize state that _PySys_EndInit locks |
| 781 | in, and so has to be called first. */ |
Eric Snow | 18c1356 | 2017-05-25 10:05:50 -0700 | [diff] [blame] | 782 | /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */ |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 783 | PySys_SetPath(Py_GetPath()); |
| 784 | if (_PySys_EndInit(interp->sysdict) < 0) |
| 785 | Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys"); |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 786 | initexternalimport(interp); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 787 | |
| 788 | /* initialize the faulthandler module */ |
| 789 | if (_PyFaulthandler_Init()) |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 790 | Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 791 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 792 | if (initfsencoding(interp) < 0) |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 793 | Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 794 | |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 795 | if (config->install_signal_handlers) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 796 | initsigs(); /* Signal handling stuff, including initintr() */ |
| 797 | |
| 798 | if (_PyTraceMalloc_Init() < 0) |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 799 | Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 800 | |
| 801 | initmain(interp); /* Module __main__ */ |
| 802 | if (initstdio() < 0) |
| 803 | Py_FatalError( |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 804 | "Py_InitializeMainInterpreter: can't initialize sys standard streams"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 805 | |
| 806 | /* Initialize warnings. */ |
| 807 | if (PySys_HasWarnOptions()) { |
| 808 | PyObject *warnings_module = PyImport_ImportModule("warnings"); |
| 809 | if (warnings_module == NULL) { |
| 810 | fprintf(stderr, "'import warnings' failed; traceback:\n"); |
| 811 | PyErr_Print(); |
| 812 | } |
| 813 | Py_XDECREF(warnings_module); |
| 814 | } |
| 815 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 816 | _Py_Initialized = 1; |
| 817 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 818 | if (!Py_NoSiteFlag) |
| 819 | initsite(); /* Module site */ |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 820 | |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 821 | return 0; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 822 | } |
| 823 | |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 824 | #undef _INIT_DEBUG_PRINT |
| 825 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 826 | void |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 827 | _Py_InitializeEx_Private(int install_sigs, int install_importlib) |
| 828 | { |
| 829 | _PyCoreConfig core_config = _PyCoreConfig_INIT; |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 830 | _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT; |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 831 | |
| 832 | /* TODO: Moar config options! */ |
| 833 | core_config.ignore_environment = Py_IgnoreEnvironmentFlag; |
| 834 | core_config._disable_importlib = !install_importlib; |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 835 | config.install_signal_handlers = install_sigs; |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 836 | _Py_InitializeCore(&core_config); |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 837 | /* TODO: Print any exceptions raised by these operations */ |
| 838 | if (_Py_ReadMainInterpreterConfig(&config)) |
| 839 | Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed"); |
| 840 | if (_Py_InitializeMainInterpreter(&config)) |
| 841 | Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed"); |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 842 | } |
| 843 | |
| 844 | |
| 845 | void |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 846 | Py_InitializeEx(int install_sigs) |
| 847 | { |
| 848 | _Py_InitializeEx_Private(install_sigs, 1); |
| 849 | } |
| 850 | |
| 851 | void |
| 852 | Py_Initialize(void) |
| 853 | { |
| 854 | Py_InitializeEx(1); |
| 855 | } |
| 856 | |
| 857 | |
| 858 | #ifdef COUNT_ALLOCS |
| 859 | extern void dump_counts(FILE*); |
| 860 | #endif |
| 861 | |
| 862 | /* Flush stdout and stderr */ |
| 863 | |
| 864 | static int |
| 865 | file_is_closed(PyObject *fobj) |
| 866 | { |
| 867 | int r; |
| 868 | PyObject *tmp = PyObject_GetAttrString(fobj, "closed"); |
| 869 | if (tmp == NULL) { |
| 870 | PyErr_Clear(); |
| 871 | return 0; |
| 872 | } |
| 873 | r = PyObject_IsTrue(tmp); |
| 874 | Py_DECREF(tmp); |
| 875 | if (r < 0) |
| 876 | PyErr_Clear(); |
| 877 | return r > 0; |
| 878 | } |
| 879 | |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 880 | static int |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 881 | flush_std_files(void) |
| 882 | { |
| 883 | PyObject *fout = _PySys_GetObjectId(&PyId_stdout); |
| 884 | PyObject *ferr = _PySys_GetObjectId(&PyId_stderr); |
| 885 | PyObject *tmp; |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 886 | int status = 0; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 887 | |
| 888 | if (fout != NULL && fout != Py_None && !file_is_closed(fout)) { |
Victor Stinner | 3466bde | 2016-09-05 18:16:01 -0700 | [diff] [blame] | 889 | tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL); |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 890 | if (tmp == NULL) { |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 891 | PyErr_WriteUnraisable(fout); |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 892 | status = -1; |
| 893 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 894 | else |
| 895 | Py_DECREF(tmp); |
| 896 | } |
| 897 | |
| 898 | if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) { |
Victor Stinner | 3466bde | 2016-09-05 18:16:01 -0700 | [diff] [blame] | 899 | tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL); |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 900 | if (tmp == NULL) { |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 901 | PyErr_Clear(); |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 902 | status = -1; |
| 903 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 904 | else |
| 905 | Py_DECREF(tmp); |
| 906 | } |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 907 | |
| 908 | return status; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 909 | } |
| 910 | |
| 911 | /* Undo the effect of Py_Initialize(). |
| 912 | |
| 913 | Beware: if multiple interpreter and/or thread states exist, these |
| 914 | are not wiped out; only the current thread and interpreter state |
| 915 | are deleted. But since everything else is deleted, those other |
| 916 | interpreter and thread states should no longer be used. |
| 917 | |
| 918 | (XXX We should do better, e.g. wipe out all interpreters and |
| 919 | threads.) |
| 920 | |
| 921 | Locking: as above. |
| 922 | |
| 923 | */ |
| 924 | |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 925 | int |
| 926 | Py_FinalizeEx(void) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 927 | { |
| 928 | PyInterpreterState *interp; |
| 929 | PyThreadState *tstate; |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 930 | int status = 0; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 931 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 932 | if (!_Py_Initialized) |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 933 | return status; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 934 | |
| 935 | wait_for_thread_shutdown(); |
| 936 | |
| 937 | /* The interpreter is still entirely intact at this point, and the |
| 938 | * exit funcs may be relying on that. In particular, if some thread |
| 939 | * or exit func is still waiting to do an import, the import machinery |
| 940 | * expects Py_IsInitialized() to return true. So don't say the |
| 941 | * interpreter is uninitialized until after the exit funcs have run. |
| 942 | * Note that Threading.py uses an exit func to do a join on all the |
| 943 | * threads created thru it, so this also protects pending imports in |
| 944 | * the threads created via Threading. |
| 945 | */ |
| 946 | call_py_exitfuncs(); |
| 947 | |
| 948 | /* Get current thread state and interpreter pointer */ |
| 949 | tstate = PyThreadState_GET(); |
| 950 | interp = tstate->interp; |
| 951 | |
| 952 | /* Remaining threads (e.g. daemon threads) will automatically exit |
| 953 | after taking the GIL (in PyEval_RestoreThread()). */ |
| 954 | _Py_Finalizing = tstate; |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 955 | _Py_Initialized = 0; |
| 956 | _Py_CoreInitialized = 0; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 957 | |
Victor Stinner | e0deff3 | 2015-03-24 13:46:18 +0100 | [diff] [blame] | 958 | /* Flush sys.stdout and sys.stderr */ |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 959 | if (flush_std_files() < 0) { |
| 960 | status = -1; |
| 961 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 962 | |
| 963 | /* Disable signal handling */ |
| 964 | PyOS_FiniInterrupts(); |
| 965 | |
| 966 | /* Collect garbage. This may call finalizers; it's nice to call these |
| 967 | * before all modules are destroyed. |
| 968 | * XXX If a __del__ or weakref callback is triggered here, and tries to |
| 969 | * XXX import a module, bad things can happen, because Python no |
| 970 | * XXX longer believes it's initialized. |
| 971 | * XXX Fatal Python error: Interpreter not initialized (version mismatch?) |
| 972 | * XXX is easy to provoke that way. I've also seen, e.g., |
| 973 | * XXX Exception exceptions.ImportError: 'No module named sha' |
| 974 | * XXX in <function callback at 0x008F5718> ignored |
| 975 | * XXX but I'm unclear on exactly how that one happens. In any case, |
| 976 | * XXX I haven't seen a real-life report of either of these. |
| 977 | */ |
Łukasz Langa | fef7e94 | 2016-09-09 21:47:46 -0700 | [diff] [blame] | 978 | _PyGC_CollectIfEnabled(); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 979 | #ifdef COUNT_ALLOCS |
| 980 | /* With COUNT_ALLOCS, it helps to run GC multiple times: |
| 981 | each collection might release some types from the type |
| 982 | list, so they become garbage. */ |
Łukasz Langa | fef7e94 | 2016-09-09 21:47:46 -0700 | [diff] [blame] | 983 | while (_PyGC_CollectIfEnabled() > 0) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 984 | /* nothing */; |
| 985 | #endif |
| 986 | /* Destroy all modules */ |
| 987 | PyImport_Cleanup(); |
| 988 | |
Victor Stinner | e0deff3 | 2015-03-24 13:46:18 +0100 | [diff] [blame] | 989 | /* Flush sys.stdout and sys.stderr (again, in case more was printed) */ |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 990 | if (flush_std_files() < 0) { |
| 991 | status = -1; |
| 992 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 993 | |
| 994 | /* Collect final garbage. This disposes of cycles created by |
| 995 | * class definitions, for example. |
| 996 | * XXX This is disabled because it caused too many problems. If |
| 997 | * XXX a __del__ or weakref callback triggers here, Python code has |
| 998 | * XXX a hard time running, because even the sys module has been |
| 999 | * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc). |
| 1000 | * XXX One symptom is a sequence of information-free messages |
| 1001 | * XXX coming from threads (if a __del__ or callback is invoked, |
| 1002 | * XXX other threads can execute too, and any exception they encounter |
| 1003 | * XXX triggers a comedy of errors as subsystem after subsystem |
| 1004 | * XXX fails to find what it *expects* to find in sys to help report |
| 1005 | * XXX the exception and consequent unexpected failures). I've also |
| 1006 | * XXX seen segfaults then, after adding print statements to the |
| 1007 | * XXX Python code getting called. |
| 1008 | */ |
| 1009 | #if 0 |
Łukasz Langa | fef7e94 | 2016-09-09 21:47:46 -0700 | [diff] [blame] | 1010 | _PyGC_CollectIfEnabled(); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1011 | #endif |
| 1012 | |
| 1013 | /* Disable tracemalloc after all Python objects have been destroyed, |
| 1014 | so it is possible to use tracemalloc in objects destructor. */ |
| 1015 | _PyTraceMalloc_Fini(); |
| 1016 | |
| 1017 | /* Destroy the database used by _PyImport_{Fixup,Find}Extension */ |
| 1018 | _PyImport_Fini(); |
| 1019 | |
| 1020 | /* Cleanup typeobject.c's internal caches. */ |
| 1021 | _PyType_Fini(); |
| 1022 | |
| 1023 | /* unload faulthandler module */ |
| 1024 | _PyFaulthandler_Fini(); |
| 1025 | |
| 1026 | /* Debugging stuff */ |
| 1027 | #ifdef COUNT_ALLOCS |
Serhiy Storchaka | 7e160ce | 2016-07-03 21:03:53 +0300 | [diff] [blame] | 1028 | dump_counts(stderr); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1029 | #endif |
| 1030 | /* dump hash stats */ |
| 1031 | _PyHash_Fini(); |
| 1032 | |
| 1033 | _PY_DEBUG_PRINT_TOTAL_REFS(); |
| 1034 | |
| 1035 | #ifdef Py_TRACE_REFS |
| 1036 | /* Display all objects still alive -- this can invoke arbitrary |
| 1037 | * __repr__ overrides, so requires a mostly-intact interpreter. |
| 1038 | * Alas, a lot of stuff may still be alive now that will be cleaned |
| 1039 | * up later. |
| 1040 | */ |
| 1041 | if (Py_GETENV("PYTHONDUMPREFS")) |
| 1042 | _Py_PrintReferences(stderr); |
| 1043 | #endif /* Py_TRACE_REFS */ |
| 1044 | |
| 1045 | /* Clear interpreter state and all thread states. */ |
| 1046 | PyInterpreterState_Clear(interp); |
| 1047 | |
| 1048 | /* Now we decref the exception classes. After this point nothing |
| 1049 | can raise an exception. That's okay, because each Fini() method |
| 1050 | below has been checked to make sure no exceptions are ever |
| 1051 | raised. |
| 1052 | */ |
| 1053 | |
| 1054 | _PyExc_Fini(); |
| 1055 | |
| 1056 | /* Sundry finalizers */ |
| 1057 | PyMethod_Fini(); |
| 1058 | PyFrame_Fini(); |
| 1059 | PyCFunction_Fini(); |
| 1060 | PyTuple_Fini(); |
| 1061 | PyList_Fini(); |
| 1062 | PySet_Fini(); |
| 1063 | PyBytes_Fini(); |
| 1064 | PyByteArray_Fini(); |
| 1065 | PyLong_Fini(); |
| 1066 | PyFloat_Fini(); |
| 1067 | PyDict_Fini(); |
| 1068 | PySlice_Fini(); |
| 1069 | _PyGC_Fini(); |
Eric Snow | 6b4be19 | 2017-05-22 21:36:03 -0700 | [diff] [blame] | 1070 | _Py_HashRandomization_Fini(); |
Serhiy Storchaka | 9171a8b | 2016-08-14 10:52:18 +0300 | [diff] [blame] | 1071 | _PyArg_Fini(); |
Yury Selivanov | eb63645 | 2016-09-08 22:01:51 -0700 | [diff] [blame] | 1072 | PyAsyncGen_Fini(); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1073 | |
| 1074 | /* Cleanup Unicode implementation */ |
| 1075 | _PyUnicode_Fini(); |
| 1076 | |
| 1077 | /* reset file system default encoding */ |
| 1078 | if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) { |
| 1079 | PyMem_RawFree((char*)Py_FileSystemDefaultEncoding); |
| 1080 | Py_FileSystemDefaultEncoding = NULL; |
| 1081 | } |
| 1082 | |
| 1083 | /* XXX Still allocated: |
| 1084 | - various static ad-hoc pointers to interned strings |
| 1085 | - int and float free list blocks |
| 1086 | - whatever various modules and libraries allocate |
| 1087 | */ |
| 1088 | |
| 1089 | PyGrammar_RemoveAccelerators(&_PyParser_Grammar); |
| 1090 | |
| 1091 | /* Cleanup auto-thread-state */ |
| 1092 | #ifdef WITH_THREAD |
| 1093 | _PyGILState_Fini(); |
| 1094 | #endif /* WITH_THREAD */ |
| 1095 | |
| 1096 | /* Delete current thread. After this, many C API calls become crashy. */ |
| 1097 | PyThreadState_Swap(NULL); |
Victor Stinner | 8a1be61 | 2016-03-14 22:07:55 +0100 | [diff] [blame] | 1098 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1099 | PyInterpreterState_Delete(interp); |
| 1100 | |
| 1101 | #ifdef Py_TRACE_REFS |
| 1102 | /* Display addresses (& refcnts) of all objects still alive. |
| 1103 | * An address can be used to find the repr of the object, printed |
| 1104 | * above by _Py_PrintReferences. |
| 1105 | */ |
| 1106 | if (Py_GETENV("PYTHONDUMPREFS")) |
| 1107 | _Py_PrintReferenceAddresses(stderr); |
| 1108 | #endif /* Py_TRACE_REFS */ |
Victor Stinner | 34be807 | 2016-03-14 12:04:26 +0100 | [diff] [blame] | 1109 | #ifdef WITH_PYMALLOC |
| 1110 | if (_PyMem_PymallocEnabled()) { |
| 1111 | char *opt = Py_GETENV("PYTHONMALLOCSTATS"); |
| 1112 | if (opt != NULL && *opt != '\0') |
| 1113 | _PyObject_DebugMallocStats(stderr); |
| 1114 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1115 | #endif |
| 1116 | |
| 1117 | call_ll_exitfuncs(); |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 1118 | return status; |
| 1119 | } |
| 1120 | |
| 1121 | void |
| 1122 | Py_Finalize(void) |
| 1123 | { |
| 1124 | Py_FinalizeEx(); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1125 | } |
| 1126 | |
| 1127 | /* Create and initialize a new interpreter and thread, and return the |
| 1128 | new thread. This requires that Py_Initialize() has been called |
| 1129 | first. |
| 1130 | |
| 1131 | Unsuccessful initialization yields a NULL pointer. Note that *no* |
| 1132 | exception information is available even in this case -- the |
| 1133 | exception information is held in the thread, and there is no |
| 1134 | thread. |
| 1135 | |
| 1136 | Locking: as above. |
| 1137 | |
| 1138 | */ |
| 1139 | |
| 1140 | PyThreadState * |
| 1141 | Py_NewInterpreter(void) |
| 1142 | { |
| 1143 | PyInterpreterState *interp; |
| 1144 | PyThreadState *tstate, *save_tstate; |
| 1145 | PyObject *bimod, *sysmod; |
| 1146 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 1147 | if (!_Py_Initialized) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1148 | Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); |
| 1149 | |
Victor Stinner | d7292b5 | 2016-06-17 12:29:00 +0200 | [diff] [blame] | 1150 | #ifdef WITH_THREAD |
Victor Stinner | 8a1be61 | 2016-03-14 22:07:55 +0100 | [diff] [blame] | 1151 | /* Issue #10915, #15751: The GIL API doesn't work with multiple |
| 1152 | interpreters: disable PyGILState_Check(). */ |
| 1153 | _PyGILState_check_enabled = 0; |
Berker Peksag | 531396c | 2016-06-17 13:25:01 +0300 | [diff] [blame] | 1154 | #endif |
Victor Stinner | 8a1be61 | 2016-03-14 22:07:55 +0100 | [diff] [blame] | 1155 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1156 | interp = PyInterpreterState_New(); |
| 1157 | if (interp == NULL) |
| 1158 | return NULL; |
| 1159 | |
| 1160 | tstate = PyThreadState_New(interp); |
| 1161 | if (tstate == NULL) { |
| 1162 | PyInterpreterState_Delete(interp); |
| 1163 | return NULL; |
| 1164 | } |
| 1165 | |
| 1166 | save_tstate = PyThreadState_Swap(tstate); |
| 1167 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 1168 | /* Copy the current interpreter config into the new interpreter */ |
| 1169 | if (save_tstate != NULL) { |
| 1170 | interp->core_config = save_tstate->interp->core_config; |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 1171 | interp->config = save_tstate->interp->config; |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 1172 | } else { |
| 1173 | /* No current thread state, copy from the main interpreter */ |
| 1174 | PyInterpreterState *main_interp = PyInterpreterState_Main(); |
| 1175 | interp->core_config = main_interp->core_config; |
Eric Snow | c7ec998 | 2017-05-23 23:00:52 -0700 | [diff] [blame] | 1176 | interp->config = main_interp->config; |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 1177 | } |
| 1178 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1179 | /* XXX The following is lax in error checking */ |
| 1180 | |
| 1181 | interp->modules = PyDict_New(); |
| 1182 | |
| 1183 | bimod = _PyImport_FindBuiltin("builtins"); |
| 1184 | if (bimod != NULL) { |
| 1185 | interp->builtins = PyModule_GetDict(bimod); |
| 1186 | if (interp->builtins == NULL) |
| 1187 | goto handle_error; |
| 1188 | Py_INCREF(interp->builtins); |
| 1189 | } |
| 1190 | |
| 1191 | /* initialize builtin exceptions */ |
| 1192 | _PyExc_Init(bimod); |
| 1193 | |
| 1194 | sysmod = _PyImport_FindBuiltin("sys"); |
| 1195 | if (bimod != NULL && sysmod != NULL) { |
| 1196 | PyObject *pstderr; |
| 1197 | |
| 1198 | interp->sysdict = PyModule_GetDict(sysmod); |
| 1199 | if (interp->sysdict == NULL) |
| 1200 | goto handle_error; |
| 1201 | Py_INCREF(interp->sysdict); |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 1202 | _PySys_EndInit(interp->sysdict); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1203 | PySys_SetPath(Py_GetPath()); |
| 1204 | PyDict_SetItemString(interp->sysdict, "modules", |
| 1205 | interp->modules); |
| 1206 | /* Set up a preliminary stderr printer until we have enough |
| 1207 | infrastructure for the io module in place. */ |
| 1208 | pstderr = PyFile_NewStdPrinter(fileno(stderr)); |
| 1209 | if (pstderr == NULL) |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 1210 | Py_FatalError("Py_NewInterpreter: can't set preliminary stderr"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1211 | _PySys_SetObjectId(&PyId_stderr, pstderr); |
| 1212 | PySys_SetObject("__stderr__", pstderr); |
| 1213 | Py_DECREF(pstderr); |
| 1214 | |
| 1215 | _PyImportHooks_Init(); |
| 1216 | |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 1217 | initimport(interp, sysmod); |
| 1218 | initexternalimport(interp); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1219 | |
| 1220 | if (initfsencoding(interp) < 0) |
| 1221 | goto handle_error; |
| 1222 | |
| 1223 | if (initstdio() < 0) |
| 1224 | Py_FatalError( |
Eric Snow | 1abcf67 | 2017-05-23 21:46:51 -0700 | [diff] [blame] | 1225 | "Py_NewInterpreter: can't initialize sys standard streams"); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1226 | initmain(interp); |
| 1227 | if (!Py_NoSiteFlag) |
| 1228 | initsite(); |
| 1229 | } |
| 1230 | |
| 1231 | if (!PyErr_Occurred()) |
| 1232 | return tstate; |
| 1233 | |
| 1234 | handle_error: |
| 1235 | /* Oops, it didn't work. Undo it all. */ |
| 1236 | |
| 1237 | PyErr_PrintEx(0); |
| 1238 | PyThreadState_Clear(tstate); |
| 1239 | PyThreadState_Swap(save_tstate); |
| 1240 | PyThreadState_Delete(tstate); |
| 1241 | PyInterpreterState_Delete(interp); |
| 1242 | |
| 1243 | return NULL; |
| 1244 | } |
| 1245 | |
| 1246 | /* Delete an interpreter and its last thread. This requires that the |
| 1247 | given thread state is current, that the thread has no remaining |
| 1248 | frames, and that it is its interpreter's only remaining thread. |
| 1249 | It is a fatal error to violate these constraints. |
| 1250 | |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 1251 | (Py_FinalizeEx() doesn't have these constraints -- it zaps |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1252 | everything, regardless.) |
| 1253 | |
| 1254 | Locking: as above. |
| 1255 | |
| 1256 | */ |
| 1257 | |
| 1258 | void |
| 1259 | Py_EndInterpreter(PyThreadState *tstate) |
| 1260 | { |
| 1261 | PyInterpreterState *interp = tstate->interp; |
| 1262 | |
| 1263 | if (tstate != PyThreadState_GET()) |
| 1264 | Py_FatalError("Py_EndInterpreter: thread is not current"); |
| 1265 | if (tstate->frame != NULL) |
| 1266 | Py_FatalError("Py_EndInterpreter: thread still has a frame"); |
| 1267 | |
| 1268 | wait_for_thread_shutdown(); |
| 1269 | |
| 1270 | if (tstate != interp->tstate_head || tstate->next != NULL) |
| 1271 | Py_FatalError("Py_EndInterpreter: not the last thread"); |
| 1272 | |
| 1273 | PyImport_Cleanup(); |
| 1274 | PyInterpreterState_Clear(interp); |
| 1275 | PyThreadState_Swap(NULL); |
| 1276 | PyInterpreterState_Delete(interp); |
| 1277 | } |
| 1278 | |
| 1279 | #ifdef MS_WINDOWS |
| 1280 | static wchar_t *progname = L"python"; |
| 1281 | #else |
| 1282 | static wchar_t *progname = L"python3"; |
| 1283 | #endif |
| 1284 | |
| 1285 | void |
| 1286 | Py_SetProgramName(wchar_t *pn) |
| 1287 | { |
| 1288 | if (pn && *pn) |
| 1289 | progname = pn; |
| 1290 | } |
| 1291 | |
| 1292 | wchar_t * |
| 1293 | Py_GetProgramName(void) |
| 1294 | { |
| 1295 | return progname; |
| 1296 | } |
| 1297 | |
| 1298 | static wchar_t *default_home = NULL; |
| 1299 | static wchar_t env_home[MAXPATHLEN+1]; |
| 1300 | |
| 1301 | void |
| 1302 | Py_SetPythonHome(wchar_t *home) |
| 1303 | { |
| 1304 | default_home = home; |
| 1305 | } |
| 1306 | |
| 1307 | wchar_t * |
| 1308 | Py_GetPythonHome(void) |
| 1309 | { |
| 1310 | wchar_t *home = default_home; |
| 1311 | if (home == NULL && !Py_IgnoreEnvironmentFlag) { |
| 1312 | char* chome = Py_GETENV("PYTHONHOME"); |
| 1313 | if (chome) { |
| 1314 | size_t size = Py_ARRAY_LENGTH(env_home); |
| 1315 | size_t r = mbstowcs(env_home, chome, size); |
| 1316 | if (r != (size_t)-1 && r < size) |
| 1317 | home = env_home; |
| 1318 | } |
| 1319 | |
| 1320 | } |
| 1321 | return home; |
| 1322 | } |
| 1323 | |
| 1324 | /* Create __main__ module */ |
| 1325 | |
| 1326 | static void |
| 1327 | initmain(PyInterpreterState *interp) |
| 1328 | { |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 1329 | PyObject *m, *d, *loader, *ann_dict; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1330 | m = PyImport_AddModule("__main__"); |
| 1331 | if (m == NULL) |
| 1332 | Py_FatalError("can't create __main__ module"); |
| 1333 | d = PyModule_GetDict(m); |
Yury Selivanov | f8cb8a1 | 2016-09-08 20:50:03 -0700 | [diff] [blame] | 1334 | ann_dict = PyDict_New(); |
| 1335 | if ((ann_dict == NULL) || |
| 1336 | (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) { |
| 1337 | Py_FatalError("Failed to initialize __main__.__annotations__"); |
| 1338 | } |
| 1339 | Py_DECREF(ann_dict); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1340 | if (PyDict_GetItemString(d, "__builtins__") == NULL) { |
| 1341 | PyObject *bimod = PyImport_ImportModule("builtins"); |
| 1342 | if (bimod == NULL) { |
| 1343 | Py_FatalError("Failed to retrieve builtins module"); |
| 1344 | } |
| 1345 | if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) { |
| 1346 | Py_FatalError("Failed to initialize __main__.__builtins__"); |
| 1347 | } |
| 1348 | Py_DECREF(bimod); |
| 1349 | } |
| 1350 | /* Main is a little special - imp.is_builtin("__main__") will return |
| 1351 | * False, but BuiltinImporter is still the most appropriate initial |
| 1352 | * setting for its __loader__ attribute. A more suitable value will |
| 1353 | * be set if __main__ gets further initialized later in the startup |
| 1354 | * process. |
| 1355 | */ |
| 1356 | loader = PyDict_GetItemString(d, "__loader__"); |
| 1357 | if (loader == NULL || loader == Py_None) { |
| 1358 | PyObject *loader = PyObject_GetAttrString(interp->importlib, |
| 1359 | "BuiltinImporter"); |
| 1360 | if (loader == NULL) { |
| 1361 | Py_FatalError("Failed to retrieve BuiltinImporter"); |
| 1362 | } |
| 1363 | if (PyDict_SetItemString(d, "__loader__", loader) < 0) { |
| 1364 | Py_FatalError("Failed to initialize __main__.__loader__"); |
| 1365 | } |
| 1366 | Py_DECREF(loader); |
| 1367 | } |
| 1368 | } |
| 1369 | |
| 1370 | static int |
| 1371 | initfsencoding(PyInterpreterState *interp) |
| 1372 | { |
| 1373 | PyObject *codec; |
| 1374 | |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 1375 | #ifdef MS_WINDOWS |
| 1376 | if (Py_LegacyWindowsFSEncodingFlag) |
| 1377 | { |
| 1378 | Py_FileSystemDefaultEncoding = "mbcs"; |
| 1379 | Py_FileSystemDefaultEncodeErrors = "replace"; |
| 1380 | } |
| 1381 | else |
| 1382 | { |
| 1383 | Py_FileSystemDefaultEncoding = "utf-8"; |
| 1384 | Py_FileSystemDefaultEncodeErrors = "surrogatepass"; |
| 1385 | } |
| 1386 | #else |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1387 | if (Py_FileSystemDefaultEncoding == NULL) |
| 1388 | { |
| 1389 | Py_FileSystemDefaultEncoding = get_locale_encoding(); |
| 1390 | if (Py_FileSystemDefaultEncoding == NULL) |
| 1391 | Py_FatalError("Py_Initialize: Unable to get the locale encoding"); |
| 1392 | |
| 1393 | Py_HasFileSystemDefaultEncoding = 0; |
| 1394 | interp->fscodec_initialized = 1; |
| 1395 | return 0; |
| 1396 | } |
Steve Dower | cc16be8 | 2016-09-08 10:35:16 -0700 | [diff] [blame] | 1397 | #endif |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1398 | |
| 1399 | /* the encoding is mbcs, utf-8 or ascii */ |
| 1400 | codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding); |
| 1401 | if (!codec) { |
| 1402 | /* Such error can only occurs in critical situations: no more |
| 1403 | * memory, import a module of the standard library failed, |
| 1404 | * etc. */ |
| 1405 | return -1; |
| 1406 | } |
| 1407 | Py_DECREF(codec); |
| 1408 | interp->fscodec_initialized = 1; |
| 1409 | return 0; |
| 1410 | } |
| 1411 | |
| 1412 | /* Import the site module (not into __main__ though) */ |
| 1413 | |
| 1414 | static void |
| 1415 | initsite(void) |
| 1416 | { |
| 1417 | PyObject *m; |
| 1418 | m = PyImport_ImportModule("site"); |
| 1419 | if (m == NULL) { |
| 1420 | fprintf(stderr, "Failed to import the site module\n"); |
| 1421 | PyErr_Print(); |
| 1422 | Py_Finalize(); |
| 1423 | exit(1); |
| 1424 | } |
| 1425 | else { |
| 1426 | Py_DECREF(m); |
| 1427 | } |
| 1428 | } |
| 1429 | |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1430 | /* Check if a file descriptor is valid or not. |
| 1431 | Return 0 if the file descriptor is invalid, return non-zero otherwise. */ |
| 1432 | static int |
| 1433 | is_valid_fd(int fd) |
| 1434 | { |
Victor Stinner | 1c4670e | 2017-05-04 00:45:56 +0200 | [diff] [blame] | 1435 | #ifdef __APPLE__ |
| 1436 | /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe |
| 1437 | and the other side of the pipe is closed, dup(1) succeed, whereas |
| 1438 | fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect |
| 1439 | such error. */ |
| 1440 | struct stat st; |
| 1441 | return (fstat(fd, &st) == 0); |
| 1442 | #else |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1443 | int fd2; |
Steve Dower | 940f33a | 2016-09-08 11:21:54 -0700 | [diff] [blame] | 1444 | if (fd < 0) |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1445 | return 0; |
| 1446 | _Py_BEGIN_SUPPRESS_IPH |
Victor Stinner | 449b271 | 2015-09-29 13:59:50 +0200 | [diff] [blame] | 1447 | /* Prefer dup() over fstat(). fstat() can require input/output whereas |
| 1448 | dup() doesn't, there is a low risk of EMFILE/ENFILE at Python |
| 1449 | startup. */ |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1450 | fd2 = dup(fd); |
| 1451 | if (fd2 >= 0) |
| 1452 | close(fd2); |
| 1453 | _Py_END_SUPPRESS_IPH |
| 1454 | return fd2 >= 0; |
Victor Stinner | 1c4670e | 2017-05-04 00:45:56 +0200 | [diff] [blame] | 1455 | #endif |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1456 | } |
| 1457 | |
| 1458 | /* returns Py_None if the fd is not valid */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1459 | static PyObject* |
| 1460 | create_stdio(PyObject* io, |
Serhiy Storchaka | ef1585e | 2015-12-25 20:01:53 +0200 | [diff] [blame] | 1461 | int fd, int write_mode, const char* name, |
| 1462 | const char* encoding, const char* errors) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1463 | { |
| 1464 | PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res; |
| 1465 | const char* mode; |
| 1466 | const char* newline; |
| 1467 | PyObject *line_buffering; |
| 1468 | int buffering, isatty; |
| 1469 | _Py_IDENTIFIER(open); |
| 1470 | _Py_IDENTIFIER(isatty); |
| 1471 | _Py_IDENTIFIER(TextIOWrapper); |
| 1472 | _Py_IDENTIFIER(mode); |
| 1473 | |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1474 | if (!is_valid_fd(fd)) |
| 1475 | Py_RETURN_NONE; |
| 1476 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1477 | /* stdin is always opened in buffered mode, first because it shouldn't |
| 1478 | make a difference in common use cases, second because TextIOWrapper |
| 1479 | depends on the presence of a read1() method which only exists on |
| 1480 | buffered streams. |
| 1481 | */ |
| 1482 | if (Py_UnbufferedStdioFlag && write_mode) |
| 1483 | buffering = 0; |
| 1484 | else |
| 1485 | buffering = -1; |
| 1486 | if (write_mode) |
| 1487 | mode = "wb"; |
| 1488 | else |
| 1489 | mode = "rb"; |
| 1490 | buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi", |
| 1491 | fd, mode, buffering, |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 1492 | Py_None, Py_None, /* encoding, errors */ |
| 1493 | Py_None, 0); /* newline, closefd */ |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1494 | if (buf == NULL) |
| 1495 | goto error; |
| 1496 | |
| 1497 | if (buffering) { |
| 1498 | _Py_IDENTIFIER(raw); |
| 1499 | raw = _PyObject_GetAttrId(buf, &PyId_raw); |
| 1500 | if (raw == NULL) |
| 1501 | goto error; |
| 1502 | } |
| 1503 | else { |
| 1504 | raw = buf; |
| 1505 | Py_INCREF(raw); |
| 1506 | } |
| 1507 | |
Steve Dower | 3929499 | 2016-08-30 21:22:36 -0700 | [diff] [blame] | 1508 | #ifdef MS_WINDOWS |
| 1509 | /* Windows console IO is always UTF-8 encoded */ |
| 1510 | if (PyWindowsConsoleIO_Check(raw)) |
| 1511 | encoding = "utf-8"; |
| 1512 | #endif |
| 1513 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1514 | text = PyUnicode_FromString(name); |
| 1515 | if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0) |
| 1516 | goto error; |
Victor Stinner | 3466bde | 2016-09-05 18:16:01 -0700 | [diff] [blame] | 1517 | res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1518 | if (res == NULL) |
| 1519 | goto error; |
| 1520 | isatty = PyObject_IsTrue(res); |
| 1521 | Py_DECREF(res); |
| 1522 | if (isatty == -1) |
| 1523 | goto error; |
| 1524 | if (isatty || Py_UnbufferedStdioFlag) |
| 1525 | line_buffering = Py_True; |
| 1526 | else |
| 1527 | line_buffering = Py_False; |
| 1528 | |
| 1529 | Py_CLEAR(raw); |
| 1530 | Py_CLEAR(text); |
| 1531 | |
| 1532 | #ifdef MS_WINDOWS |
| 1533 | /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r" |
| 1534 | newlines to "\n". |
| 1535 | sys.stdout and sys.stderr: translate "\n" to "\r\n". */ |
| 1536 | newline = NULL; |
| 1537 | #else |
| 1538 | /* sys.stdin: split lines at "\n". |
| 1539 | sys.stdout and sys.stderr: don't translate newlines (use "\n"). */ |
| 1540 | newline = "\n"; |
| 1541 | #endif |
| 1542 | |
| 1543 | stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO", |
| 1544 | buf, encoding, errors, |
| 1545 | newline, line_buffering); |
| 1546 | Py_CLEAR(buf); |
| 1547 | if (stream == NULL) |
| 1548 | goto error; |
| 1549 | |
| 1550 | if (write_mode) |
| 1551 | mode = "w"; |
| 1552 | else |
| 1553 | mode = "r"; |
| 1554 | text = PyUnicode_FromString(mode); |
| 1555 | if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0) |
| 1556 | goto error; |
| 1557 | Py_CLEAR(text); |
| 1558 | return stream; |
| 1559 | |
| 1560 | error: |
| 1561 | Py_XDECREF(buf); |
| 1562 | Py_XDECREF(stream); |
| 1563 | Py_XDECREF(text); |
| 1564 | Py_XDECREF(raw); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1565 | |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1566 | if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) { |
| 1567 | /* Issue #24891: the file descriptor was closed after the first |
| 1568 | is_valid_fd() check was called. Ignore the OSError and set the |
| 1569 | stream to None. */ |
| 1570 | PyErr_Clear(); |
| 1571 | Py_RETURN_NONE; |
| 1572 | } |
| 1573 | return NULL; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1574 | } |
| 1575 | |
| 1576 | /* Initialize sys.stdin, stdout, stderr and builtins.open */ |
| 1577 | static int |
| 1578 | initstdio(void) |
| 1579 | { |
| 1580 | PyObject *iomod = NULL, *wrapper; |
| 1581 | PyObject *bimod = NULL; |
| 1582 | PyObject *m; |
| 1583 | PyObject *std = NULL; |
| 1584 | int status = 0, fd; |
| 1585 | PyObject * encoding_attr; |
| 1586 | char *pythonioencoding = NULL, *encoding, *errors; |
| 1587 | |
| 1588 | /* Hack to avoid a nasty recursion issue when Python is invoked |
| 1589 | in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ |
| 1590 | if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { |
| 1591 | goto error; |
| 1592 | } |
| 1593 | Py_DECREF(m); |
| 1594 | |
| 1595 | if (!(m = PyImport_ImportModule("encodings.latin_1"))) { |
| 1596 | goto error; |
| 1597 | } |
| 1598 | Py_DECREF(m); |
| 1599 | |
| 1600 | if (!(bimod = PyImport_ImportModule("builtins"))) { |
| 1601 | goto error; |
| 1602 | } |
| 1603 | |
| 1604 | if (!(iomod = PyImport_ImportModule("io"))) { |
| 1605 | goto error; |
| 1606 | } |
| 1607 | if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { |
| 1608 | goto error; |
| 1609 | } |
| 1610 | |
| 1611 | /* Set builtins.open */ |
| 1612 | if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { |
| 1613 | Py_DECREF(wrapper); |
| 1614 | goto error; |
| 1615 | } |
| 1616 | Py_DECREF(wrapper); |
| 1617 | |
| 1618 | encoding = _Py_StandardStreamEncoding; |
| 1619 | errors = _Py_StandardStreamErrors; |
| 1620 | if (!encoding || !errors) { |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1621 | pythonioencoding = Py_GETENV("PYTHONIOENCODING"); |
| 1622 | if (pythonioencoding) { |
| 1623 | char *err; |
| 1624 | pythonioencoding = _PyMem_Strdup(pythonioencoding); |
| 1625 | if (pythonioencoding == NULL) { |
| 1626 | PyErr_NoMemory(); |
| 1627 | goto error; |
| 1628 | } |
| 1629 | err = strchr(pythonioencoding, ':'); |
| 1630 | if (err) { |
| 1631 | *err = '\0'; |
| 1632 | err++; |
Serhiy Storchaka | fc43511 | 2016-04-10 14:34:13 +0300 | [diff] [blame] | 1633 | if (*err && !errors) { |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1634 | errors = err; |
| 1635 | } |
| 1636 | } |
| 1637 | if (*pythonioencoding && !encoding) { |
| 1638 | encoding = pythonioencoding; |
| 1639 | } |
| 1640 | } |
Serhiy Storchaka | fc43511 | 2016-04-10 14:34:13 +0300 | [diff] [blame] | 1641 | if (!errors && !(pythonioencoding && *pythonioencoding)) { |
Nick Coghlan | 6ea4186 | 2017-06-11 13:16:15 +1000 | [diff] [blame] | 1642 | /* Choose the default error handler based on the current locale */ |
| 1643 | errors = get_default_standard_stream_error_handler(); |
Serhiy Storchaka | fc43511 | 2016-04-10 14:34:13 +0300 | [diff] [blame] | 1644 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1645 | } |
| 1646 | |
| 1647 | /* Set sys.stdin */ |
| 1648 | fd = fileno(stdin); |
| 1649 | /* Under some conditions stdin, stdout and stderr may not be connected |
| 1650 | * and fileno() may point to an invalid file descriptor. For example |
| 1651 | * GUI apps don't have valid standard streams by default. |
| 1652 | */ |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1653 | std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors); |
| 1654 | if (std == NULL) |
| 1655 | goto error; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1656 | PySys_SetObject("__stdin__", std); |
| 1657 | _PySys_SetObjectId(&PyId_stdin, std); |
| 1658 | Py_DECREF(std); |
| 1659 | |
| 1660 | /* Set sys.stdout */ |
| 1661 | fd = fileno(stdout); |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1662 | std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors); |
| 1663 | if (std == NULL) |
| 1664 | goto error; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1665 | PySys_SetObject("__stdout__", std); |
| 1666 | _PySys_SetObjectId(&PyId_stdout, std); |
| 1667 | Py_DECREF(std); |
| 1668 | |
| 1669 | #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ |
| 1670 | /* Set sys.stderr, replaces the preliminary stderr */ |
| 1671 | fd = fileno(stderr); |
Victor Stinner | 874dbe8 | 2015-09-04 17:29:57 +0200 | [diff] [blame] | 1672 | std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace"); |
| 1673 | if (std == NULL) |
| 1674 | goto error; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1675 | |
| 1676 | /* Same as hack above, pre-import stderr's codec to avoid recursion |
| 1677 | when import.c tries to write to stderr in verbose mode. */ |
| 1678 | encoding_attr = PyObject_GetAttrString(std, "encoding"); |
| 1679 | if (encoding_attr != NULL) { |
Serhiy Storchaka | 85b0f5b | 2016-11-20 10:16:47 +0200 | [diff] [blame] | 1680 | const char *std_encoding = PyUnicode_AsUTF8(encoding_attr); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1681 | if (std_encoding != NULL) { |
| 1682 | PyObject *codec_info = _PyCodec_Lookup(std_encoding); |
| 1683 | Py_XDECREF(codec_info); |
| 1684 | } |
| 1685 | Py_DECREF(encoding_attr); |
| 1686 | } |
| 1687 | PyErr_Clear(); /* Not a fatal error if codec isn't available */ |
| 1688 | |
| 1689 | if (PySys_SetObject("__stderr__", std) < 0) { |
| 1690 | Py_DECREF(std); |
| 1691 | goto error; |
| 1692 | } |
| 1693 | if (_PySys_SetObjectId(&PyId_stderr, std) < 0) { |
| 1694 | Py_DECREF(std); |
| 1695 | goto error; |
| 1696 | } |
| 1697 | Py_DECREF(std); |
| 1698 | #endif |
| 1699 | |
| 1700 | if (0) { |
| 1701 | error: |
| 1702 | status = -1; |
| 1703 | } |
| 1704 | |
| 1705 | /* We won't need them anymore. */ |
| 1706 | if (_Py_StandardStreamEncoding) { |
| 1707 | PyMem_RawFree(_Py_StandardStreamEncoding); |
| 1708 | _Py_StandardStreamEncoding = NULL; |
| 1709 | } |
| 1710 | if (_Py_StandardStreamErrors) { |
| 1711 | PyMem_RawFree(_Py_StandardStreamErrors); |
| 1712 | _Py_StandardStreamErrors = NULL; |
| 1713 | } |
| 1714 | PyMem_Free(pythonioencoding); |
| 1715 | Py_XDECREF(bimod); |
| 1716 | Py_XDECREF(iomod); |
| 1717 | return status; |
| 1718 | } |
| 1719 | |
| 1720 | |
Victor Stinner | 10dc484 | 2015-03-24 12:01:30 +0100 | [diff] [blame] | 1721 | static void |
Victor Stinner | 791da1c | 2016-03-14 16:53:12 +0100 | [diff] [blame] | 1722 | _Py_FatalError_DumpTracebacks(int fd) |
Victor Stinner | 10dc484 | 2015-03-24 12:01:30 +0100 | [diff] [blame] | 1723 | { |
Victor Stinner | 10dc484 | 2015-03-24 12:01:30 +0100 | [diff] [blame] | 1724 | fputc('\n', stderr); |
| 1725 | fflush(stderr); |
| 1726 | |
| 1727 | /* display the current Python stack */ |
Victor Stinner | 861d9ab | 2016-03-16 22:45:24 +0100 | [diff] [blame] | 1728 | _Py_DumpTracebackThreads(fd, NULL, NULL); |
Victor Stinner | 10dc484 | 2015-03-24 12:01:30 +0100 | [diff] [blame] | 1729 | } |
Victor Stinner | 791da1c | 2016-03-14 16:53:12 +0100 | [diff] [blame] | 1730 | |
| 1731 | /* Print the current exception (if an exception is set) with its traceback, |
| 1732 | or display the current Python stack. |
| 1733 | |
| 1734 | Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is |
| 1735 | called on catastrophic cases. |
| 1736 | |
| 1737 | Return 1 if the traceback was displayed, 0 otherwise. */ |
| 1738 | |
| 1739 | static int |
| 1740 | _Py_FatalError_PrintExc(int fd) |
| 1741 | { |
| 1742 | PyObject *ferr, *res; |
| 1743 | PyObject *exception, *v, *tb; |
| 1744 | int has_tb; |
| 1745 | |
| 1746 | if (PyThreadState_GET() == NULL) { |
| 1747 | /* The GIL is released: trying to acquire it is likely to deadlock, |
| 1748 | just give up. */ |
| 1749 | return 0; |
| 1750 | } |
| 1751 | |
| 1752 | PyErr_Fetch(&exception, &v, &tb); |
| 1753 | if (exception == NULL) { |
| 1754 | /* No current exception */ |
| 1755 | return 0; |
| 1756 | } |
| 1757 | |
| 1758 | ferr = _PySys_GetObjectId(&PyId_stderr); |
| 1759 | if (ferr == NULL || ferr == Py_None) { |
| 1760 | /* sys.stderr is not set yet or set to None, |
| 1761 | no need to try to display the exception */ |
| 1762 | return 0; |
| 1763 | } |
| 1764 | |
| 1765 | PyErr_NormalizeException(&exception, &v, &tb); |
| 1766 | if (tb == NULL) { |
| 1767 | tb = Py_None; |
| 1768 | Py_INCREF(tb); |
| 1769 | } |
| 1770 | PyException_SetTraceback(v, tb); |
| 1771 | if (exception == NULL) { |
| 1772 | /* PyErr_NormalizeException() failed */ |
| 1773 | return 0; |
| 1774 | } |
| 1775 | |
| 1776 | has_tb = (tb != Py_None); |
| 1777 | PyErr_Display(exception, v, tb); |
| 1778 | Py_XDECREF(exception); |
| 1779 | Py_XDECREF(v); |
| 1780 | Py_XDECREF(tb); |
| 1781 | |
| 1782 | /* sys.stderr may be buffered: call sys.stderr.flush() */ |
Victor Stinner | 3466bde | 2016-09-05 18:16:01 -0700 | [diff] [blame] | 1783 | res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL); |
Victor Stinner | 791da1c | 2016-03-14 16:53:12 +0100 | [diff] [blame] | 1784 | if (res == NULL) |
| 1785 | PyErr_Clear(); |
| 1786 | else |
| 1787 | Py_DECREF(res); |
| 1788 | |
| 1789 | return has_tb; |
| 1790 | } |
| 1791 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1792 | /* Print fatal error message and abort */ |
| 1793 | |
| 1794 | void |
| 1795 | Py_FatalError(const char *msg) |
| 1796 | { |
| 1797 | const int fd = fileno(stderr); |
Victor Stinner | 53345a4 | 2015-03-25 01:55:14 +0100 | [diff] [blame] | 1798 | static int reentrant = 0; |
| 1799 | #ifdef MS_WINDOWS |
| 1800 | size_t len; |
| 1801 | WCHAR* buffer; |
| 1802 | size_t i; |
| 1803 | #endif |
| 1804 | |
| 1805 | if (reentrant) { |
| 1806 | /* Py_FatalError() caused a second fatal error. |
| 1807 | Example: flush_std_files() raises a recursion error. */ |
| 1808 | goto exit; |
| 1809 | } |
| 1810 | reentrant = 1; |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1811 | |
| 1812 | fprintf(stderr, "Fatal Python error: %s\n", msg); |
| 1813 | fflush(stderr); /* it helps in Windows debug build */ |
Victor Stinner | 10dc484 | 2015-03-24 12:01:30 +0100 | [diff] [blame] | 1814 | |
Victor Stinner | e0deff3 | 2015-03-24 13:46:18 +0100 | [diff] [blame] | 1815 | /* Print the exception (if an exception is set) with its traceback, |
| 1816 | * or display the current Python stack. */ |
Victor Stinner | 791da1c | 2016-03-14 16:53:12 +0100 | [diff] [blame] | 1817 | if (!_Py_FatalError_PrintExc(fd)) |
| 1818 | _Py_FatalError_DumpTracebacks(fd); |
Victor Stinner | 10dc484 | 2015-03-24 12:01:30 +0100 | [diff] [blame] | 1819 | |
Victor Stinner | 2025d78 | 2016-03-16 23:19:15 +0100 | [diff] [blame] | 1820 | /* The main purpose of faulthandler is to display the traceback. We already |
| 1821 | * did our best to display it. So faulthandler can now be disabled. |
| 1822 | * (Don't trigger it on abort().) */ |
| 1823 | _PyFaulthandler_Fini(); |
| 1824 | |
Victor Stinner | 791da1c | 2016-03-14 16:53:12 +0100 | [diff] [blame] | 1825 | /* Check if the current Python thread hold the GIL */ |
| 1826 | if (PyThreadState_GET() != NULL) { |
| 1827 | /* Flush sys.stdout and sys.stderr */ |
| 1828 | flush_std_files(); |
| 1829 | } |
Victor Stinner | e0deff3 | 2015-03-24 13:46:18 +0100 | [diff] [blame] | 1830 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1831 | #ifdef MS_WINDOWS |
Victor Stinner | 53345a4 | 2015-03-25 01:55:14 +0100 | [diff] [blame] | 1832 | len = strlen(msg); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1833 | |
Victor Stinner | 53345a4 | 2015-03-25 01:55:14 +0100 | [diff] [blame] | 1834 | /* Convert the message to wchar_t. This uses a simple one-to-one |
| 1835 | conversion, assuming that the this error message actually uses ASCII |
| 1836 | only. If this ceases to be true, we will have to convert. */ |
| 1837 | buffer = alloca( (len+1) * (sizeof *buffer)); |
| 1838 | for( i=0; i<=len; ++i) |
| 1839 | buffer[i] = msg[i]; |
| 1840 | OutputDebugStringW(L"Fatal Python error: "); |
| 1841 | OutputDebugStringW(buffer); |
| 1842 | OutputDebugStringW(L"\n"); |
| 1843 | #endif /* MS_WINDOWS */ |
| 1844 | |
| 1845 | exit: |
| 1846 | #if defined(MS_WINDOWS) && defined(_DEBUG) |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1847 | DebugBreak(); |
| 1848 | #endif |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1849 | abort(); |
| 1850 | } |
| 1851 | |
| 1852 | /* Clean up and exit */ |
| 1853 | |
| 1854 | #ifdef WITH_THREAD |
Victor Stinner | d7292b5 | 2016-06-17 12:29:00 +0200 | [diff] [blame] | 1855 | # include "pythread.h" |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1856 | #endif |
| 1857 | |
| 1858 | static void (*pyexitfunc)(void) = NULL; |
| 1859 | /* For the atexit module. */ |
| 1860 | void _Py_PyAtExit(void (*func)(void)) |
| 1861 | { |
| 1862 | pyexitfunc = func; |
| 1863 | } |
| 1864 | |
| 1865 | static void |
| 1866 | call_py_exitfuncs(void) |
| 1867 | { |
| 1868 | if (pyexitfunc == NULL) |
| 1869 | return; |
| 1870 | |
| 1871 | (*pyexitfunc)(); |
| 1872 | PyErr_Clear(); |
| 1873 | } |
| 1874 | |
| 1875 | /* Wait until threading._shutdown completes, provided |
| 1876 | the threading module was imported in the first place. |
| 1877 | The shutdown routine will wait until all non-daemon |
| 1878 | "threading" threads have completed. */ |
| 1879 | static void |
| 1880 | wait_for_thread_shutdown(void) |
| 1881 | { |
| 1882 | #ifdef WITH_THREAD |
| 1883 | _Py_IDENTIFIER(_shutdown); |
| 1884 | PyObject *result; |
| 1885 | PyThreadState *tstate = PyThreadState_GET(); |
| 1886 | PyObject *threading = PyMapping_GetItemString(tstate->interp->modules, |
| 1887 | "threading"); |
| 1888 | if (threading == NULL) { |
| 1889 | /* threading not imported */ |
| 1890 | PyErr_Clear(); |
| 1891 | return; |
| 1892 | } |
Victor Stinner | 3466bde | 2016-09-05 18:16:01 -0700 | [diff] [blame] | 1893 | result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL); |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1894 | if (result == NULL) { |
| 1895 | PyErr_WriteUnraisable(threading); |
| 1896 | } |
| 1897 | else { |
| 1898 | Py_DECREF(result); |
| 1899 | } |
| 1900 | Py_DECREF(threading); |
| 1901 | #endif |
| 1902 | } |
| 1903 | |
| 1904 | #define NEXITFUNCS 32 |
| 1905 | static void (*exitfuncs[NEXITFUNCS])(void); |
| 1906 | static int nexitfuncs = 0; |
| 1907 | |
| 1908 | int Py_AtExit(void (*func)(void)) |
| 1909 | { |
| 1910 | if (nexitfuncs >= NEXITFUNCS) |
| 1911 | return -1; |
| 1912 | exitfuncs[nexitfuncs++] = func; |
| 1913 | return 0; |
| 1914 | } |
| 1915 | |
| 1916 | static void |
| 1917 | call_ll_exitfuncs(void) |
| 1918 | { |
| 1919 | while (nexitfuncs > 0) |
| 1920 | (*exitfuncs[--nexitfuncs])(); |
| 1921 | |
| 1922 | fflush(stdout); |
| 1923 | fflush(stderr); |
| 1924 | } |
| 1925 | |
| 1926 | void |
| 1927 | Py_Exit(int sts) |
| 1928 | { |
Martin Panter | b4ce1fc | 2015-11-30 03:18:29 +0000 | [diff] [blame] | 1929 | if (Py_FinalizeEx() < 0) { |
| 1930 | sts = 120; |
| 1931 | } |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1932 | |
| 1933 | exit(sts); |
| 1934 | } |
| 1935 | |
| 1936 | static void |
| 1937 | initsigs(void) |
| 1938 | { |
| 1939 | #ifdef SIGPIPE |
| 1940 | PyOS_setsig(SIGPIPE, SIG_IGN); |
| 1941 | #endif |
| 1942 | #ifdef SIGXFZ |
| 1943 | PyOS_setsig(SIGXFZ, SIG_IGN); |
| 1944 | #endif |
| 1945 | #ifdef SIGXFSZ |
| 1946 | PyOS_setsig(SIGXFSZ, SIG_IGN); |
| 1947 | #endif |
| 1948 | PyOS_InitInterrupts(); /* May imply initsignal() */ |
| 1949 | if (PyErr_Occurred()) { |
| 1950 | Py_FatalError("Py_Initialize: can't import signal"); |
| 1951 | } |
| 1952 | } |
| 1953 | |
| 1954 | |
| 1955 | /* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL. |
| 1956 | * |
| 1957 | * All of the code in this function must only use async-signal-safe functions, |
| 1958 | * listed at `man 7 signal` or |
| 1959 | * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html. |
| 1960 | */ |
| 1961 | void |
| 1962 | _Py_RestoreSignals(void) |
| 1963 | { |
| 1964 | #ifdef SIGPIPE |
| 1965 | PyOS_setsig(SIGPIPE, SIG_DFL); |
| 1966 | #endif |
| 1967 | #ifdef SIGXFZ |
| 1968 | PyOS_setsig(SIGXFZ, SIG_DFL); |
| 1969 | #endif |
| 1970 | #ifdef SIGXFSZ |
| 1971 | PyOS_setsig(SIGXFSZ, SIG_DFL); |
| 1972 | #endif |
| 1973 | } |
| 1974 | |
| 1975 | |
| 1976 | /* |
| 1977 | * The file descriptor fd is considered ``interactive'' if either |
| 1978 | * a) isatty(fd) is TRUE, or |
| 1979 | * b) the -i flag was given, and the filename associated with |
| 1980 | * the descriptor is NULL or "<stdin>" or "???". |
| 1981 | */ |
| 1982 | int |
| 1983 | Py_FdIsInteractive(FILE *fp, const char *filename) |
| 1984 | { |
| 1985 | if (isatty((int)fileno(fp))) |
| 1986 | return 1; |
| 1987 | if (!Py_InteractiveFlag) |
| 1988 | return 0; |
| 1989 | return (filename == NULL) || |
| 1990 | (strcmp(filename, "<stdin>") == 0) || |
| 1991 | (strcmp(filename, "???") == 0); |
| 1992 | } |
| 1993 | |
| 1994 | |
Nick Coghlan | d600951 | 2014-11-20 21:39:37 +1000 | [diff] [blame] | 1995 | /* Wrappers around sigaction() or signal(). */ |
| 1996 | |
| 1997 | PyOS_sighandler_t |
| 1998 | PyOS_getsig(int sig) |
| 1999 | { |
| 2000 | #ifdef HAVE_SIGACTION |
| 2001 | struct sigaction context; |
| 2002 | if (sigaction(sig, NULL, &context) == -1) |
| 2003 | return SIG_ERR; |
| 2004 | return context.sa_handler; |
| 2005 | #else |
| 2006 | PyOS_sighandler_t handler; |
| 2007 | /* Special signal handling for the secure CRT in Visual Studio 2005 */ |
| 2008 | #if defined(_MSC_VER) && _MSC_VER >= 1400 |
| 2009 | switch (sig) { |
| 2010 | /* Only these signals are valid */ |
| 2011 | case SIGINT: |
| 2012 | case SIGILL: |
| 2013 | case SIGFPE: |
| 2014 | case SIGSEGV: |
| 2015 | case SIGTERM: |
| 2016 | case SIGBREAK: |
| 2017 | case SIGABRT: |
| 2018 | break; |
| 2019 | /* Don't call signal() with other values or it will assert */ |
| 2020 | default: |
| 2021 | return SIG_ERR; |
| 2022 | } |
| 2023 | #endif /* _MSC_VER && _MSC_VER >= 1400 */ |
| 2024 | handler = signal(sig, SIG_IGN); |
| 2025 | if (handler != SIG_ERR) |
| 2026 | signal(sig, handler); |
| 2027 | return handler; |
| 2028 | #endif |
| 2029 | } |
| 2030 | |
| 2031 | /* |
| 2032 | * All of the code in this function must only use async-signal-safe functions, |
| 2033 | * listed at `man 7 signal` or |
| 2034 | * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html. |
| 2035 | */ |
| 2036 | PyOS_sighandler_t |
| 2037 | PyOS_setsig(int sig, PyOS_sighandler_t handler) |
| 2038 | { |
| 2039 | #ifdef HAVE_SIGACTION |
| 2040 | /* Some code in Modules/signalmodule.c depends on sigaction() being |
| 2041 | * used here if HAVE_SIGACTION is defined. Fix that if this code |
| 2042 | * changes to invalidate that assumption. |
| 2043 | */ |
| 2044 | struct sigaction context, ocontext; |
| 2045 | context.sa_handler = handler; |
| 2046 | sigemptyset(&context.sa_mask); |
| 2047 | context.sa_flags = 0; |
| 2048 | if (sigaction(sig, &context, &ocontext) == -1) |
| 2049 | return SIG_ERR; |
| 2050 | return ocontext.sa_handler; |
| 2051 | #else |
| 2052 | PyOS_sighandler_t oldhandler; |
| 2053 | oldhandler = signal(sig, handler); |
| 2054 | #ifdef HAVE_SIGINTERRUPT |
| 2055 | siginterrupt(sig, 1); |
| 2056 | #endif |
| 2057 | return oldhandler; |
| 2058 | #endif |
| 2059 | } |
| 2060 | |
| 2061 | #ifdef __cplusplus |
| 2062 | } |
| 2063 | #endif |