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