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