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