blob: 048c2b283d48b463558de875d1809c4d53c31922 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* 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 Dower39294992016-08-30 21:22:36 -070034
35extern PyTypeObject PyWindowsConsoleIO_Type;
36#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100037#endif
38
39_Py_IDENTIFIER(flush);
40_Py_IDENTIFIER(name);
41_Py_IDENTIFIER(stdin);
42_Py_IDENTIFIER(stdout);
43_Py_IDENTIFIER(stderr);
44
45#ifdef __cplusplus
46extern "C" {
47#endif
48
49extern wchar_t *Py_GetPath(void);
50
51extern grammar _PyParser_Grammar; /* From graminit.c */
52
53/* Forward */
54static void initmain(PyInterpreterState *interp);
55static int initfsencoding(PyInterpreterState *interp);
56static void initsite(void);
57static int initstdio(void);
58static void initsigs(void);
59static void call_py_exitfuncs(void);
60static void wait_for_thread_shutdown(void);
61static void call_ll_exitfuncs(void);
62extern int _PyUnicode_Init(void);
63extern int _PyStructSequence_Init(void);
64extern void _PyUnicode_Fini(void);
65extern int _PyLong_Init(void);
66extern void PyLong_Fini(void);
67extern int _PyFaulthandler_Init(void);
68extern void _PyFaulthandler_Fini(void);
69extern void _PyHash_Fini(void);
70extern int _PyTraceMalloc_Init(void);
71extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070072extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100073
74#ifdef WITH_THREAD
75extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
77#endif /* WITH_THREAD */
78
79/* Global configuration variable declarations are in pydebug.h */
80/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
81int Py_DebugFlag; /* Needed by parser.c */
82int Py_VerboseFlag; /* Needed by import.c */
83int Py_QuietFlag; /* Needed by sysmodule.c */
84int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
85int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
86int Py_OptimizeFlag = 0; /* Needed by compile.c */
87int Py_NoSiteFlag; /* Suppress 'import site' */
88int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
89int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
90int Py_FrozenFlag; /* Needed by getpath.c */
91int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +080092int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +100093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
94int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
95int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
96int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -070097#ifdef MS_WINDOWS
98int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -070099int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700100#endif
Nick Coghland6009512014-11-20 21:39:37 +1000101
102PyThreadState *_Py_Finalizing = NULL;
103
104/* Hack to force loading of object files */
105int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
106 PyOS_mystrnicmp; /* Python/pystrcmp.o */
107
108/* PyModule_GetWarningsModule is no longer necessary as of 2.6
109since _warnings is builtin. This API should not be used. */
110PyObject *
111PyModule_GetWarningsModule(void)
112{
113 return PyImport_ImportModule("warnings");
114}
115
Eric Snowc7ec9982017-05-23 23:00:52 -0700116
Eric Snow1abcf672017-05-23 21:46:51 -0700117/* APIs to access the initialization flags
118 *
119 * Can be called prior to Py_Initialize.
120 */
121int _Py_CoreInitialized = 0;
122int _Py_Initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000123
Eric Snow1abcf672017-05-23 21:46:51 -0700124int
125_Py_IsCoreInitialized(void)
126{
127 return _Py_CoreInitialized;
128}
Nick Coghland6009512014-11-20 21:39:37 +1000129
130int
131Py_IsInitialized(void)
132{
Eric Snow1abcf672017-05-23 21:46:51 -0700133 return _Py_Initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000134}
135
136/* Helper to allow an embedding application to override the normal
137 * mechanism that attempts to figure out an appropriate IO encoding
138 */
139
140static char *_Py_StandardStreamEncoding = NULL;
141static char *_Py_StandardStreamErrors = NULL;
142
143int
144Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
145{
146 if (Py_IsInitialized()) {
147 /* This is too late to have any effect */
148 return -1;
149 }
150 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
151 * initialised yet.
152 *
153 * However, the raw memory allocators are initialised appropriately
154 * as C static variables, so _PyMem_RawStrdup is OK even though
155 * Py_Initialize hasn't been called yet.
156 */
157 if (encoding) {
158 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
159 if (!_Py_StandardStreamEncoding) {
160 return -2;
161 }
162 }
163 if (errors) {
164 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
165 if (!_Py_StandardStreamErrors) {
166 if (_Py_StandardStreamEncoding) {
167 PyMem_RawFree(_Py_StandardStreamEncoding);
168 }
169 return -3;
170 }
171 }
Steve Dower39294992016-08-30 21:22:36 -0700172#ifdef MS_WINDOWS
173 if (_Py_StandardStreamEncoding) {
174 /* Overriding the stream encoding implies legacy streams */
175 Py_LegacyWindowsStdioFlag = 1;
176 }
177#endif
Nick Coghland6009512014-11-20 21:39:37 +1000178 return 0;
179}
180
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000181/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
182 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000183 initializations fail, a fatal error is issued and the function does
184 not return. On return, the first thread and interpreter state have
185 been created.
186
187 Locking: you must hold the interpreter lock while calling this.
188 (If the lock has not yet been initialized, that's equivalent to
189 having the lock, but you cannot use multiple threads.)
190
191*/
192
193static int
194add_flag(int flag, const char *envs)
195{
196 int env = atoi(envs);
197 if (flag < env)
198 flag = env;
199 if (flag < 1)
200 flag = 1;
201 return flag;
202}
203
204static char*
205get_codec_name(const char *encoding)
206{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200207 const char *name_utf8;
208 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000209 PyObject *codec, *name = NULL;
210
211 codec = _PyCodec_Lookup(encoding);
212 if (!codec)
213 goto error;
214
215 name = _PyObject_GetAttrId(codec, &PyId_name);
216 Py_CLEAR(codec);
217 if (!name)
218 goto error;
219
Serhiy Storchaka06515832016-11-20 09:13:07 +0200220 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000221 if (name_utf8 == NULL)
222 goto error;
223 name_str = _PyMem_RawStrdup(name_utf8);
224 Py_DECREF(name);
225 if (name_str == NULL) {
226 PyErr_NoMemory();
227 return NULL;
228 }
229 return name_str;
230
231error:
232 Py_XDECREF(codec);
233 Py_XDECREF(name);
234 return NULL;
235}
236
237static char*
238get_locale_encoding(void)
239{
240#ifdef MS_WINDOWS
241 char codepage[100];
242 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
243 return get_codec_name(codepage);
244#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
245 char* codeset = nl_langinfo(CODESET);
246 if (!codeset || codeset[0] == '\0') {
247 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
248 return NULL;
249 }
250 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200251#elif defined(__ANDROID__)
252 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000253#else
254 PyErr_SetNone(PyExc_NotImplementedError);
255 return NULL;
256#endif
257}
258
259static void
Eric Snow1abcf672017-05-23 21:46:51 -0700260initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000261{
262 PyObject *importlib;
263 PyObject *impmod;
264 PyObject *sys_modules;
265 PyObject *value;
266
267 /* Import _importlib through its frozen version, _frozen_importlib. */
268 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
269 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
270 }
271 else if (Py_VerboseFlag) {
272 PySys_FormatStderr("import _frozen_importlib # frozen\n");
273 }
274 importlib = PyImport_AddModule("_frozen_importlib");
275 if (importlib == NULL) {
276 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
277 "sys.modules");
278 }
279 interp->importlib = importlib;
280 Py_INCREF(interp->importlib);
281
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300282 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
283 if (interp->import_func == NULL)
284 Py_FatalError("Py_Initialize: __import__ not found");
285 Py_INCREF(interp->import_func);
286
Victor Stinnercd6e6942015-09-18 09:11:57 +0200287 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000288 impmod = PyInit_imp();
289 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200290 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000291 }
292 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200293 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000294 }
295 sys_modules = PyImport_GetModuleDict();
296 if (Py_VerboseFlag) {
297 PySys_FormatStderr("import sys # builtin\n");
298 }
299 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
300 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
301 }
302
Victor Stinnercd6e6942015-09-18 09:11:57 +0200303 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000304 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Eric Snow6b4be192017-05-22 21:36:03 -0700305 if (value != NULL)
306 value = PyObject_CallMethod(importlib,
307 "_install_external_importers", "");
Nick Coghland6009512014-11-20 21:39:37 +1000308 if (value == NULL) {
309 PyErr_Print();
310 Py_FatalError("Py_Initialize: importlib install failed");
311 }
312 Py_DECREF(value);
313 Py_DECREF(impmod);
314
315 _PyImportZip_Init();
316}
317
Eric Snow1abcf672017-05-23 21:46:51 -0700318static void
319initexternalimport(PyInterpreterState *interp)
320{
321 PyObject *value;
322 value = PyObject_CallMethod(interp->importlib,
323 "_install_external_importers", "");
324 if (value == NULL) {
325 PyErr_Print();
326 Py_FatalError("Py_EndInitialization: external importer setup failed");
327 }
328}
Nick Coghland6009512014-11-20 21:39:37 +1000329
Eric Snow1abcf672017-05-23 21:46:51 -0700330
331/* Global initializations. Can be undone by Py_Finalize(). Don't
332 call this twice without an intervening Py_Finalize() call.
333
334 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
335 must have a corresponding call to Py_Finalize.
336
337 Locking: you must hold the interpreter lock while calling these APIs.
338 (If the lock has not yet been initialized, that's equivalent to
339 having the lock, but you cannot use multiple threads.)
340
341*/
342
343/* Begin interpreter initialization
344 *
345 * On return, the first thread and interpreter state have been created,
346 * but the compiler, signal handling, multithreading and
347 * multiple interpreter support, and codec infrastructure are not yet
348 * available.
349 *
350 * The import system will support builtin and frozen modules only.
351 * The only supported io is writing to sys.stderr
352 *
353 * If any operation invoked by this function fails, a fatal error is
354 * issued and the function does not return.
355 *
356 * Any code invoked from this function should *not* assume it has access
357 * to the Python C API (unless the API is explicitly listed as being
358 * safe to call without calling Py_Initialize first)
359 */
360
361/* TODO: Progresively move functionality from Py_BeginInitialization to
362 * Py_ReadConfig and Py_EndInitialization
363 */
364
365void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000366{
367 PyInterpreterState *interp;
368 PyThreadState *tstate;
369 PyObject *bimod, *sysmod, *pstderr;
370 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700371 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700372 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000373
Eric Snow1abcf672017-05-23 21:46:51 -0700374 if (config != NULL) {
375 core_config = *config;
376 }
377
378 if (_Py_Initialized) {
379 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
380 }
381 if (_Py_CoreInitialized) {
382 Py_FatalError("Py_InitializeCore: runtime core already initialized");
383 }
384
385 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
386 * threads behave a little more gracefully at interpreter shutdown.
387 * We clobber it here so the new interpreter can start with a clean
388 * slate.
389 *
390 * However, this may still lead to misbehaviour if there are daemon
391 * threads still hanging around from a previous Py_Initialize/Finalize
392 * pair :(
393 */
Nick Coghland6009512014-11-20 21:39:37 +1000394 _Py_Finalizing = NULL;
395
Xavier de Gayeb445ad72016-11-16 07:24:20 +0100396#ifdef HAVE_SETLOCALE
Nick Coghland6009512014-11-20 21:39:37 +1000397 /* Set up the LC_CTYPE locale, so we can obtain
398 the locale's charset without having to switch
399 locales. */
400 setlocale(LC_CTYPE, "");
401#endif
402
403 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
404 Py_DebugFlag = add_flag(Py_DebugFlag, p);
405 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
406 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
407 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
408 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
409 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
410 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700411 /* The variable is only tested for existence here;
412 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000413 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
414 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700415#ifdef MS_WINDOWS
416 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
417 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700418 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
419 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700420#endif
Nick Coghland6009512014-11-20 21:39:37 +1000421
Eric Snow1abcf672017-05-23 21:46:51 -0700422 _Py_HashRandomization_Init(&core_config);
423 if (!core_config.use_hash_seed || core_config.hash_seed) {
424 /* Random or non-zero hash seed */
425 Py_HashRandomizationFlag = 1;
426 }
Nick Coghland6009512014-11-20 21:39:37 +1000427
Eric Snowe3774162017-05-22 19:46:40 -0700428 _PyInterpreterState_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000429 interp = PyInterpreterState_New();
430 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700431 Py_FatalError("Py_InitializeCore: can't make main interpreter");
432 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700433 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000434
435 tstate = PyThreadState_New(interp);
436 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700437 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000438 (void) PyThreadState_Swap(tstate);
439
440#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000441 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000442 destroying the GIL might fail when it is being referenced from
443 another running thread (see issue #9901).
444 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000445 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000446 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000447 /* Auto-thread-state API */
448 _PyGILState_Init(interp, tstate);
449#endif /* WITH_THREAD */
450
451 _Py_ReadyTypes();
452
453 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700454 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000455
456 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700457 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000458
459 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700460 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000461
462 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700463 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000464
465 interp->modules = PyDict_New();
466 if (interp->modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700467 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000468
469 /* Init Unicode implementation; relies on the codec registry */
470 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700471 Py_FatalError("Py_InitializeCore: can't initialize unicode");
472
Nick Coghland6009512014-11-20 21:39:37 +1000473 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700474 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000475
476 bimod = _PyBuiltin_Init();
477 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700478 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Nick Coghland6009512014-11-20 21:39:37 +1000479 _PyImport_FixupBuiltin(bimod, "builtins");
480 interp->builtins = PyModule_GetDict(bimod);
481 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700482 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000483 Py_INCREF(interp->builtins);
484
485 /* initialize builtin exceptions */
486 _PyExc_Init(bimod);
487
Eric Snow6b4be192017-05-22 21:36:03 -0700488 sysmod = _PySys_BeginInit();
Nick Coghland6009512014-11-20 21:39:37 +1000489 if (sysmod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700490 Py_FatalError("Py_InitializeCore: can't initialize sys");
Nick Coghland6009512014-11-20 21:39:37 +1000491 interp->sysdict = PyModule_GetDict(sysmod);
492 if (interp->sysdict == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700493 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
Nick Coghland6009512014-11-20 21:39:37 +1000494 Py_INCREF(interp->sysdict);
495 _PyImport_FixupBuiltin(sysmod, "sys");
Nick Coghland6009512014-11-20 21:39:37 +1000496 PyDict_SetItemString(interp->sysdict, "modules",
497 interp->modules);
498
499 /* Set up a preliminary stderr printer until we have enough
500 infrastructure for the io module in place. */
501 pstderr = PyFile_NewStdPrinter(fileno(stderr));
502 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700503 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000504 _PySys_SetObjectId(&PyId_stderr, pstderr);
505 PySys_SetObject("__stderr__", pstderr);
506 Py_DECREF(pstderr);
507
508 _PyImport_Init();
509
510 _PyImportHooks_Init();
511
512 /* Initialize _warnings. */
513 _PyWarnings_Init();
514
Eric Snow1abcf672017-05-23 21:46:51 -0700515 /* This call sets up builtin and frozen import support */
516 if (!interp->core_config._disable_importlib) {
517 initimport(interp, sysmod);
518 }
519
520 /* Only when we get here is the runtime core fully initialized */
521 _Py_CoreInitialized = 1;
522}
523
Eric Snowc7ec9982017-05-23 23:00:52 -0700524/* Read configuration settings from standard locations
525 *
526 * This function doesn't make any changes to the interpreter state - it
527 * merely populates any missing configuration settings. This allows an
528 * embedding application to completely override a config option by
529 * setting it before calling this function, or else modify the default
530 * setting before passing the fully populated config to Py_EndInitialization.
531 *
532 * More advanced selective initialization tricks are possible by calling
533 * this function multiple times with various preconfigured settings.
534 */
535
536int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
537{
538 /* Signal handlers are installed by default */
539 if (config->install_signal_handlers < 0) {
540 config->install_signal_handlers = 1;
541 }
542
543 return 0;
544}
545
546/* Update interpreter state based on supplied configuration settings
547 *
548 * After calling this function, most of the restrictions on the interpreter
549 * are lifted. The only remaining incomplete settings are those related
550 * to the main module (sys.argv[0], __main__ metadata)
551 *
552 * Calling this when the interpreter is not initializing, is already
553 * initialized or without a valid current thread state is a fatal error.
554 * Other errors should be reported as normal Python exceptions with a
555 * non-zero return code.
556 */
557int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700558{
559 PyInterpreterState *interp;
560 PyThreadState *tstate;
561
Eric Snowc7ec9982017-05-23 23:00:52 -0700562 if (!_Py_CoreInitialized) {
563 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
564 }
565 if (_Py_Initialized) {
566 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
567 }
568
Eric Snow1abcf672017-05-23 21:46:51 -0700569 /* Get current thread state and interpreter pointer */
570 tstate = PyThreadState_GET();
571 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700572 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700573 interp = tstate->interp;
574 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700575 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700576
577 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700578 interp->config = *config;
579
Eric Snow1abcf672017-05-23 21:46:51 -0700580 if (interp->core_config._disable_importlib) {
581 /* Special mode for freeze_importlib: run with no import system
582 *
583 * This means anything which needs support from extension modules
584 * or pure Python code in the standard library won't work.
585 */
586 _Py_Initialized = 1;
587 return 0;
588 }
589 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000590
Victor Stinner13019fd2015-04-03 13:10:54 +0200591 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700592 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200593
Eric Snow1abcf672017-05-23 21:46:51 -0700594 /* Finish setting up the sys module and import system */
595 /* GetPath may initialize state that _PySys_EndInit locks
596 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700597 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700598 PySys_SetPath(Py_GetPath());
599 if (_PySys_EndInit(interp->sysdict) < 0)
600 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700601 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000602
603 /* initialize the faulthandler module */
604 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700605 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000606
Nick Coghland6009512014-11-20 21:39:37 +1000607 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700608 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000609
Eric Snowc7ec9982017-05-23 23:00:52 -0700610 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000611 initsigs(); /* Signal handling stuff, including initintr() */
612
613 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700614 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000615
616 initmain(interp); /* Module __main__ */
617 if (initstdio() < 0)
618 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700619 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000620
621 /* Initialize warnings. */
622 if (PySys_HasWarnOptions()) {
623 PyObject *warnings_module = PyImport_ImportModule("warnings");
624 if (warnings_module == NULL) {
625 fprintf(stderr, "'import warnings' failed; traceback:\n");
626 PyErr_Print();
627 }
628 Py_XDECREF(warnings_module);
629 }
630
Eric Snow1abcf672017-05-23 21:46:51 -0700631 _Py_Initialized = 1;
632
Nick Coghland6009512014-11-20 21:39:37 +1000633 if (!Py_NoSiteFlag)
634 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700635
Eric Snowc7ec9982017-05-23 23:00:52 -0700636 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000637}
638
Eric Snowc7ec9982017-05-23 23:00:52 -0700639#undef _INIT_DEBUG_PRINT
640
Nick Coghland6009512014-11-20 21:39:37 +1000641void
Eric Snow1abcf672017-05-23 21:46:51 -0700642_Py_InitializeEx_Private(int install_sigs, int install_importlib)
643{
644 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700645 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700646
647 /* TODO: Moar config options! */
648 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
649 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700650 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700651 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700652 /* TODO: Print any exceptions raised by these operations */
653 if (_Py_ReadMainInterpreterConfig(&config))
654 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
655 if (_Py_InitializeMainInterpreter(&config))
656 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700657}
658
659
660void
Nick Coghland6009512014-11-20 21:39:37 +1000661Py_InitializeEx(int install_sigs)
662{
663 _Py_InitializeEx_Private(install_sigs, 1);
664}
665
666void
667Py_Initialize(void)
668{
669 Py_InitializeEx(1);
670}
671
672
673#ifdef COUNT_ALLOCS
674extern void dump_counts(FILE*);
675#endif
676
677/* Flush stdout and stderr */
678
679static int
680file_is_closed(PyObject *fobj)
681{
682 int r;
683 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
684 if (tmp == NULL) {
685 PyErr_Clear();
686 return 0;
687 }
688 r = PyObject_IsTrue(tmp);
689 Py_DECREF(tmp);
690 if (r < 0)
691 PyErr_Clear();
692 return r > 0;
693}
694
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000695static int
Nick Coghland6009512014-11-20 21:39:37 +1000696flush_std_files(void)
697{
698 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
699 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
700 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000701 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000702
703 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700704 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000705 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000706 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000707 status = -1;
708 }
Nick Coghland6009512014-11-20 21:39:37 +1000709 else
710 Py_DECREF(tmp);
711 }
712
713 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700714 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000715 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000716 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000717 status = -1;
718 }
Nick Coghland6009512014-11-20 21:39:37 +1000719 else
720 Py_DECREF(tmp);
721 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000722
723 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000724}
725
726/* Undo the effect of Py_Initialize().
727
728 Beware: if multiple interpreter and/or thread states exist, these
729 are not wiped out; only the current thread and interpreter state
730 are deleted. But since everything else is deleted, those other
731 interpreter and thread states should no longer be used.
732
733 (XXX We should do better, e.g. wipe out all interpreters and
734 threads.)
735
736 Locking: as above.
737
738*/
739
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000740int
741Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000742{
743 PyInterpreterState *interp;
744 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000745 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000746
Eric Snow1abcf672017-05-23 21:46:51 -0700747 if (!_Py_Initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000748 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000749
750 wait_for_thread_shutdown();
751
752 /* The interpreter is still entirely intact at this point, and the
753 * exit funcs may be relying on that. In particular, if some thread
754 * or exit func is still waiting to do an import, the import machinery
755 * expects Py_IsInitialized() to return true. So don't say the
756 * interpreter is uninitialized until after the exit funcs have run.
757 * Note that Threading.py uses an exit func to do a join on all the
758 * threads created thru it, so this also protects pending imports in
759 * the threads created via Threading.
760 */
761 call_py_exitfuncs();
762
763 /* Get current thread state and interpreter pointer */
764 tstate = PyThreadState_GET();
765 interp = tstate->interp;
766
767 /* Remaining threads (e.g. daemon threads) will automatically exit
768 after taking the GIL (in PyEval_RestoreThread()). */
769 _Py_Finalizing = tstate;
Eric Snow1abcf672017-05-23 21:46:51 -0700770 _Py_Initialized = 0;
771 _Py_CoreInitialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000772
Victor Stinnere0deff32015-03-24 13:46:18 +0100773 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000774 if (flush_std_files() < 0) {
775 status = -1;
776 }
Nick Coghland6009512014-11-20 21:39:37 +1000777
778 /* Disable signal handling */
779 PyOS_FiniInterrupts();
780
781 /* Collect garbage. This may call finalizers; it's nice to call these
782 * before all modules are destroyed.
783 * XXX If a __del__ or weakref callback is triggered here, and tries to
784 * XXX import a module, bad things can happen, because Python no
785 * XXX longer believes it's initialized.
786 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
787 * XXX is easy to provoke that way. I've also seen, e.g.,
788 * XXX Exception exceptions.ImportError: 'No module named sha'
789 * XXX in <function callback at 0x008F5718> ignored
790 * XXX but I'm unclear on exactly how that one happens. In any case,
791 * XXX I haven't seen a real-life report of either of these.
792 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700793 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000794#ifdef COUNT_ALLOCS
795 /* With COUNT_ALLOCS, it helps to run GC multiple times:
796 each collection might release some types from the type
797 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700798 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000799 /* nothing */;
800#endif
801 /* Destroy all modules */
802 PyImport_Cleanup();
803
Victor Stinnere0deff32015-03-24 13:46:18 +0100804 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000805 if (flush_std_files() < 0) {
806 status = -1;
807 }
Nick Coghland6009512014-11-20 21:39:37 +1000808
809 /* Collect final garbage. This disposes of cycles created by
810 * class definitions, for example.
811 * XXX This is disabled because it caused too many problems. If
812 * XXX a __del__ or weakref callback triggers here, Python code has
813 * XXX a hard time running, because even the sys module has been
814 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
815 * XXX One symptom is a sequence of information-free messages
816 * XXX coming from threads (if a __del__ or callback is invoked,
817 * XXX other threads can execute too, and any exception they encounter
818 * XXX triggers a comedy of errors as subsystem after subsystem
819 * XXX fails to find what it *expects* to find in sys to help report
820 * XXX the exception and consequent unexpected failures). I've also
821 * XXX seen segfaults then, after adding print statements to the
822 * XXX Python code getting called.
823 */
824#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -0700825 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000826#endif
827
828 /* Disable tracemalloc after all Python objects have been destroyed,
829 so it is possible to use tracemalloc in objects destructor. */
830 _PyTraceMalloc_Fini();
831
832 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
833 _PyImport_Fini();
834
835 /* Cleanup typeobject.c's internal caches. */
836 _PyType_Fini();
837
838 /* unload faulthandler module */
839 _PyFaulthandler_Fini();
840
841 /* Debugging stuff */
842#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300843 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +1000844#endif
845 /* dump hash stats */
846 _PyHash_Fini();
847
848 _PY_DEBUG_PRINT_TOTAL_REFS();
849
850#ifdef Py_TRACE_REFS
851 /* Display all objects still alive -- this can invoke arbitrary
852 * __repr__ overrides, so requires a mostly-intact interpreter.
853 * Alas, a lot of stuff may still be alive now that will be cleaned
854 * up later.
855 */
856 if (Py_GETENV("PYTHONDUMPREFS"))
857 _Py_PrintReferences(stderr);
858#endif /* Py_TRACE_REFS */
859
860 /* Clear interpreter state and all thread states. */
861 PyInterpreterState_Clear(interp);
862
863 /* Now we decref the exception classes. After this point nothing
864 can raise an exception. That's okay, because each Fini() method
865 below has been checked to make sure no exceptions are ever
866 raised.
867 */
868
869 _PyExc_Fini();
870
871 /* Sundry finalizers */
872 PyMethod_Fini();
873 PyFrame_Fini();
874 PyCFunction_Fini();
875 PyTuple_Fini();
876 PyList_Fini();
877 PySet_Fini();
878 PyBytes_Fini();
879 PyByteArray_Fini();
880 PyLong_Fini();
881 PyFloat_Fini();
882 PyDict_Fini();
883 PySlice_Fini();
884 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -0700885 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +0300886 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -0700887 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +1000888
889 /* Cleanup Unicode implementation */
890 _PyUnicode_Fini();
891
892 /* reset file system default encoding */
893 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
894 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
895 Py_FileSystemDefaultEncoding = NULL;
896 }
897
898 /* XXX Still allocated:
899 - various static ad-hoc pointers to interned strings
900 - int and float free list blocks
901 - whatever various modules and libraries allocate
902 */
903
904 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
905
906 /* Cleanup auto-thread-state */
907#ifdef WITH_THREAD
908 _PyGILState_Fini();
909#endif /* WITH_THREAD */
910
911 /* Delete current thread. After this, many C API calls become crashy. */
912 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +0100913
Nick Coghland6009512014-11-20 21:39:37 +1000914 PyInterpreterState_Delete(interp);
915
916#ifdef Py_TRACE_REFS
917 /* Display addresses (& refcnts) of all objects still alive.
918 * An address can be used to find the repr of the object, printed
919 * above by _Py_PrintReferences.
920 */
921 if (Py_GETENV("PYTHONDUMPREFS"))
922 _Py_PrintReferenceAddresses(stderr);
923#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +0100924#ifdef WITH_PYMALLOC
925 if (_PyMem_PymallocEnabled()) {
926 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
927 if (opt != NULL && *opt != '\0')
928 _PyObject_DebugMallocStats(stderr);
929 }
Nick Coghland6009512014-11-20 21:39:37 +1000930#endif
931
932 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000933 return status;
934}
935
936void
937Py_Finalize(void)
938{
939 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +1000940}
941
942/* Create and initialize a new interpreter and thread, and return the
943 new thread. This requires that Py_Initialize() has been called
944 first.
945
946 Unsuccessful initialization yields a NULL pointer. Note that *no*
947 exception information is available even in this case -- the
948 exception information is held in the thread, and there is no
949 thread.
950
951 Locking: as above.
952
953*/
954
955PyThreadState *
956Py_NewInterpreter(void)
957{
958 PyInterpreterState *interp;
959 PyThreadState *tstate, *save_tstate;
960 PyObject *bimod, *sysmod;
961
Eric Snow1abcf672017-05-23 21:46:51 -0700962 if (!_Py_Initialized)
Nick Coghland6009512014-11-20 21:39:37 +1000963 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
964
Victor Stinnerd7292b52016-06-17 12:29:00 +0200965#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +0100966 /* Issue #10915, #15751: The GIL API doesn't work with multiple
967 interpreters: disable PyGILState_Check(). */
968 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +0300969#endif
Victor Stinner8a1be612016-03-14 22:07:55 +0100970
Nick Coghland6009512014-11-20 21:39:37 +1000971 interp = PyInterpreterState_New();
972 if (interp == NULL)
973 return NULL;
974
975 tstate = PyThreadState_New(interp);
976 if (tstate == NULL) {
977 PyInterpreterState_Delete(interp);
978 return NULL;
979 }
980
981 save_tstate = PyThreadState_Swap(tstate);
982
Eric Snow1abcf672017-05-23 21:46:51 -0700983 /* Copy the current interpreter config into the new interpreter */
984 if (save_tstate != NULL) {
985 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700986 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -0700987 } else {
988 /* No current thread state, copy from the main interpreter */
989 PyInterpreterState *main_interp = PyInterpreterState_Main();
990 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700991 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -0700992 }
993
Nick Coghland6009512014-11-20 21:39:37 +1000994 /* XXX The following is lax in error checking */
995
996 interp->modules = PyDict_New();
997
998 bimod = _PyImport_FindBuiltin("builtins");
999 if (bimod != NULL) {
1000 interp->builtins = PyModule_GetDict(bimod);
1001 if (interp->builtins == NULL)
1002 goto handle_error;
1003 Py_INCREF(interp->builtins);
1004 }
1005
1006 /* initialize builtin exceptions */
1007 _PyExc_Init(bimod);
1008
1009 sysmod = _PyImport_FindBuiltin("sys");
1010 if (bimod != NULL && sysmod != NULL) {
1011 PyObject *pstderr;
1012
1013 interp->sysdict = PyModule_GetDict(sysmod);
1014 if (interp->sysdict == NULL)
1015 goto handle_error;
1016 Py_INCREF(interp->sysdict);
Eric Snow1abcf672017-05-23 21:46:51 -07001017 _PySys_EndInit(interp->sysdict);
Nick Coghland6009512014-11-20 21:39:37 +10001018 PySys_SetPath(Py_GetPath());
1019 PyDict_SetItemString(interp->sysdict, "modules",
1020 interp->modules);
1021 /* Set up a preliminary stderr printer until we have enough
1022 infrastructure for the io module in place. */
1023 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1024 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001025 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001026 _PySys_SetObjectId(&PyId_stderr, pstderr);
1027 PySys_SetObject("__stderr__", pstderr);
1028 Py_DECREF(pstderr);
1029
1030 _PyImportHooks_Init();
1031
Eric Snow1abcf672017-05-23 21:46:51 -07001032 initimport(interp, sysmod);
1033 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001034
1035 if (initfsencoding(interp) < 0)
1036 goto handle_error;
1037
1038 if (initstdio() < 0)
1039 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001040 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001041 initmain(interp);
1042 if (!Py_NoSiteFlag)
1043 initsite();
1044 }
1045
1046 if (!PyErr_Occurred())
1047 return tstate;
1048
1049handle_error:
1050 /* Oops, it didn't work. Undo it all. */
1051
1052 PyErr_PrintEx(0);
1053 PyThreadState_Clear(tstate);
1054 PyThreadState_Swap(save_tstate);
1055 PyThreadState_Delete(tstate);
1056 PyInterpreterState_Delete(interp);
1057
1058 return NULL;
1059}
1060
1061/* Delete an interpreter and its last thread. This requires that the
1062 given thread state is current, that the thread has no remaining
1063 frames, and that it is its interpreter's only remaining thread.
1064 It is a fatal error to violate these constraints.
1065
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001066 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001067 everything, regardless.)
1068
1069 Locking: as above.
1070
1071*/
1072
1073void
1074Py_EndInterpreter(PyThreadState *tstate)
1075{
1076 PyInterpreterState *interp = tstate->interp;
1077
1078 if (tstate != PyThreadState_GET())
1079 Py_FatalError("Py_EndInterpreter: thread is not current");
1080 if (tstate->frame != NULL)
1081 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1082
1083 wait_for_thread_shutdown();
1084
1085 if (tstate != interp->tstate_head || tstate->next != NULL)
1086 Py_FatalError("Py_EndInterpreter: not the last thread");
1087
1088 PyImport_Cleanup();
1089 PyInterpreterState_Clear(interp);
1090 PyThreadState_Swap(NULL);
1091 PyInterpreterState_Delete(interp);
1092}
1093
1094#ifdef MS_WINDOWS
1095static wchar_t *progname = L"python";
1096#else
1097static wchar_t *progname = L"python3";
1098#endif
1099
1100void
1101Py_SetProgramName(wchar_t *pn)
1102{
1103 if (pn && *pn)
1104 progname = pn;
1105}
1106
1107wchar_t *
1108Py_GetProgramName(void)
1109{
1110 return progname;
1111}
1112
1113static wchar_t *default_home = NULL;
1114static wchar_t env_home[MAXPATHLEN+1];
1115
1116void
1117Py_SetPythonHome(wchar_t *home)
1118{
1119 default_home = home;
1120}
1121
1122wchar_t *
1123Py_GetPythonHome(void)
1124{
1125 wchar_t *home = default_home;
1126 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1127 char* chome = Py_GETENV("PYTHONHOME");
1128 if (chome) {
1129 size_t size = Py_ARRAY_LENGTH(env_home);
1130 size_t r = mbstowcs(env_home, chome, size);
1131 if (r != (size_t)-1 && r < size)
1132 home = env_home;
1133 }
1134
1135 }
1136 return home;
1137}
1138
1139/* Create __main__ module */
1140
1141static void
1142initmain(PyInterpreterState *interp)
1143{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001144 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001145 m = PyImport_AddModule("__main__");
1146 if (m == NULL)
1147 Py_FatalError("can't create __main__ module");
1148 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001149 ann_dict = PyDict_New();
1150 if ((ann_dict == NULL) ||
1151 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1152 Py_FatalError("Failed to initialize __main__.__annotations__");
1153 }
1154 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001155 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1156 PyObject *bimod = PyImport_ImportModule("builtins");
1157 if (bimod == NULL) {
1158 Py_FatalError("Failed to retrieve builtins module");
1159 }
1160 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1161 Py_FatalError("Failed to initialize __main__.__builtins__");
1162 }
1163 Py_DECREF(bimod);
1164 }
1165 /* Main is a little special - imp.is_builtin("__main__") will return
1166 * False, but BuiltinImporter is still the most appropriate initial
1167 * setting for its __loader__ attribute. A more suitable value will
1168 * be set if __main__ gets further initialized later in the startup
1169 * process.
1170 */
1171 loader = PyDict_GetItemString(d, "__loader__");
1172 if (loader == NULL || loader == Py_None) {
1173 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1174 "BuiltinImporter");
1175 if (loader == NULL) {
1176 Py_FatalError("Failed to retrieve BuiltinImporter");
1177 }
1178 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1179 Py_FatalError("Failed to initialize __main__.__loader__");
1180 }
1181 Py_DECREF(loader);
1182 }
1183}
1184
1185static int
1186initfsencoding(PyInterpreterState *interp)
1187{
1188 PyObject *codec;
1189
Steve Dowercc16be82016-09-08 10:35:16 -07001190#ifdef MS_WINDOWS
1191 if (Py_LegacyWindowsFSEncodingFlag)
1192 {
1193 Py_FileSystemDefaultEncoding = "mbcs";
1194 Py_FileSystemDefaultEncodeErrors = "replace";
1195 }
1196 else
1197 {
1198 Py_FileSystemDefaultEncoding = "utf-8";
1199 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1200 }
1201#else
Nick Coghland6009512014-11-20 21:39:37 +10001202 if (Py_FileSystemDefaultEncoding == NULL)
1203 {
1204 Py_FileSystemDefaultEncoding = get_locale_encoding();
1205 if (Py_FileSystemDefaultEncoding == NULL)
1206 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1207
1208 Py_HasFileSystemDefaultEncoding = 0;
1209 interp->fscodec_initialized = 1;
1210 return 0;
1211 }
Steve Dowercc16be82016-09-08 10:35:16 -07001212#endif
Nick Coghland6009512014-11-20 21:39:37 +10001213
1214 /* the encoding is mbcs, utf-8 or ascii */
1215 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1216 if (!codec) {
1217 /* Such error can only occurs in critical situations: no more
1218 * memory, import a module of the standard library failed,
1219 * etc. */
1220 return -1;
1221 }
1222 Py_DECREF(codec);
1223 interp->fscodec_initialized = 1;
1224 return 0;
1225}
1226
1227/* Import the site module (not into __main__ though) */
1228
1229static void
1230initsite(void)
1231{
1232 PyObject *m;
1233 m = PyImport_ImportModule("site");
1234 if (m == NULL) {
1235 fprintf(stderr, "Failed to import the site module\n");
1236 PyErr_Print();
1237 Py_Finalize();
1238 exit(1);
1239 }
1240 else {
1241 Py_DECREF(m);
1242 }
1243}
1244
Victor Stinner874dbe82015-09-04 17:29:57 +02001245/* Check if a file descriptor is valid or not.
1246 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1247static int
1248is_valid_fd(int fd)
1249{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001250#ifdef __APPLE__
1251 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1252 and the other side of the pipe is closed, dup(1) succeed, whereas
1253 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1254 such error. */
1255 struct stat st;
1256 return (fstat(fd, &st) == 0);
1257#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001258 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001259 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001260 return 0;
1261 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001262 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1263 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1264 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001265 fd2 = dup(fd);
1266 if (fd2 >= 0)
1267 close(fd2);
1268 _Py_END_SUPPRESS_IPH
1269 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001270#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001271}
1272
1273/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001274static PyObject*
1275create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001276 int fd, int write_mode, const char* name,
1277 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001278{
1279 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1280 const char* mode;
1281 const char* newline;
1282 PyObject *line_buffering;
1283 int buffering, isatty;
1284 _Py_IDENTIFIER(open);
1285 _Py_IDENTIFIER(isatty);
1286 _Py_IDENTIFIER(TextIOWrapper);
1287 _Py_IDENTIFIER(mode);
1288
Victor Stinner874dbe82015-09-04 17:29:57 +02001289 if (!is_valid_fd(fd))
1290 Py_RETURN_NONE;
1291
Nick Coghland6009512014-11-20 21:39:37 +10001292 /* stdin is always opened in buffered mode, first because it shouldn't
1293 make a difference in common use cases, second because TextIOWrapper
1294 depends on the presence of a read1() method which only exists on
1295 buffered streams.
1296 */
1297 if (Py_UnbufferedStdioFlag && write_mode)
1298 buffering = 0;
1299 else
1300 buffering = -1;
1301 if (write_mode)
1302 mode = "wb";
1303 else
1304 mode = "rb";
1305 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1306 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001307 Py_None, Py_None, /* encoding, errors */
1308 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001309 if (buf == NULL)
1310 goto error;
1311
1312 if (buffering) {
1313 _Py_IDENTIFIER(raw);
1314 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1315 if (raw == NULL)
1316 goto error;
1317 }
1318 else {
1319 raw = buf;
1320 Py_INCREF(raw);
1321 }
1322
Steve Dower39294992016-08-30 21:22:36 -07001323#ifdef MS_WINDOWS
1324 /* Windows console IO is always UTF-8 encoded */
1325 if (PyWindowsConsoleIO_Check(raw))
1326 encoding = "utf-8";
1327#endif
1328
Nick Coghland6009512014-11-20 21:39:37 +10001329 text = PyUnicode_FromString(name);
1330 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1331 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001332 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001333 if (res == NULL)
1334 goto error;
1335 isatty = PyObject_IsTrue(res);
1336 Py_DECREF(res);
1337 if (isatty == -1)
1338 goto error;
1339 if (isatty || Py_UnbufferedStdioFlag)
1340 line_buffering = Py_True;
1341 else
1342 line_buffering = Py_False;
1343
1344 Py_CLEAR(raw);
1345 Py_CLEAR(text);
1346
1347#ifdef MS_WINDOWS
1348 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1349 newlines to "\n".
1350 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1351 newline = NULL;
1352#else
1353 /* sys.stdin: split lines at "\n".
1354 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1355 newline = "\n";
1356#endif
1357
1358 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1359 buf, encoding, errors,
1360 newline, line_buffering);
1361 Py_CLEAR(buf);
1362 if (stream == NULL)
1363 goto error;
1364
1365 if (write_mode)
1366 mode = "w";
1367 else
1368 mode = "r";
1369 text = PyUnicode_FromString(mode);
1370 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1371 goto error;
1372 Py_CLEAR(text);
1373 return stream;
1374
1375error:
1376 Py_XDECREF(buf);
1377 Py_XDECREF(stream);
1378 Py_XDECREF(text);
1379 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001380
Victor Stinner874dbe82015-09-04 17:29:57 +02001381 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1382 /* Issue #24891: the file descriptor was closed after the first
1383 is_valid_fd() check was called. Ignore the OSError and set the
1384 stream to None. */
1385 PyErr_Clear();
1386 Py_RETURN_NONE;
1387 }
1388 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001389}
1390
1391/* Initialize sys.stdin, stdout, stderr and builtins.open */
1392static int
1393initstdio(void)
1394{
1395 PyObject *iomod = NULL, *wrapper;
1396 PyObject *bimod = NULL;
1397 PyObject *m;
1398 PyObject *std = NULL;
1399 int status = 0, fd;
1400 PyObject * encoding_attr;
1401 char *pythonioencoding = NULL, *encoding, *errors;
1402
1403 /* Hack to avoid a nasty recursion issue when Python is invoked
1404 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1405 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1406 goto error;
1407 }
1408 Py_DECREF(m);
1409
1410 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1411 goto error;
1412 }
1413 Py_DECREF(m);
1414
1415 if (!(bimod = PyImport_ImportModule("builtins"))) {
1416 goto error;
1417 }
1418
1419 if (!(iomod = PyImport_ImportModule("io"))) {
1420 goto error;
1421 }
1422 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1423 goto error;
1424 }
1425
1426 /* Set builtins.open */
1427 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1428 Py_DECREF(wrapper);
1429 goto error;
1430 }
1431 Py_DECREF(wrapper);
1432
1433 encoding = _Py_StandardStreamEncoding;
1434 errors = _Py_StandardStreamErrors;
1435 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001436 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1437 if (pythonioencoding) {
1438 char *err;
1439 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1440 if (pythonioencoding == NULL) {
1441 PyErr_NoMemory();
1442 goto error;
1443 }
1444 err = strchr(pythonioencoding, ':');
1445 if (err) {
1446 *err = '\0';
1447 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001448 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001449 errors = err;
1450 }
1451 }
1452 if (*pythonioencoding && !encoding) {
1453 encoding = pythonioencoding;
1454 }
1455 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001456 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1457 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1458 stdin and stdout use the surrogateescape error handler by
1459 default, instead of the strict error handler. */
1460 char *loc = setlocale(LC_CTYPE, NULL);
1461 if (loc != NULL && strcmp(loc, "C") == 0)
1462 errors = "surrogateescape";
1463 }
Nick Coghland6009512014-11-20 21:39:37 +10001464 }
1465
1466 /* Set sys.stdin */
1467 fd = fileno(stdin);
1468 /* Under some conditions stdin, stdout and stderr may not be connected
1469 * and fileno() may point to an invalid file descriptor. For example
1470 * GUI apps don't have valid standard streams by default.
1471 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001472 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1473 if (std == NULL)
1474 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001475 PySys_SetObject("__stdin__", std);
1476 _PySys_SetObjectId(&PyId_stdin, std);
1477 Py_DECREF(std);
1478
1479 /* Set sys.stdout */
1480 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001481 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1482 if (std == NULL)
1483 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001484 PySys_SetObject("__stdout__", std);
1485 _PySys_SetObjectId(&PyId_stdout, std);
1486 Py_DECREF(std);
1487
1488#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1489 /* Set sys.stderr, replaces the preliminary stderr */
1490 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001491 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1492 if (std == NULL)
1493 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001494
1495 /* Same as hack above, pre-import stderr's codec to avoid recursion
1496 when import.c tries to write to stderr in verbose mode. */
1497 encoding_attr = PyObject_GetAttrString(std, "encoding");
1498 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001499 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001500 if (std_encoding != NULL) {
1501 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1502 Py_XDECREF(codec_info);
1503 }
1504 Py_DECREF(encoding_attr);
1505 }
1506 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1507
1508 if (PySys_SetObject("__stderr__", std) < 0) {
1509 Py_DECREF(std);
1510 goto error;
1511 }
1512 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1513 Py_DECREF(std);
1514 goto error;
1515 }
1516 Py_DECREF(std);
1517#endif
1518
1519 if (0) {
1520 error:
1521 status = -1;
1522 }
1523
1524 /* We won't need them anymore. */
1525 if (_Py_StandardStreamEncoding) {
1526 PyMem_RawFree(_Py_StandardStreamEncoding);
1527 _Py_StandardStreamEncoding = NULL;
1528 }
1529 if (_Py_StandardStreamErrors) {
1530 PyMem_RawFree(_Py_StandardStreamErrors);
1531 _Py_StandardStreamErrors = NULL;
1532 }
1533 PyMem_Free(pythonioencoding);
1534 Py_XDECREF(bimod);
1535 Py_XDECREF(iomod);
1536 return status;
1537}
1538
1539
Victor Stinner10dc4842015-03-24 12:01:30 +01001540static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001541_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001542{
Victor Stinner10dc4842015-03-24 12:01:30 +01001543 fputc('\n', stderr);
1544 fflush(stderr);
1545
1546 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001547 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001548}
Victor Stinner791da1c2016-03-14 16:53:12 +01001549
1550/* Print the current exception (if an exception is set) with its traceback,
1551 or display the current Python stack.
1552
1553 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1554 called on catastrophic cases.
1555
1556 Return 1 if the traceback was displayed, 0 otherwise. */
1557
1558static int
1559_Py_FatalError_PrintExc(int fd)
1560{
1561 PyObject *ferr, *res;
1562 PyObject *exception, *v, *tb;
1563 int has_tb;
1564
1565 if (PyThreadState_GET() == NULL) {
1566 /* The GIL is released: trying to acquire it is likely to deadlock,
1567 just give up. */
1568 return 0;
1569 }
1570
1571 PyErr_Fetch(&exception, &v, &tb);
1572 if (exception == NULL) {
1573 /* No current exception */
1574 return 0;
1575 }
1576
1577 ferr = _PySys_GetObjectId(&PyId_stderr);
1578 if (ferr == NULL || ferr == Py_None) {
1579 /* sys.stderr is not set yet or set to None,
1580 no need to try to display the exception */
1581 return 0;
1582 }
1583
1584 PyErr_NormalizeException(&exception, &v, &tb);
1585 if (tb == NULL) {
1586 tb = Py_None;
1587 Py_INCREF(tb);
1588 }
1589 PyException_SetTraceback(v, tb);
1590 if (exception == NULL) {
1591 /* PyErr_NormalizeException() failed */
1592 return 0;
1593 }
1594
1595 has_tb = (tb != Py_None);
1596 PyErr_Display(exception, v, tb);
1597 Py_XDECREF(exception);
1598 Py_XDECREF(v);
1599 Py_XDECREF(tb);
1600
1601 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001602 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001603 if (res == NULL)
1604 PyErr_Clear();
1605 else
1606 Py_DECREF(res);
1607
1608 return has_tb;
1609}
1610
Nick Coghland6009512014-11-20 21:39:37 +10001611/* Print fatal error message and abort */
1612
1613void
1614Py_FatalError(const char *msg)
1615{
1616 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001617 static int reentrant = 0;
1618#ifdef MS_WINDOWS
1619 size_t len;
1620 WCHAR* buffer;
1621 size_t i;
1622#endif
1623
1624 if (reentrant) {
1625 /* Py_FatalError() caused a second fatal error.
1626 Example: flush_std_files() raises a recursion error. */
1627 goto exit;
1628 }
1629 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001630
1631 fprintf(stderr, "Fatal Python error: %s\n", msg);
1632 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001633
Victor Stinnere0deff32015-03-24 13:46:18 +01001634 /* Print the exception (if an exception is set) with its traceback,
1635 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001636 if (!_Py_FatalError_PrintExc(fd))
1637 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001638
Victor Stinner2025d782016-03-16 23:19:15 +01001639 /* The main purpose of faulthandler is to display the traceback. We already
1640 * did our best to display it. So faulthandler can now be disabled.
1641 * (Don't trigger it on abort().) */
1642 _PyFaulthandler_Fini();
1643
Victor Stinner791da1c2016-03-14 16:53:12 +01001644 /* Check if the current Python thread hold the GIL */
1645 if (PyThreadState_GET() != NULL) {
1646 /* Flush sys.stdout and sys.stderr */
1647 flush_std_files();
1648 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001649
Nick Coghland6009512014-11-20 21:39:37 +10001650#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001651 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001652
Victor Stinner53345a42015-03-25 01:55:14 +01001653 /* Convert the message to wchar_t. This uses a simple one-to-one
1654 conversion, assuming that the this error message actually uses ASCII
1655 only. If this ceases to be true, we will have to convert. */
1656 buffer = alloca( (len+1) * (sizeof *buffer));
1657 for( i=0; i<=len; ++i)
1658 buffer[i] = msg[i];
1659 OutputDebugStringW(L"Fatal Python error: ");
1660 OutputDebugStringW(buffer);
1661 OutputDebugStringW(L"\n");
1662#endif /* MS_WINDOWS */
1663
1664exit:
1665#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001666 DebugBreak();
1667#endif
Nick Coghland6009512014-11-20 21:39:37 +10001668 abort();
1669}
1670
1671/* Clean up and exit */
1672
1673#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001674# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001675#endif
1676
1677static void (*pyexitfunc)(void) = NULL;
1678/* For the atexit module. */
1679void _Py_PyAtExit(void (*func)(void))
1680{
1681 pyexitfunc = func;
1682}
1683
1684static void
1685call_py_exitfuncs(void)
1686{
1687 if (pyexitfunc == NULL)
1688 return;
1689
1690 (*pyexitfunc)();
1691 PyErr_Clear();
1692}
1693
1694/* Wait until threading._shutdown completes, provided
1695 the threading module was imported in the first place.
1696 The shutdown routine will wait until all non-daemon
1697 "threading" threads have completed. */
1698static void
1699wait_for_thread_shutdown(void)
1700{
1701#ifdef WITH_THREAD
1702 _Py_IDENTIFIER(_shutdown);
1703 PyObject *result;
1704 PyThreadState *tstate = PyThreadState_GET();
1705 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1706 "threading");
1707 if (threading == NULL) {
1708 /* threading not imported */
1709 PyErr_Clear();
1710 return;
1711 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001712 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001713 if (result == NULL) {
1714 PyErr_WriteUnraisable(threading);
1715 }
1716 else {
1717 Py_DECREF(result);
1718 }
1719 Py_DECREF(threading);
1720#endif
1721}
1722
1723#define NEXITFUNCS 32
1724static void (*exitfuncs[NEXITFUNCS])(void);
1725static int nexitfuncs = 0;
1726
1727int Py_AtExit(void (*func)(void))
1728{
1729 if (nexitfuncs >= NEXITFUNCS)
1730 return -1;
1731 exitfuncs[nexitfuncs++] = func;
1732 return 0;
1733}
1734
1735static void
1736call_ll_exitfuncs(void)
1737{
1738 while (nexitfuncs > 0)
1739 (*exitfuncs[--nexitfuncs])();
1740
1741 fflush(stdout);
1742 fflush(stderr);
1743}
1744
1745void
1746Py_Exit(int sts)
1747{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001748 if (Py_FinalizeEx() < 0) {
1749 sts = 120;
1750 }
Nick Coghland6009512014-11-20 21:39:37 +10001751
1752 exit(sts);
1753}
1754
1755static void
1756initsigs(void)
1757{
1758#ifdef SIGPIPE
1759 PyOS_setsig(SIGPIPE, SIG_IGN);
1760#endif
1761#ifdef SIGXFZ
1762 PyOS_setsig(SIGXFZ, SIG_IGN);
1763#endif
1764#ifdef SIGXFSZ
1765 PyOS_setsig(SIGXFSZ, SIG_IGN);
1766#endif
1767 PyOS_InitInterrupts(); /* May imply initsignal() */
1768 if (PyErr_Occurred()) {
1769 Py_FatalError("Py_Initialize: can't import signal");
1770 }
1771}
1772
1773
1774/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1775 *
1776 * All of the code in this function must only use async-signal-safe functions,
1777 * listed at `man 7 signal` or
1778 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1779 */
1780void
1781_Py_RestoreSignals(void)
1782{
1783#ifdef SIGPIPE
1784 PyOS_setsig(SIGPIPE, SIG_DFL);
1785#endif
1786#ifdef SIGXFZ
1787 PyOS_setsig(SIGXFZ, SIG_DFL);
1788#endif
1789#ifdef SIGXFSZ
1790 PyOS_setsig(SIGXFSZ, SIG_DFL);
1791#endif
1792}
1793
1794
1795/*
1796 * The file descriptor fd is considered ``interactive'' if either
1797 * a) isatty(fd) is TRUE, or
1798 * b) the -i flag was given, and the filename associated with
1799 * the descriptor is NULL or "<stdin>" or "???".
1800 */
1801int
1802Py_FdIsInteractive(FILE *fp, const char *filename)
1803{
1804 if (isatty((int)fileno(fp)))
1805 return 1;
1806 if (!Py_InteractiveFlag)
1807 return 0;
1808 return (filename == NULL) ||
1809 (strcmp(filename, "<stdin>") == 0) ||
1810 (strcmp(filename, "???") == 0);
1811}
1812
1813
Nick Coghland6009512014-11-20 21:39:37 +10001814/* Wrappers around sigaction() or signal(). */
1815
1816PyOS_sighandler_t
1817PyOS_getsig(int sig)
1818{
1819#ifdef HAVE_SIGACTION
1820 struct sigaction context;
1821 if (sigaction(sig, NULL, &context) == -1)
1822 return SIG_ERR;
1823 return context.sa_handler;
1824#else
1825 PyOS_sighandler_t handler;
1826/* Special signal handling for the secure CRT in Visual Studio 2005 */
1827#if defined(_MSC_VER) && _MSC_VER >= 1400
1828 switch (sig) {
1829 /* Only these signals are valid */
1830 case SIGINT:
1831 case SIGILL:
1832 case SIGFPE:
1833 case SIGSEGV:
1834 case SIGTERM:
1835 case SIGBREAK:
1836 case SIGABRT:
1837 break;
1838 /* Don't call signal() with other values or it will assert */
1839 default:
1840 return SIG_ERR;
1841 }
1842#endif /* _MSC_VER && _MSC_VER >= 1400 */
1843 handler = signal(sig, SIG_IGN);
1844 if (handler != SIG_ERR)
1845 signal(sig, handler);
1846 return handler;
1847#endif
1848}
1849
1850/*
1851 * All of the code in this function must only use async-signal-safe functions,
1852 * listed at `man 7 signal` or
1853 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1854 */
1855PyOS_sighandler_t
1856PyOS_setsig(int sig, PyOS_sighandler_t handler)
1857{
1858#ifdef HAVE_SIGACTION
1859 /* Some code in Modules/signalmodule.c depends on sigaction() being
1860 * used here if HAVE_SIGACTION is defined. Fix that if this code
1861 * changes to invalidate that assumption.
1862 */
1863 struct sigaction context, ocontext;
1864 context.sa_handler = handler;
1865 sigemptyset(&context.sa_mask);
1866 context.sa_flags = 0;
1867 if (sigaction(sig, &context, &ocontext) == -1)
1868 return SIG_ERR;
1869 return ocontext.sa_handler;
1870#else
1871 PyOS_sighandler_t oldhandler;
1872 oldhandler = signal(sig, handler);
1873#ifdef HAVE_SIGINTERRUPT
1874 siginterrupt(sig, 1);
1875#endif
1876 return oldhandler;
1877#endif
1878}
1879
1880#ifdef __cplusplus
1881}
1882#endif