blob: d106c45be75bb2088040b594e8f65e455e7b8dca [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);
72
73#ifdef WITH_THREAD
74extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
75extern void _PyGILState_Fini(void);
76#endif /* WITH_THREAD */
77
78/* Global configuration variable declarations are in pydebug.h */
79/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
80int Py_DebugFlag; /* Needed by parser.c */
81int Py_VerboseFlag; /* Needed by import.c */
82int Py_QuietFlag; /* Needed by sysmodule.c */
83int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
84int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
85int Py_OptimizeFlag = 0; /* Needed by compile.c */
86int Py_NoSiteFlag; /* Suppress 'import site' */
87int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
88int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
89int Py_FrozenFlag; /* Needed by getpath.c */
90int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +080091int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +100092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
93int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
94int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
95int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -070096#ifdef MS_WINDOWS
97int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -070098int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -070099#endif
Nick Coghland6009512014-11-20 21:39:37 +1000100
101PyThreadState *_Py_Finalizing = NULL;
102
103/* Hack to force loading of object files */
104int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
105 PyOS_mystrnicmp; /* Python/pystrcmp.o */
106
107/* PyModule_GetWarningsModule is no longer necessary as of 2.6
108since _warnings is builtin. This API should not be used. */
109PyObject *
110PyModule_GetWarningsModule(void)
111{
112 return PyImport_ImportModule("warnings");
113}
114
Eric Snow1abcf672017-05-23 21:46:51 -0700115/* APIs to access the initialization flags
116 *
117 * Can be called prior to Py_Initialize.
118 */
119int _Py_CoreInitialized = 0;
120int _Py_Initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000121
Eric Snow1abcf672017-05-23 21:46:51 -0700122int
123_Py_IsCoreInitialized(void)
124{
125 return _Py_CoreInitialized;
126}
Nick Coghland6009512014-11-20 21:39:37 +1000127
128int
129Py_IsInitialized(void)
130{
Eric Snow1abcf672017-05-23 21:46:51 -0700131 return _Py_Initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000132}
133
134/* Helper to allow an embedding application to override the normal
135 * mechanism that attempts to figure out an appropriate IO encoding
136 */
137
138static char *_Py_StandardStreamEncoding = NULL;
139static char *_Py_StandardStreamErrors = NULL;
140
141int
142Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
143{
144 if (Py_IsInitialized()) {
145 /* This is too late to have any effect */
146 return -1;
147 }
148 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
149 * initialised yet.
150 *
151 * However, the raw memory allocators are initialised appropriately
152 * as C static variables, so _PyMem_RawStrdup is OK even though
153 * Py_Initialize hasn't been called yet.
154 */
155 if (encoding) {
156 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
157 if (!_Py_StandardStreamEncoding) {
158 return -2;
159 }
160 }
161 if (errors) {
162 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
163 if (!_Py_StandardStreamErrors) {
164 if (_Py_StandardStreamEncoding) {
165 PyMem_RawFree(_Py_StandardStreamEncoding);
166 }
167 return -3;
168 }
169 }
Steve Dower39294992016-08-30 21:22:36 -0700170#ifdef MS_WINDOWS
171 if (_Py_StandardStreamEncoding) {
172 /* Overriding the stream encoding implies legacy streams */
173 Py_LegacyWindowsStdioFlag = 1;
174 }
175#endif
Nick Coghland6009512014-11-20 21:39:37 +1000176 return 0;
177}
178
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000179/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
180 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000181 initializations fail, a fatal error is issued and the function does
182 not return. On return, the first thread and interpreter state have
183 been created.
184
185 Locking: you must hold the interpreter lock while calling this.
186 (If the lock has not yet been initialized, that's equivalent to
187 having the lock, but you cannot use multiple threads.)
188
189*/
190
191static int
192add_flag(int flag, const char *envs)
193{
194 int env = atoi(envs);
195 if (flag < env)
196 flag = env;
197 if (flag < 1)
198 flag = 1;
199 return flag;
200}
201
202static char*
203get_codec_name(const char *encoding)
204{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200205 const char *name_utf8;
206 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000207 PyObject *codec, *name = NULL;
208
209 codec = _PyCodec_Lookup(encoding);
210 if (!codec)
211 goto error;
212
213 name = _PyObject_GetAttrId(codec, &PyId_name);
214 Py_CLEAR(codec);
215 if (!name)
216 goto error;
217
Serhiy Storchaka06515832016-11-20 09:13:07 +0200218 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000219 if (name_utf8 == NULL)
220 goto error;
221 name_str = _PyMem_RawStrdup(name_utf8);
222 Py_DECREF(name);
223 if (name_str == NULL) {
224 PyErr_NoMemory();
225 return NULL;
226 }
227 return name_str;
228
229error:
230 Py_XDECREF(codec);
231 Py_XDECREF(name);
232 return NULL;
233}
234
235static char*
236get_locale_encoding(void)
237{
238#ifdef MS_WINDOWS
239 char codepage[100];
240 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
241 return get_codec_name(codepage);
242#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
243 char* codeset = nl_langinfo(CODESET);
244 if (!codeset || codeset[0] == '\0') {
245 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
246 return NULL;
247 }
248 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200249#elif defined(__ANDROID__)
250 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000251#else
252 PyErr_SetNone(PyExc_NotImplementedError);
253 return NULL;
254#endif
255}
256
257static void
Eric Snow1abcf672017-05-23 21:46:51 -0700258initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000259{
260 PyObject *importlib;
261 PyObject *impmod;
262 PyObject *sys_modules;
263 PyObject *value;
264
265 /* Import _importlib through its frozen version, _frozen_importlib. */
266 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
267 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
268 }
269 else if (Py_VerboseFlag) {
270 PySys_FormatStderr("import _frozen_importlib # frozen\n");
271 }
272 importlib = PyImport_AddModule("_frozen_importlib");
273 if (importlib == NULL) {
274 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
275 "sys.modules");
276 }
277 interp->importlib = importlib;
278 Py_INCREF(interp->importlib);
279
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300280 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
281 if (interp->import_func == NULL)
282 Py_FatalError("Py_Initialize: __import__ not found");
283 Py_INCREF(interp->import_func);
284
Victor Stinnercd6e6942015-09-18 09:11:57 +0200285 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000286 impmod = PyInit_imp();
287 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200288 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000289 }
290 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200291 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000292 }
293 sys_modules = PyImport_GetModuleDict();
294 if (Py_VerboseFlag) {
295 PySys_FormatStderr("import sys # builtin\n");
296 }
297 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
298 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
299 }
300
Victor Stinnercd6e6942015-09-18 09:11:57 +0200301 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000302 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Eric Snow6b4be192017-05-22 21:36:03 -0700303 if (value != NULL)
304 value = PyObject_CallMethod(importlib,
305 "_install_external_importers", "");
Nick Coghland6009512014-11-20 21:39:37 +1000306 if (value == NULL) {
307 PyErr_Print();
308 Py_FatalError("Py_Initialize: importlib install failed");
309 }
310 Py_DECREF(value);
311 Py_DECREF(impmod);
312
313 _PyImportZip_Init();
314}
315
Eric Snow1abcf672017-05-23 21:46:51 -0700316static void
317initexternalimport(PyInterpreterState *interp)
318{
319 PyObject *value;
320 value = PyObject_CallMethod(interp->importlib,
321 "_install_external_importers", "");
322 if (value == NULL) {
323 PyErr_Print();
324 Py_FatalError("Py_EndInitialization: external importer setup failed");
325 }
326}
Nick Coghland6009512014-11-20 21:39:37 +1000327
Eric Snow1abcf672017-05-23 21:46:51 -0700328
329/* Global initializations. Can be undone by Py_Finalize(). Don't
330 call this twice without an intervening Py_Finalize() call.
331
332 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
333 must have a corresponding call to Py_Finalize.
334
335 Locking: you must hold the interpreter lock while calling these APIs.
336 (If the lock has not yet been initialized, that's equivalent to
337 having the lock, but you cannot use multiple threads.)
338
339*/
340
341/* Begin interpreter initialization
342 *
343 * On return, the first thread and interpreter state have been created,
344 * but the compiler, signal handling, multithreading and
345 * multiple interpreter support, and codec infrastructure are not yet
346 * available.
347 *
348 * The import system will support builtin and frozen modules only.
349 * The only supported io is writing to sys.stderr
350 *
351 * If any operation invoked by this function fails, a fatal error is
352 * issued and the function does not return.
353 *
354 * Any code invoked from this function should *not* assume it has access
355 * to the Python C API (unless the API is explicitly listed as being
356 * safe to call without calling Py_Initialize first)
357 */
358
359/* TODO: Progresively move functionality from Py_BeginInitialization to
360 * Py_ReadConfig and Py_EndInitialization
361 */
362
363void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000364{
365 PyInterpreterState *interp;
366 PyThreadState *tstate;
367 PyObject *bimod, *sysmod, *pstderr;
368 char *p;
369 extern void _Py_ReadyTypes(void);
Eric Snow1abcf672017-05-23 21:46:51 -0700370 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000371
Eric Snow1abcf672017-05-23 21:46:51 -0700372 if (config != NULL) {
373 core_config = *config;
374 }
375
376 if (_Py_Initialized) {
377 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
378 }
379 if (_Py_CoreInitialized) {
380 Py_FatalError("Py_InitializeCore: runtime core already initialized");
381 }
382
383 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
384 * threads behave a little more gracefully at interpreter shutdown.
385 * We clobber it here so the new interpreter can start with a clean
386 * slate.
387 *
388 * However, this may still lead to misbehaviour if there are daemon
389 * threads still hanging around from a previous Py_Initialize/Finalize
390 * pair :(
391 */
Nick Coghland6009512014-11-20 21:39:37 +1000392 _Py_Finalizing = NULL;
393
Xavier de Gayeb445ad72016-11-16 07:24:20 +0100394#ifdef HAVE_SETLOCALE
Nick Coghland6009512014-11-20 21:39:37 +1000395 /* Set up the LC_CTYPE locale, so we can obtain
396 the locale's charset without having to switch
397 locales. */
398 setlocale(LC_CTYPE, "");
399#endif
400
401 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
402 Py_DebugFlag = add_flag(Py_DebugFlag, p);
403 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
404 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
405 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
406 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
407 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
408 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700409 /* The variable is only tested for existence here;
410 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000411 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
412 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700413#ifdef MS_WINDOWS
414 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
415 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700416 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
417 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700418#endif
Nick Coghland6009512014-11-20 21:39:37 +1000419
Eric Snow1abcf672017-05-23 21:46:51 -0700420 _Py_HashRandomization_Init(&core_config);
421 if (!core_config.use_hash_seed || core_config.hash_seed) {
422 /* Random or non-zero hash seed */
423 Py_HashRandomizationFlag = 1;
424 }
Nick Coghland6009512014-11-20 21:39:37 +1000425
Eric Snowe3774162017-05-22 19:46:40 -0700426 _PyInterpreterState_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000427 interp = PyInterpreterState_New();
428 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700429 Py_FatalError("Py_InitializeCore: can't make main interpreter");
430 interp->core_config = core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000431
432 tstate = PyThreadState_New(interp);
433 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700434 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000435 (void) PyThreadState_Swap(tstate);
436
437#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000438 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000439 destroying the GIL might fail when it is being referenced from
440 another running thread (see issue #9901).
441 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000442 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000443 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000444 /* Auto-thread-state API */
445 _PyGILState_Init(interp, tstate);
446#endif /* WITH_THREAD */
447
448 _Py_ReadyTypes();
449
450 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700451 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000452
453 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700454 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000455
456 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700457 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000458
459 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700460 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000461
462 interp->modules = PyDict_New();
463 if (interp->modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700464 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000465
466 /* Init Unicode implementation; relies on the codec registry */
467 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700468 Py_FatalError("Py_InitializeCore: can't initialize unicode");
469
Nick Coghland6009512014-11-20 21:39:37 +1000470 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700471 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000472
473 bimod = _PyBuiltin_Init();
474 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700475 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Nick Coghland6009512014-11-20 21:39:37 +1000476 _PyImport_FixupBuiltin(bimod, "builtins");
477 interp->builtins = PyModule_GetDict(bimod);
478 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700479 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000480 Py_INCREF(interp->builtins);
481
482 /* initialize builtin exceptions */
483 _PyExc_Init(bimod);
484
Eric Snow6b4be192017-05-22 21:36:03 -0700485 sysmod = _PySys_BeginInit();
Nick Coghland6009512014-11-20 21:39:37 +1000486 if (sysmod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700487 Py_FatalError("Py_InitializeCore: can't initialize sys");
Nick Coghland6009512014-11-20 21:39:37 +1000488 interp->sysdict = PyModule_GetDict(sysmod);
489 if (interp->sysdict == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700490 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
Nick Coghland6009512014-11-20 21:39:37 +1000491 Py_INCREF(interp->sysdict);
492 _PyImport_FixupBuiltin(sysmod, "sys");
Nick Coghland6009512014-11-20 21:39:37 +1000493 PyDict_SetItemString(interp->sysdict, "modules",
494 interp->modules);
495
496 /* Set up a preliminary stderr printer until we have enough
497 infrastructure for the io module in place. */
498 pstderr = PyFile_NewStdPrinter(fileno(stderr));
499 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700500 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000501 _PySys_SetObjectId(&PyId_stderr, pstderr);
502 PySys_SetObject("__stderr__", pstderr);
503 Py_DECREF(pstderr);
504
505 _PyImport_Init();
506
507 _PyImportHooks_Init();
508
509 /* Initialize _warnings. */
510 _PyWarnings_Init();
511
Eric Snow1abcf672017-05-23 21:46:51 -0700512 /* This call sets up builtin and frozen import support */
513 if (!interp->core_config._disable_importlib) {
514 initimport(interp, sysmod);
515 }
516
517 /* Only when we get here is the runtime core fully initialized */
518 _Py_CoreInitialized = 1;
519}
520
521int
522_Py_InitializeMainInterpreter(int install_sigs)
523{
524 PyInterpreterState *interp;
525 PyThreadState *tstate;
526
527 /* Get current thread state and interpreter pointer */
528 tstate = PyThreadState_GET();
529 if (!tstate)
530 Py_FatalError("Py_Initialize: failed to read thread state");
531 interp = tstate->interp;
532 if (!interp)
533 Py_FatalError("Py_Initialize: failed to get interpreter");
534
535 /* Now finish configuring the main interpreter */
536 if (interp->core_config._disable_importlib) {
537 /* Special mode for freeze_importlib: run with no import system
538 *
539 * This means anything which needs support from extension modules
540 * or pure Python code in the standard library won't work.
541 */
542 _Py_Initialized = 1;
543 return 0;
544 }
545 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000546
Victor Stinner13019fd2015-04-03 13:10:54 +0200547 if (_PyTime_Init() < 0)
548 Py_FatalError("Py_Initialize: can't initialize time");
549
Eric Snow1abcf672017-05-23 21:46:51 -0700550 /* Finish setting up the sys module and import system */
551 /* GetPath may initialize state that _PySys_EndInit locks
552 in, and so has to be called first. */
553 PySys_SetPath(Py_GetPath());
554 if (_PySys_EndInit(interp->sysdict) < 0)
555 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
556 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
557 PySys_SetPath(Py_GetPath());
558 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000559
560 /* initialize the faulthandler module */
561 if (_PyFaulthandler_Init())
562 Py_FatalError("Py_Initialize: can't initialize faulthandler");
563
Nick Coghland6009512014-11-20 21:39:37 +1000564 if (initfsencoding(interp) < 0)
565 Py_FatalError("Py_Initialize: unable to load the file system codec");
566
567 if (install_sigs)
568 initsigs(); /* Signal handling stuff, including initintr() */
569
570 if (_PyTraceMalloc_Init() < 0)
571 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
572
573 initmain(interp); /* Module __main__ */
574 if (initstdio() < 0)
575 Py_FatalError(
576 "Py_Initialize: can't initialize sys standard streams");
577
578 /* Initialize warnings. */
579 if (PySys_HasWarnOptions()) {
580 PyObject *warnings_module = PyImport_ImportModule("warnings");
581 if (warnings_module == NULL) {
582 fprintf(stderr, "'import warnings' failed; traceback:\n");
583 PyErr_Print();
584 }
585 Py_XDECREF(warnings_module);
586 }
587
Eric Snow1abcf672017-05-23 21:46:51 -0700588 _Py_Initialized = 1;
589
Nick Coghland6009512014-11-20 21:39:37 +1000590 if (!Py_NoSiteFlag)
591 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700592
593 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000594}
595
596void
Eric Snow1abcf672017-05-23 21:46:51 -0700597_Py_InitializeEx_Private(int install_sigs, int install_importlib)
598{
599 _PyCoreConfig core_config = _PyCoreConfig_INIT;
600
601 /* TODO: Moar config options! */
602 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
603 core_config._disable_importlib = !install_importlib;
604 _Py_InitializeCore(&core_config);
605 _Py_InitializeMainInterpreter(install_sigs);
606}
607
608
609void
Nick Coghland6009512014-11-20 21:39:37 +1000610Py_InitializeEx(int install_sigs)
611{
612 _Py_InitializeEx_Private(install_sigs, 1);
613}
614
615void
616Py_Initialize(void)
617{
618 Py_InitializeEx(1);
619}
620
621
622#ifdef COUNT_ALLOCS
623extern void dump_counts(FILE*);
624#endif
625
626/* Flush stdout and stderr */
627
628static int
629file_is_closed(PyObject *fobj)
630{
631 int r;
632 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
633 if (tmp == NULL) {
634 PyErr_Clear();
635 return 0;
636 }
637 r = PyObject_IsTrue(tmp);
638 Py_DECREF(tmp);
639 if (r < 0)
640 PyErr_Clear();
641 return r > 0;
642}
643
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000644static int
Nick Coghland6009512014-11-20 21:39:37 +1000645flush_std_files(void)
646{
647 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
648 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
649 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000650 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000651
652 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700653 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000654 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000655 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000656 status = -1;
657 }
Nick Coghland6009512014-11-20 21:39:37 +1000658 else
659 Py_DECREF(tmp);
660 }
661
662 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700663 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000664 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000665 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000666 status = -1;
667 }
Nick Coghland6009512014-11-20 21:39:37 +1000668 else
669 Py_DECREF(tmp);
670 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000671
672 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000673}
674
675/* Undo the effect of Py_Initialize().
676
677 Beware: if multiple interpreter and/or thread states exist, these
678 are not wiped out; only the current thread and interpreter state
679 are deleted. But since everything else is deleted, those other
680 interpreter and thread states should no longer be used.
681
682 (XXX We should do better, e.g. wipe out all interpreters and
683 threads.)
684
685 Locking: as above.
686
687*/
688
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000689int
690Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000691{
692 PyInterpreterState *interp;
693 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000694 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000695
Eric Snow1abcf672017-05-23 21:46:51 -0700696 if (!_Py_Initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000697 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000698
699 wait_for_thread_shutdown();
700
701 /* The interpreter is still entirely intact at this point, and the
702 * exit funcs may be relying on that. In particular, if some thread
703 * or exit func is still waiting to do an import, the import machinery
704 * expects Py_IsInitialized() to return true. So don't say the
705 * interpreter is uninitialized until after the exit funcs have run.
706 * Note that Threading.py uses an exit func to do a join on all the
707 * threads created thru it, so this also protects pending imports in
708 * the threads created via Threading.
709 */
710 call_py_exitfuncs();
711
712 /* Get current thread state and interpreter pointer */
713 tstate = PyThreadState_GET();
714 interp = tstate->interp;
715
716 /* Remaining threads (e.g. daemon threads) will automatically exit
717 after taking the GIL (in PyEval_RestoreThread()). */
718 _Py_Finalizing = tstate;
Eric Snow1abcf672017-05-23 21:46:51 -0700719 _Py_Initialized = 0;
720 _Py_CoreInitialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000721
Victor Stinnere0deff32015-03-24 13:46:18 +0100722 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000723 if (flush_std_files() < 0) {
724 status = -1;
725 }
Nick Coghland6009512014-11-20 21:39:37 +1000726
727 /* Disable signal handling */
728 PyOS_FiniInterrupts();
729
730 /* Collect garbage. This may call finalizers; it's nice to call these
731 * before all modules are destroyed.
732 * XXX If a __del__ or weakref callback is triggered here, and tries to
733 * XXX import a module, bad things can happen, because Python no
734 * XXX longer believes it's initialized.
735 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
736 * XXX is easy to provoke that way. I've also seen, e.g.,
737 * XXX Exception exceptions.ImportError: 'No module named sha'
738 * XXX in <function callback at 0x008F5718> ignored
739 * XXX but I'm unclear on exactly how that one happens. In any case,
740 * XXX I haven't seen a real-life report of either of these.
741 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700742 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000743#ifdef COUNT_ALLOCS
744 /* With COUNT_ALLOCS, it helps to run GC multiple times:
745 each collection might release some types from the type
746 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700747 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000748 /* nothing */;
749#endif
750 /* Destroy all modules */
751 PyImport_Cleanup();
752
Victor Stinnere0deff32015-03-24 13:46:18 +0100753 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000754 if (flush_std_files() < 0) {
755 status = -1;
756 }
Nick Coghland6009512014-11-20 21:39:37 +1000757
758 /* Collect final garbage. This disposes of cycles created by
759 * class definitions, for example.
760 * XXX This is disabled because it caused too many problems. If
761 * XXX a __del__ or weakref callback triggers here, Python code has
762 * XXX a hard time running, because even the sys module has been
763 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
764 * XXX One symptom is a sequence of information-free messages
765 * XXX coming from threads (if a __del__ or callback is invoked,
766 * XXX other threads can execute too, and any exception they encounter
767 * XXX triggers a comedy of errors as subsystem after subsystem
768 * XXX fails to find what it *expects* to find in sys to help report
769 * XXX the exception and consequent unexpected failures). I've also
770 * XXX seen segfaults then, after adding print statements to the
771 * XXX Python code getting called.
772 */
773#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -0700774 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000775#endif
776
777 /* Disable tracemalloc after all Python objects have been destroyed,
778 so it is possible to use tracemalloc in objects destructor. */
779 _PyTraceMalloc_Fini();
780
781 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
782 _PyImport_Fini();
783
784 /* Cleanup typeobject.c's internal caches. */
785 _PyType_Fini();
786
787 /* unload faulthandler module */
788 _PyFaulthandler_Fini();
789
790 /* Debugging stuff */
791#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +0300792 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +1000793#endif
794 /* dump hash stats */
795 _PyHash_Fini();
796
797 _PY_DEBUG_PRINT_TOTAL_REFS();
798
799#ifdef Py_TRACE_REFS
800 /* Display all objects still alive -- this can invoke arbitrary
801 * __repr__ overrides, so requires a mostly-intact interpreter.
802 * Alas, a lot of stuff may still be alive now that will be cleaned
803 * up later.
804 */
805 if (Py_GETENV("PYTHONDUMPREFS"))
806 _Py_PrintReferences(stderr);
807#endif /* Py_TRACE_REFS */
808
809 /* Clear interpreter state and all thread states. */
810 PyInterpreterState_Clear(interp);
811
812 /* Now we decref the exception classes. After this point nothing
813 can raise an exception. That's okay, because each Fini() method
814 below has been checked to make sure no exceptions are ever
815 raised.
816 */
817
818 _PyExc_Fini();
819
820 /* Sundry finalizers */
821 PyMethod_Fini();
822 PyFrame_Fini();
823 PyCFunction_Fini();
824 PyTuple_Fini();
825 PyList_Fini();
826 PySet_Fini();
827 PyBytes_Fini();
828 PyByteArray_Fini();
829 PyLong_Fini();
830 PyFloat_Fini();
831 PyDict_Fini();
832 PySlice_Fini();
833 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -0700834 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +0300835 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -0700836 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +1000837
838 /* Cleanup Unicode implementation */
839 _PyUnicode_Fini();
840
841 /* reset file system default encoding */
842 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
843 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
844 Py_FileSystemDefaultEncoding = NULL;
845 }
846
847 /* XXX Still allocated:
848 - various static ad-hoc pointers to interned strings
849 - int and float free list blocks
850 - whatever various modules and libraries allocate
851 */
852
853 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
854
855 /* Cleanup auto-thread-state */
856#ifdef WITH_THREAD
857 _PyGILState_Fini();
858#endif /* WITH_THREAD */
859
860 /* Delete current thread. After this, many C API calls become crashy. */
861 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +0100862
Nick Coghland6009512014-11-20 21:39:37 +1000863 PyInterpreterState_Delete(interp);
864
865#ifdef Py_TRACE_REFS
866 /* Display addresses (& refcnts) of all objects still alive.
867 * An address can be used to find the repr of the object, printed
868 * above by _Py_PrintReferences.
869 */
870 if (Py_GETENV("PYTHONDUMPREFS"))
871 _Py_PrintReferenceAddresses(stderr);
872#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +0100873#ifdef WITH_PYMALLOC
874 if (_PyMem_PymallocEnabled()) {
875 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
876 if (opt != NULL && *opt != '\0')
877 _PyObject_DebugMallocStats(stderr);
878 }
Nick Coghland6009512014-11-20 21:39:37 +1000879#endif
880
881 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000882 return status;
883}
884
885void
886Py_Finalize(void)
887{
888 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +1000889}
890
891/* Create and initialize a new interpreter and thread, and return the
892 new thread. This requires that Py_Initialize() has been called
893 first.
894
895 Unsuccessful initialization yields a NULL pointer. Note that *no*
896 exception information is available even in this case -- the
897 exception information is held in the thread, and there is no
898 thread.
899
900 Locking: as above.
901
902*/
903
904PyThreadState *
905Py_NewInterpreter(void)
906{
907 PyInterpreterState *interp;
908 PyThreadState *tstate, *save_tstate;
909 PyObject *bimod, *sysmod;
910
Eric Snow1abcf672017-05-23 21:46:51 -0700911 if (!_Py_Initialized)
Nick Coghland6009512014-11-20 21:39:37 +1000912 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
913
Victor Stinnerd7292b52016-06-17 12:29:00 +0200914#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +0100915 /* Issue #10915, #15751: The GIL API doesn't work with multiple
916 interpreters: disable PyGILState_Check(). */
917 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +0300918#endif
Victor Stinner8a1be612016-03-14 22:07:55 +0100919
Nick Coghland6009512014-11-20 21:39:37 +1000920 interp = PyInterpreterState_New();
921 if (interp == NULL)
922 return NULL;
923
924 tstate = PyThreadState_New(interp);
925 if (tstate == NULL) {
926 PyInterpreterState_Delete(interp);
927 return NULL;
928 }
929
930 save_tstate = PyThreadState_Swap(tstate);
931
Eric Snow1abcf672017-05-23 21:46:51 -0700932 /* Copy the current interpreter config into the new interpreter */
933 if (save_tstate != NULL) {
934 interp->core_config = save_tstate->interp->core_config;
935 } else {
936 /* No current thread state, copy from the main interpreter */
937 PyInterpreterState *main_interp = PyInterpreterState_Main();
938 interp->core_config = main_interp->core_config;
939 }
940
Nick Coghland6009512014-11-20 21:39:37 +1000941 /* XXX The following is lax in error checking */
942
943 interp->modules = PyDict_New();
944
945 bimod = _PyImport_FindBuiltin("builtins");
946 if (bimod != NULL) {
947 interp->builtins = PyModule_GetDict(bimod);
948 if (interp->builtins == NULL)
949 goto handle_error;
950 Py_INCREF(interp->builtins);
951 }
952
953 /* initialize builtin exceptions */
954 _PyExc_Init(bimod);
955
956 sysmod = _PyImport_FindBuiltin("sys");
957 if (bimod != NULL && sysmod != NULL) {
958 PyObject *pstderr;
959
960 interp->sysdict = PyModule_GetDict(sysmod);
961 if (interp->sysdict == NULL)
962 goto handle_error;
963 Py_INCREF(interp->sysdict);
Eric Snow1abcf672017-05-23 21:46:51 -0700964 _PySys_EndInit(interp->sysdict);
Nick Coghland6009512014-11-20 21:39:37 +1000965 PySys_SetPath(Py_GetPath());
966 PyDict_SetItemString(interp->sysdict, "modules",
967 interp->modules);
968 /* Set up a preliminary stderr printer until we have enough
969 infrastructure for the io module in place. */
970 pstderr = PyFile_NewStdPrinter(fileno(stderr));
971 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700972 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000973 _PySys_SetObjectId(&PyId_stderr, pstderr);
974 PySys_SetObject("__stderr__", pstderr);
975 Py_DECREF(pstderr);
976
977 _PyImportHooks_Init();
978
Eric Snow1abcf672017-05-23 21:46:51 -0700979 initimport(interp, sysmod);
980 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000981
982 if (initfsencoding(interp) < 0)
983 goto handle_error;
984
985 if (initstdio() < 0)
986 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -0700987 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000988 initmain(interp);
989 if (!Py_NoSiteFlag)
990 initsite();
991 }
992
993 if (!PyErr_Occurred())
994 return tstate;
995
996handle_error:
997 /* Oops, it didn't work. Undo it all. */
998
999 PyErr_PrintEx(0);
1000 PyThreadState_Clear(tstate);
1001 PyThreadState_Swap(save_tstate);
1002 PyThreadState_Delete(tstate);
1003 PyInterpreterState_Delete(interp);
1004
1005 return NULL;
1006}
1007
1008/* Delete an interpreter and its last thread. This requires that the
1009 given thread state is current, that the thread has no remaining
1010 frames, and that it is its interpreter's only remaining thread.
1011 It is a fatal error to violate these constraints.
1012
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001013 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001014 everything, regardless.)
1015
1016 Locking: as above.
1017
1018*/
1019
1020void
1021Py_EndInterpreter(PyThreadState *tstate)
1022{
1023 PyInterpreterState *interp = tstate->interp;
1024
1025 if (tstate != PyThreadState_GET())
1026 Py_FatalError("Py_EndInterpreter: thread is not current");
1027 if (tstate->frame != NULL)
1028 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1029
1030 wait_for_thread_shutdown();
1031
1032 if (tstate != interp->tstate_head || tstate->next != NULL)
1033 Py_FatalError("Py_EndInterpreter: not the last thread");
1034
1035 PyImport_Cleanup();
1036 PyInterpreterState_Clear(interp);
1037 PyThreadState_Swap(NULL);
1038 PyInterpreterState_Delete(interp);
1039}
1040
1041#ifdef MS_WINDOWS
1042static wchar_t *progname = L"python";
1043#else
1044static wchar_t *progname = L"python3";
1045#endif
1046
1047void
1048Py_SetProgramName(wchar_t *pn)
1049{
1050 if (pn && *pn)
1051 progname = pn;
1052}
1053
1054wchar_t *
1055Py_GetProgramName(void)
1056{
1057 return progname;
1058}
1059
1060static wchar_t *default_home = NULL;
1061static wchar_t env_home[MAXPATHLEN+1];
1062
1063void
1064Py_SetPythonHome(wchar_t *home)
1065{
1066 default_home = home;
1067}
1068
1069wchar_t *
1070Py_GetPythonHome(void)
1071{
1072 wchar_t *home = default_home;
1073 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1074 char* chome = Py_GETENV("PYTHONHOME");
1075 if (chome) {
1076 size_t size = Py_ARRAY_LENGTH(env_home);
1077 size_t r = mbstowcs(env_home, chome, size);
1078 if (r != (size_t)-1 && r < size)
1079 home = env_home;
1080 }
1081
1082 }
1083 return home;
1084}
1085
1086/* Create __main__ module */
1087
1088static void
1089initmain(PyInterpreterState *interp)
1090{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001091 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001092 m = PyImport_AddModule("__main__");
1093 if (m == NULL)
1094 Py_FatalError("can't create __main__ module");
1095 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001096 ann_dict = PyDict_New();
1097 if ((ann_dict == NULL) ||
1098 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1099 Py_FatalError("Failed to initialize __main__.__annotations__");
1100 }
1101 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001102 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1103 PyObject *bimod = PyImport_ImportModule("builtins");
1104 if (bimod == NULL) {
1105 Py_FatalError("Failed to retrieve builtins module");
1106 }
1107 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1108 Py_FatalError("Failed to initialize __main__.__builtins__");
1109 }
1110 Py_DECREF(bimod);
1111 }
1112 /* Main is a little special - imp.is_builtin("__main__") will return
1113 * False, but BuiltinImporter is still the most appropriate initial
1114 * setting for its __loader__ attribute. A more suitable value will
1115 * be set if __main__ gets further initialized later in the startup
1116 * process.
1117 */
1118 loader = PyDict_GetItemString(d, "__loader__");
1119 if (loader == NULL || loader == Py_None) {
1120 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1121 "BuiltinImporter");
1122 if (loader == NULL) {
1123 Py_FatalError("Failed to retrieve BuiltinImporter");
1124 }
1125 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1126 Py_FatalError("Failed to initialize __main__.__loader__");
1127 }
1128 Py_DECREF(loader);
1129 }
1130}
1131
1132static int
1133initfsencoding(PyInterpreterState *interp)
1134{
1135 PyObject *codec;
1136
Steve Dowercc16be82016-09-08 10:35:16 -07001137#ifdef MS_WINDOWS
1138 if (Py_LegacyWindowsFSEncodingFlag)
1139 {
1140 Py_FileSystemDefaultEncoding = "mbcs";
1141 Py_FileSystemDefaultEncodeErrors = "replace";
1142 }
1143 else
1144 {
1145 Py_FileSystemDefaultEncoding = "utf-8";
1146 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1147 }
1148#else
Nick Coghland6009512014-11-20 21:39:37 +10001149 if (Py_FileSystemDefaultEncoding == NULL)
1150 {
1151 Py_FileSystemDefaultEncoding = get_locale_encoding();
1152 if (Py_FileSystemDefaultEncoding == NULL)
1153 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1154
1155 Py_HasFileSystemDefaultEncoding = 0;
1156 interp->fscodec_initialized = 1;
1157 return 0;
1158 }
Steve Dowercc16be82016-09-08 10:35:16 -07001159#endif
Nick Coghland6009512014-11-20 21:39:37 +10001160
1161 /* the encoding is mbcs, utf-8 or ascii */
1162 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1163 if (!codec) {
1164 /* Such error can only occurs in critical situations: no more
1165 * memory, import a module of the standard library failed,
1166 * etc. */
1167 return -1;
1168 }
1169 Py_DECREF(codec);
1170 interp->fscodec_initialized = 1;
1171 return 0;
1172}
1173
1174/* Import the site module (not into __main__ though) */
1175
1176static void
1177initsite(void)
1178{
1179 PyObject *m;
1180 m = PyImport_ImportModule("site");
1181 if (m == NULL) {
1182 fprintf(stderr, "Failed to import the site module\n");
1183 PyErr_Print();
1184 Py_Finalize();
1185 exit(1);
1186 }
1187 else {
1188 Py_DECREF(m);
1189 }
1190}
1191
Victor Stinner874dbe82015-09-04 17:29:57 +02001192/* Check if a file descriptor is valid or not.
1193 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1194static int
1195is_valid_fd(int fd)
1196{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001197#ifdef __APPLE__
1198 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1199 and the other side of the pipe is closed, dup(1) succeed, whereas
1200 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1201 such error. */
1202 struct stat st;
1203 return (fstat(fd, &st) == 0);
1204#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001205 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001206 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001207 return 0;
1208 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001209 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1210 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1211 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001212 fd2 = dup(fd);
1213 if (fd2 >= 0)
1214 close(fd2);
1215 _Py_END_SUPPRESS_IPH
1216 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001217#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001218}
1219
1220/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001221static PyObject*
1222create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001223 int fd, int write_mode, const char* name,
1224 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001225{
1226 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1227 const char* mode;
1228 const char* newline;
1229 PyObject *line_buffering;
1230 int buffering, isatty;
1231 _Py_IDENTIFIER(open);
1232 _Py_IDENTIFIER(isatty);
1233 _Py_IDENTIFIER(TextIOWrapper);
1234 _Py_IDENTIFIER(mode);
1235
Victor Stinner874dbe82015-09-04 17:29:57 +02001236 if (!is_valid_fd(fd))
1237 Py_RETURN_NONE;
1238
Nick Coghland6009512014-11-20 21:39:37 +10001239 /* stdin is always opened in buffered mode, first because it shouldn't
1240 make a difference in common use cases, second because TextIOWrapper
1241 depends on the presence of a read1() method which only exists on
1242 buffered streams.
1243 */
1244 if (Py_UnbufferedStdioFlag && write_mode)
1245 buffering = 0;
1246 else
1247 buffering = -1;
1248 if (write_mode)
1249 mode = "wb";
1250 else
1251 mode = "rb";
1252 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1253 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001254 Py_None, Py_None, /* encoding, errors */
1255 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001256 if (buf == NULL)
1257 goto error;
1258
1259 if (buffering) {
1260 _Py_IDENTIFIER(raw);
1261 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1262 if (raw == NULL)
1263 goto error;
1264 }
1265 else {
1266 raw = buf;
1267 Py_INCREF(raw);
1268 }
1269
Steve Dower39294992016-08-30 21:22:36 -07001270#ifdef MS_WINDOWS
1271 /* Windows console IO is always UTF-8 encoded */
1272 if (PyWindowsConsoleIO_Check(raw))
1273 encoding = "utf-8";
1274#endif
1275
Nick Coghland6009512014-11-20 21:39:37 +10001276 text = PyUnicode_FromString(name);
1277 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1278 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001279 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001280 if (res == NULL)
1281 goto error;
1282 isatty = PyObject_IsTrue(res);
1283 Py_DECREF(res);
1284 if (isatty == -1)
1285 goto error;
1286 if (isatty || Py_UnbufferedStdioFlag)
1287 line_buffering = Py_True;
1288 else
1289 line_buffering = Py_False;
1290
1291 Py_CLEAR(raw);
1292 Py_CLEAR(text);
1293
1294#ifdef MS_WINDOWS
1295 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1296 newlines to "\n".
1297 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1298 newline = NULL;
1299#else
1300 /* sys.stdin: split lines at "\n".
1301 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1302 newline = "\n";
1303#endif
1304
1305 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1306 buf, encoding, errors,
1307 newline, line_buffering);
1308 Py_CLEAR(buf);
1309 if (stream == NULL)
1310 goto error;
1311
1312 if (write_mode)
1313 mode = "w";
1314 else
1315 mode = "r";
1316 text = PyUnicode_FromString(mode);
1317 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1318 goto error;
1319 Py_CLEAR(text);
1320 return stream;
1321
1322error:
1323 Py_XDECREF(buf);
1324 Py_XDECREF(stream);
1325 Py_XDECREF(text);
1326 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001327
Victor Stinner874dbe82015-09-04 17:29:57 +02001328 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1329 /* Issue #24891: the file descriptor was closed after the first
1330 is_valid_fd() check was called. Ignore the OSError and set the
1331 stream to None. */
1332 PyErr_Clear();
1333 Py_RETURN_NONE;
1334 }
1335 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001336}
1337
1338/* Initialize sys.stdin, stdout, stderr and builtins.open */
1339static int
1340initstdio(void)
1341{
1342 PyObject *iomod = NULL, *wrapper;
1343 PyObject *bimod = NULL;
1344 PyObject *m;
1345 PyObject *std = NULL;
1346 int status = 0, fd;
1347 PyObject * encoding_attr;
1348 char *pythonioencoding = NULL, *encoding, *errors;
1349
1350 /* Hack to avoid a nasty recursion issue when Python is invoked
1351 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1352 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1353 goto error;
1354 }
1355 Py_DECREF(m);
1356
1357 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1358 goto error;
1359 }
1360 Py_DECREF(m);
1361
1362 if (!(bimod = PyImport_ImportModule("builtins"))) {
1363 goto error;
1364 }
1365
1366 if (!(iomod = PyImport_ImportModule("io"))) {
1367 goto error;
1368 }
1369 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1370 goto error;
1371 }
1372
1373 /* Set builtins.open */
1374 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1375 Py_DECREF(wrapper);
1376 goto error;
1377 }
1378 Py_DECREF(wrapper);
1379
1380 encoding = _Py_StandardStreamEncoding;
1381 errors = _Py_StandardStreamErrors;
1382 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001383 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1384 if (pythonioencoding) {
1385 char *err;
1386 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1387 if (pythonioencoding == NULL) {
1388 PyErr_NoMemory();
1389 goto error;
1390 }
1391 err = strchr(pythonioencoding, ':');
1392 if (err) {
1393 *err = '\0';
1394 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001395 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001396 errors = err;
1397 }
1398 }
1399 if (*pythonioencoding && !encoding) {
1400 encoding = pythonioencoding;
1401 }
1402 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001403 if (!errors && !(pythonioencoding && *pythonioencoding)) {
1404 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1405 stdin and stdout use the surrogateescape error handler by
1406 default, instead of the strict error handler. */
1407 char *loc = setlocale(LC_CTYPE, NULL);
1408 if (loc != NULL && strcmp(loc, "C") == 0)
1409 errors = "surrogateescape";
1410 }
Nick Coghland6009512014-11-20 21:39:37 +10001411 }
1412
1413 /* Set sys.stdin */
1414 fd = fileno(stdin);
1415 /* Under some conditions stdin, stdout and stderr may not be connected
1416 * and fileno() may point to an invalid file descriptor. For example
1417 * GUI apps don't have valid standard streams by default.
1418 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001419 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1420 if (std == NULL)
1421 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001422 PySys_SetObject("__stdin__", std);
1423 _PySys_SetObjectId(&PyId_stdin, std);
1424 Py_DECREF(std);
1425
1426 /* Set sys.stdout */
1427 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001428 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1429 if (std == NULL)
1430 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001431 PySys_SetObject("__stdout__", std);
1432 _PySys_SetObjectId(&PyId_stdout, std);
1433 Py_DECREF(std);
1434
1435#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1436 /* Set sys.stderr, replaces the preliminary stderr */
1437 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001438 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1439 if (std == NULL)
1440 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001441
1442 /* Same as hack above, pre-import stderr's codec to avoid recursion
1443 when import.c tries to write to stderr in verbose mode. */
1444 encoding_attr = PyObject_GetAttrString(std, "encoding");
1445 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001446 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001447 if (std_encoding != NULL) {
1448 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1449 Py_XDECREF(codec_info);
1450 }
1451 Py_DECREF(encoding_attr);
1452 }
1453 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1454
1455 if (PySys_SetObject("__stderr__", std) < 0) {
1456 Py_DECREF(std);
1457 goto error;
1458 }
1459 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1460 Py_DECREF(std);
1461 goto error;
1462 }
1463 Py_DECREF(std);
1464#endif
1465
1466 if (0) {
1467 error:
1468 status = -1;
1469 }
1470
1471 /* We won't need them anymore. */
1472 if (_Py_StandardStreamEncoding) {
1473 PyMem_RawFree(_Py_StandardStreamEncoding);
1474 _Py_StandardStreamEncoding = NULL;
1475 }
1476 if (_Py_StandardStreamErrors) {
1477 PyMem_RawFree(_Py_StandardStreamErrors);
1478 _Py_StandardStreamErrors = NULL;
1479 }
1480 PyMem_Free(pythonioencoding);
1481 Py_XDECREF(bimod);
1482 Py_XDECREF(iomod);
1483 return status;
1484}
1485
1486
Victor Stinner10dc4842015-03-24 12:01:30 +01001487static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001488_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001489{
Victor Stinner10dc4842015-03-24 12:01:30 +01001490 fputc('\n', stderr);
1491 fflush(stderr);
1492
1493 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001494 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001495}
Victor Stinner791da1c2016-03-14 16:53:12 +01001496
1497/* Print the current exception (if an exception is set) with its traceback,
1498 or display the current Python stack.
1499
1500 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1501 called on catastrophic cases.
1502
1503 Return 1 if the traceback was displayed, 0 otherwise. */
1504
1505static int
1506_Py_FatalError_PrintExc(int fd)
1507{
1508 PyObject *ferr, *res;
1509 PyObject *exception, *v, *tb;
1510 int has_tb;
1511
1512 if (PyThreadState_GET() == NULL) {
1513 /* The GIL is released: trying to acquire it is likely to deadlock,
1514 just give up. */
1515 return 0;
1516 }
1517
1518 PyErr_Fetch(&exception, &v, &tb);
1519 if (exception == NULL) {
1520 /* No current exception */
1521 return 0;
1522 }
1523
1524 ferr = _PySys_GetObjectId(&PyId_stderr);
1525 if (ferr == NULL || ferr == Py_None) {
1526 /* sys.stderr is not set yet or set to None,
1527 no need to try to display the exception */
1528 return 0;
1529 }
1530
1531 PyErr_NormalizeException(&exception, &v, &tb);
1532 if (tb == NULL) {
1533 tb = Py_None;
1534 Py_INCREF(tb);
1535 }
1536 PyException_SetTraceback(v, tb);
1537 if (exception == NULL) {
1538 /* PyErr_NormalizeException() failed */
1539 return 0;
1540 }
1541
1542 has_tb = (tb != Py_None);
1543 PyErr_Display(exception, v, tb);
1544 Py_XDECREF(exception);
1545 Py_XDECREF(v);
1546 Py_XDECREF(tb);
1547
1548 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001549 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001550 if (res == NULL)
1551 PyErr_Clear();
1552 else
1553 Py_DECREF(res);
1554
1555 return has_tb;
1556}
1557
Nick Coghland6009512014-11-20 21:39:37 +10001558/* Print fatal error message and abort */
1559
1560void
1561Py_FatalError(const char *msg)
1562{
1563 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001564 static int reentrant = 0;
1565#ifdef MS_WINDOWS
1566 size_t len;
1567 WCHAR* buffer;
1568 size_t i;
1569#endif
1570
1571 if (reentrant) {
1572 /* Py_FatalError() caused a second fatal error.
1573 Example: flush_std_files() raises a recursion error. */
1574 goto exit;
1575 }
1576 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001577
1578 fprintf(stderr, "Fatal Python error: %s\n", msg);
1579 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001580
Victor Stinnere0deff32015-03-24 13:46:18 +01001581 /* Print the exception (if an exception is set) with its traceback,
1582 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001583 if (!_Py_FatalError_PrintExc(fd))
1584 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001585
Victor Stinner2025d782016-03-16 23:19:15 +01001586 /* The main purpose of faulthandler is to display the traceback. We already
1587 * did our best to display it. So faulthandler can now be disabled.
1588 * (Don't trigger it on abort().) */
1589 _PyFaulthandler_Fini();
1590
Victor Stinner791da1c2016-03-14 16:53:12 +01001591 /* Check if the current Python thread hold the GIL */
1592 if (PyThreadState_GET() != NULL) {
1593 /* Flush sys.stdout and sys.stderr */
1594 flush_std_files();
1595 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001596
Nick Coghland6009512014-11-20 21:39:37 +10001597#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001598 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001599
Victor Stinner53345a42015-03-25 01:55:14 +01001600 /* Convert the message to wchar_t. This uses a simple one-to-one
1601 conversion, assuming that the this error message actually uses ASCII
1602 only. If this ceases to be true, we will have to convert. */
1603 buffer = alloca( (len+1) * (sizeof *buffer));
1604 for( i=0; i<=len; ++i)
1605 buffer[i] = msg[i];
1606 OutputDebugStringW(L"Fatal Python error: ");
1607 OutputDebugStringW(buffer);
1608 OutputDebugStringW(L"\n");
1609#endif /* MS_WINDOWS */
1610
1611exit:
1612#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001613 DebugBreak();
1614#endif
Nick Coghland6009512014-11-20 21:39:37 +10001615 abort();
1616}
1617
1618/* Clean up and exit */
1619
1620#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001621# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001622#endif
1623
1624static void (*pyexitfunc)(void) = NULL;
1625/* For the atexit module. */
1626void _Py_PyAtExit(void (*func)(void))
1627{
1628 pyexitfunc = func;
1629}
1630
1631static void
1632call_py_exitfuncs(void)
1633{
1634 if (pyexitfunc == NULL)
1635 return;
1636
1637 (*pyexitfunc)();
1638 PyErr_Clear();
1639}
1640
1641/* Wait until threading._shutdown completes, provided
1642 the threading module was imported in the first place.
1643 The shutdown routine will wait until all non-daemon
1644 "threading" threads have completed. */
1645static void
1646wait_for_thread_shutdown(void)
1647{
1648#ifdef WITH_THREAD
1649 _Py_IDENTIFIER(_shutdown);
1650 PyObject *result;
1651 PyThreadState *tstate = PyThreadState_GET();
1652 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1653 "threading");
1654 if (threading == NULL) {
1655 /* threading not imported */
1656 PyErr_Clear();
1657 return;
1658 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001659 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001660 if (result == NULL) {
1661 PyErr_WriteUnraisable(threading);
1662 }
1663 else {
1664 Py_DECREF(result);
1665 }
1666 Py_DECREF(threading);
1667#endif
1668}
1669
1670#define NEXITFUNCS 32
1671static void (*exitfuncs[NEXITFUNCS])(void);
1672static int nexitfuncs = 0;
1673
1674int Py_AtExit(void (*func)(void))
1675{
1676 if (nexitfuncs >= NEXITFUNCS)
1677 return -1;
1678 exitfuncs[nexitfuncs++] = func;
1679 return 0;
1680}
1681
1682static void
1683call_ll_exitfuncs(void)
1684{
1685 while (nexitfuncs > 0)
1686 (*exitfuncs[--nexitfuncs])();
1687
1688 fflush(stdout);
1689 fflush(stderr);
1690}
1691
1692void
1693Py_Exit(int sts)
1694{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001695 if (Py_FinalizeEx() < 0) {
1696 sts = 120;
1697 }
Nick Coghland6009512014-11-20 21:39:37 +10001698
1699 exit(sts);
1700}
1701
1702static void
1703initsigs(void)
1704{
1705#ifdef SIGPIPE
1706 PyOS_setsig(SIGPIPE, SIG_IGN);
1707#endif
1708#ifdef SIGXFZ
1709 PyOS_setsig(SIGXFZ, SIG_IGN);
1710#endif
1711#ifdef SIGXFSZ
1712 PyOS_setsig(SIGXFSZ, SIG_IGN);
1713#endif
1714 PyOS_InitInterrupts(); /* May imply initsignal() */
1715 if (PyErr_Occurred()) {
1716 Py_FatalError("Py_Initialize: can't import signal");
1717 }
1718}
1719
1720
1721/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1722 *
1723 * All of the code in this function must only use async-signal-safe functions,
1724 * listed at `man 7 signal` or
1725 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1726 */
1727void
1728_Py_RestoreSignals(void)
1729{
1730#ifdef SIGPIPE
1731 PyOS_setsig(SIGPIPE, SIG_DFL);
1732#endif
1733#ifdef SIGXFZ
1734 PyOS_setsig(SIGXFZ, SIG_DFL);
1735#endif
1736#ifdef SIGXFSZ
1737 PyOS_setsig(SIGXFSZ, SIG_DFL);
1738#endif
1739}
1740
1741
1742/*
1743 * The file descriptor fd is considered ``interactive'' if either
1744 * a) isatty(fd) is TRUE, or
1745 * b) the -i flag was given, and the filename associated with
1746 * the descriptor is NULL or "<stdin>" or "???".
1747 */
1748int
1749Py_FdIsInteractive(FILE *fp, const char *filename)
1750{
1751 if (isatty((int)fileno(fp)))
1752 return 1;
1753 if (!Py_InteractiveFlag)
1754 return 0;
1755 return (filename == NULL) ||
1756 (strcmp(filename, "<stdin>") == 0) ||
1757 (strcmp(filename, "???") == 0);
1758}
1759
1760
Nick Coghland6009512014-11-20 21:39:37 +10001761/* Wrappers around sigaction() or signal(). */
1762
1763PyOS_sighandler_t
1764PyOS_getsig(int sig)
1765{
1766#ifdef HAVE_SIGACTION
1767 struct sigaction context;
1768 if (sigaction(sig, NULL, &context) == -1)
1769 return SIG_ERR;
1770 return context.sa_handler;
1771#else
1772 PyOS_sighandler_t handler;
1773/* Special signal handling for the secure CRT in Visual Studio 2005 */
1774#if defined(_MSC_VER) && _MSC_VER >= 1400
1775 switch (sig) {
1776 /* Only these signals are valid */
1777 case SIGINT:
1778 case SIGILL:
1779 case SIGFPE:
1780 case SIGSEGV:
1781 case SIGTERM:
1782 case SIGBREAK:
1783 case SIGABRT:
1784 break;
1785 /* Don't call signal() with other values or it will assert */
1786 default:
1787 return SIG_ERR;
1788 }
1789#endif /* _MSC_VER && _MSC_VER >= 1400 */
1790 handler = signal(sig, SIG_IGN);
1791 if (handler != SIG_ERR)
1792 signal(sig, handler);
1793 return handler;
1794#endif
1795}
1796
1797/*
1798 * All of the code in this function must only use async-signal-safe functions,
1799 * listed at `man 7 signal` or
1800 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1801 */
1802PyOS_sighandler_t
1803PyOS_setsig(int sig, PyOS_sighandler_t handler)
1804{
1805#ifdef HAVE_SIGACTION
1806 /* Some code in Modules/signalmodule.c depends on sigaction() being
1807 * used here if HAVE_SIGACTION is defined. Fix that if this code
1808 * changes to invalidate that assumption.
1809 */
1810 struct sigaction context, ocontext;
1811 context.sa_handler = handler;
1812 sigemptyset(&context.sa_mask);
1813 context.sa_flags = 0;
1814 if (sigaction(sig, &context, &ocontext) == -1)
1815 return SIG_ERR;
1816 return ocontext.sa_handler;
1817#else
1818 PyOS_sighandler_t oldhandler;
1819 oldhandler = signal(sig, handler);
1820#ifdef HAVE_SIGINTERRUPT
1821 siginterrupt(sig, 1);
1822#endif
1823 return oldhandler;
1824#endif
1825}
1826
1827#ifdef __cplusplus
1828}
1829#endif