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