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