blob: a17adf7626b010489537d54e073950bfba63fe84 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001
2/* Python interpreter top-level routines, including init/exit */
3
4#include "Python.h"
5
6#include "Python-ast.h"
7#undef Yield /* undefine macro conflicting with winbase.h */
8#include "grammar.h"
9#include "node.h"
10#include "token.h"
11#include "parsetok.h"
12#include "errcode.h"
13#include "code.h"
14#include "symtable.h"
15#include "ast.h"
16#include "marshal.h"
17#include "osdefs.h"
18#include <locale.h>
19
20#ifdef HAVE_SIGNAL_H
21#include <signal.h>
22#endif
23
24#ifdef MS_WINDOWS
25#include "malloc.h" /* for alloca */
26#endif
27
28#ifdef HAVE_LANGINFO_H
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTE
34#include "windows.h"
35#endif
36
37_Py_IDENTIFIER(flush);
38_Py_IDENTIFIER(name);
39_Py_IDENTIFIER(stdin);
40_Py_IDENTIFIER(stdout);
41_Py_IDENTIFIER(stderr);
42
43#ifdef __cplusplus
44extern "C" {
45#endif
46
47extern wchar_t *Py_GetPath(void);
48
49extern grammar _PyParser_Grammar; /* From graminit.c */
50
51/* Forward */
52static void initmain(PyInterpreterState *interp);
53static int initfsencoding(PyInterpreterState *interp);
54static void initsite(void);
55static int initstdio(void);
56static void initsigs(void);
57static void call_py_exitfuncs(void);
58static void wait_for_thread_shutdown(void);
59static void call_ll_exitfuncs(void);
60extern int _PyUnicode_Init(void);
61extern int _PyStructSequence_Init(void);
62extern void _PyUnicode_Fini(void);
63extern int _PyLong_Init(void);
64extern void PyLong_Fini(void);
65extern int _PyFaulthandler_Init(void);
66extern void _PyFaulthandler_Fini(void);
67extern void _PyHash_Fini(void);
68extern int _PyTraceMalloc_Init(void);
69extern int _PyTraceMalloc_Fini(void);
70
71#ifdef WITH_THREAD
72extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
73extern void _PyGILState_Fini(void);
74#endif /* WITH_THREAD */
75
76/* Global configuration variable declarations are in pydebug.h */
77/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
78int Py_DebugFlag; /* Needed by parser.c */
79int Py_VerboseFlag; /* Needed by import.c */
80int Py_QuietFlag; /* Needed by sysmodule.c */
81int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
82int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
83int Py_OptimizeFlag = 0; /* Needed by compile.c */
84int Py_NoSiteFlag; /* Suppress 'import site' */
85int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
86int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
87int Py_FrozenFlag; /* Needed by getpath.c */
88int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
89int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
90int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
91int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
92int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
93int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
94
95PyThreadState *_Py_Finalizing = NULL;
96
97/* Hack to force loading of object files */
98int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
99 PyOS_mystrnicmp; /* Python/pystrcmp.o */
100
101/* PyModule_GetWarningsModule is no longer necessary as of 2.6
102since _warnings is builtin. This API should not be used. */
103PyObject *
104PyModule_GetWarningsModule(void)
105{
106 return PyImport_ImportModule("warnings");
107}
108
109static int initialized = 0;
110
111/* API to access the initialized flag -- useful for esoteric use */
112
113int
114Py_IsInitialized(void)
115{
116 return initialized;
117}
118
119/* Helper to allow an embedding application to override the normal
120 * mechanism that attempts to figure out an appropriate IO encoding
121 */
122
123static char *_Py_StandardStreamEncoding = NULL;
124static char *_Py_StandardStreamErrors = NULL;
125
126int
127Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
128{
129 if (Py_IsInitialized()) {
130 /* This is too late to have any effect */
131 return -1;
132 }
133 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
134 * initialised yet.
135 *
136 * However, the raw memory allocators are initialised appropriately
137 * as C static variables, so _PyMem_RawStrdup is OK even though
138 * Py_Initialize hasn't been called yet.
139 */
140 if (encoding) {
141 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
142 if (!_Py_StandardStreamEncoding) {
143 return -2;
144 }
145 }
146 if (errors) {
147 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
148 if (!_Py_StandardStreamErrors) {
149 if (_Py_StandardStreamEncoding) {
150 PyMem_RawFree(_Py_StandardStreamEncoding);
151 }
152 return -3;
153 }
154 }
155 return 0;
156}
157
158/* Global initializations. Can be undone by Py_Finalize(). Don't
159 call this twice without an intervening Py_Finalize() call. When
160 initializations fail, a fatal error is issued and the function does
161 not return. On return, the first thread and interpreter state have
162 been created.
163
164 Locking: you must hold the interpreter lock while calling this.
165 (If the lock has not yet been initialized, that's equivalent to
166 having the lock, but you cannot use multiple threads.)
167
168*/
169
170static int
171add_flag(int flag, const char *envs)
172{
173 int env = atoi(envs);
174 if (flag < env)
175 flag = env;
176 if (flag < 1)
177 flag = 1;
178 return flag;
179}
180
181static char*
182get_codec_name(const char *encoding)
183{
184 char *name_utf8, *name_str;
185 PyObject *codec, *name = NULL;
186
187 codec = _PyCodec_Lookup(encoding);
188 if (!codec)
189 goto error;
190
191 name = _PyObject_GetAttrId(codec, &PyId_name);
192 Py_CLEAR(codec);
193 if (!name)
194 goto error;
195
196 name_utf8 = _PyUnicode_AsString(name);
197 if (name_utf8 == NULL)
198 goto error;
199 name_str = _PyMem_RawStrdup(name_utf8);
200 Py_DECREF(name);
201 if (name_str == NULL) {
202 PyErr_NoMemory();
203 return NULL;
204 }
205 return name_str;
206
207error:
208 Py_XDECREF(codec);
209 Py_XDECREF(name);
210 return NULL;
211}
212
213static char*
214get_locale_encoding(void)
215{
216#ifdef MS_WINDOWS
217 char codepage[100];
218 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
219 return get_codec_name(codepage);
220#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
221 char* codeset = nl_langinfo(CODESET);
222 if (!codeset || codeset[0] == '\0') {
223 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
224 return NULL;
225 }
226 return get_codec_name(codeset);
227#else
228 PyErr_SetNone(PyExc_NotImplementedError);
229 return NULL;
230#endif
231}
232
233static void
234import_init(PyInterpreterState *interp, PyObject *sysmod)
235{
236 PyObject *importlib;
237 PyObject *impmod;
238 PyObject *sys_modules;
239 PyObject *value;
240
241 /* Import _importlib through its frozen version, _frozen_importlib. */
242 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
243 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
244 }
245 else if (Py_VerboseFlag) {
246 PySys_FormatStderr("import _frozen_importlib # frozen\n");
247 }
248 importlib = PyImport_AddModule("_frozen_importlib");
249 if (importlib == NULL) {
250 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
251 "sys.modules");
252 }
253 interp->importlib = importlib;
254 Py_INCREF(interp->importlib);
255
256 /* Install _importlib as __import__ */
257 impmod = PyInit_imp();
258 if (impmod == NULL) {
259 Py_FatalError("Py_Initialize: can't import imp");
260 }
261 else if (Py_VerboseFlag) {
262 PySys_FormatStderr("import imp # builtin\n");
263 }
264 sys_modules = PyImport_GetModuleDict();
265 if (Py_VerboseFlag) {
266 PySys_FormatStderr("import sys # builtin\n");
267 }
268 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
269 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
270 }
271
272 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
273 if (value == NULL) {
274 PyErr_Print();
275 Py_FatalError("Py_Initialize: importlib install failed");
276 }
277 Py_DECREF(value);
278 Py_DECREF(impmod);
279
280 _PyImportZip_Init();
281}
282
283
284void
285_Py_InitializeEx_Private(int install_sigs, int install_importlib)
286{
287 PyInterpreterState *interp;
288 PyThreadState *tstate;
289 PyObject *bimod, *sysmod, *pstderr;
290 char *p;
291 extern void _Py_ReadyTypes(void);
292
293 if (initialized)
294 return;
295 initialized = 1;
296 _Py_Finalizing = NULL;
297
298#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
299 /* Set up the LC_CTYPE locale, so we can obtain
300 the locale's charset without having to switch
301 locales. */
302 setlocale(LC_CTYPE, "");
303#endif
304
305 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
306 Py_DebugFlag = add_flag(Py_DebugFlag, p);
307 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
308 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
309 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
310 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
311 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
312 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
313 /* The variable is only tested for existence here; _PyRandom_Init will
314 check its value further. */
315 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
316 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
317
318 _PyRandom_Init();
319
320 interp = PyInterpreterState_New();
321 if (interp == NULL)
322 Py_FatalError("Py_Initialize: can't make first interpreter");
323
324 tstate = PyThreadState_New(interp);
325 if (tstate == NULL)
326 Py_FatalError("Py_Initialize: can't make first thread");
327 (void) PyThreadState_Swap(tstate);
328
329#ifdef WITH_THREAD
330 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
331 destroying the GIL might fail when it is being referenced from
332 another running thread (see issue #9901).
333 Instead we destroy the previously created GIL here, which ensures
334 that we can call Py_Initialize / Py_Finalize multiple times. */
335 _PyEval_FiniThreads();
336
337 /* Auto-thread-state API */
338 _PyGILState_Init(interp, tstate);
339#endif /* WITH_THREAD */
340
341 _Py_ReadyTypes();
342
343 if (!_PyFrame_Init())
344 Py_FatalError("Py_Initialize: can't init frames");
345
346 if (!_PyLong_Init())
347 Py_FatalError("Py_Initialize: can't init longs");
348
349 if (!PyByteArray_Init())
350 Py_FatalError("Py_Initialize: can't init bytearray");
351
352 if (!_PyFloat_Init())
353 Py_FatalError("Py_Initialize: can't init float");
354
355 interp->modules = PyDict_New();
356 if (interp->modules == NULL)
357 Py_FatalError("Py_Initialize: can't make modules dictionary");
358
359 /* Init Unicode implementation; relies on the codec registry */
360 if (_PyUnicode_Init() < 0)
361 Py_FatalError("Py_Initialize: can't initialize unicode");
362 if (_PyStructSequence_Init() < 0)
363 Py_FatalError("Py_Initialize: can't initialize structseq");
364
365 bimod = _PyBuiltin_Init();
366 if (bimod == NULL)
367 Py_FatalError("Py_Initialize: can't initialize builtins modules");
368 _PyImport_FixupBuiltin(bimod, "builtins");
369 interp->builtins = PyModule_GetDict(bimod);
370 if (interp->builtins == NULL)
371 Py_FatalError("Py_Initialize: can't initialize builtins dict");
372 Py_INCREF(interp->builtins);
373
374 /* initialize builtin exceptions */
375 _PyExc_Init(bimod);
376
377 sysmod = _PySys_Init();
378 if (sysmod == NULL)
379 Py_FatalError("Py_Initialize: can't initialize sys");
380 interp->sysdict = PyModule_GetDict(sysmod);
381 if (interp->sysdict == NULL)
382 Py_FatalError("Py_Initialize: can't initialize sys dict");
383 Py_INCREF(interp->sysdict);
384 _PyImport_FixupBuiltin(sysmod, "sys");
385 PySys_SetPath(Py_GetPath());
386 PyDict_SetItemString(interp->sysdict, "modules",
387 interp->modules);
388
389 /* Set up a preliminary stderr printer until we have enough
390 infrastructure for the io module in place. */
391 pstderr = PyFile_NewStdPrinter(fileno(stderr));
392 if (pstderr == NULL)
393 Py_FatalError("Py_Initialize: can't set preliminary stderr");
394 _PySys_SetObjectId(&PyId_stderr, pstderr);
395 PySys_SetObject("__stderr__", pstderr);
396 Py_DECREF(pstderr);
397
398 _PyImport_Init();
399
400 _PyImportHooks_Init();
401
402 /* Initialize _warnings. */
403 _PyWarnings_Init();
404
405 if (!install_importlib)
406 return;
407
Victor Stinner13019fd2015-04-03 13:10:54 +0200408 if (_PyTime_Init() < 0)
409 Py_FatalError("Py_Initialize: can't initialize time");
410
Nick Coghland6009512014-11-20 21:39:37 +1000411 import_init(interp, sysmod);
412
413 /* initialize the faulthandler module */
414 if (_PyFaulthandler_Init())
415 Py_FatalError("Py_Initialize: can't initialize faulthandler");
416
Nick Coghland6009512014-11-20 21:39:37 +1000417 if (initfsencoding(interp) < 0)
418 Py_FatalError("Py_Initialize: unable to load the file system codec");
419
420 if (install_sigs)
421 initsigs(); /* Signal handling stuff, including initintr() */
422
423 if (_PyTraceMalloc_Init() < 0)
424 Py_FatalError("Py_Initialize: can't initialize tracemalloc");
425
426 initmain(interp); /* Module __main__ */
427 if (initstdio() < 0)
428 Py_FatalError(
429 "Py_Initialize: can't initialize sys standard streams");
430
431 /* Initialize warnings. */
432 if (PySys_HasWarnOptions()) {
433 PyObject *warnings_module = PyImport_ImportModule("warnings");
434 if (warnings_module == NULL) {
435 fprintf(stderr, "'import warnings' failed; traceback:\n");
436 PyErr_Print();
437 }
438 Py_XDECREF(warnings_module);
439 }
440
441 if (!Py_NoSiteFlag)
442 initsite(); /* Module site */
443}
444
445void
446Py_InitializeEx(int install_sigs)
447{
448 _Py_InitializeEx_Private(install_sigs, 1);
449}
450
451void
452Py_Initialize(void)
453{
454 Py_InitializeEx(1);
455}
456
457
458#ifdef COUNT_ALLOCS
459extern void dump_counts(FILE*);
460#endif
461
462/* Flush stdout and stderr */
463
464static int
465file_is_closed(PyObject *fobj)
466{
467 int r;
468 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
469 if (tmp == NULL) {
470 PyErr_Clear();
471 return 0;
472 }
473 r = PyObject_IsTrue(tmp);
474 Py_DECREF(tmp);
475 if (r < 0)
476 PyErr_Clear();
477 return r > 0;
478}
479
480static void
481flush_std_files(void)
482{
483 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
484 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
485 PyObject *tmp;
486
487 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
488 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
489 if (tmp == NULL)
490 PyErr_WriteUnraisable(fout);
491 else
492 Py_DECREF(tmp);
493 }
494
495 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
496 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
497 if (tmp == NULL)
498 PyErr_Clear();
499 else
500 Py_DECREF(tmp);
501 }
502}
503
504/* Undo the effect of Py_Initialize().
505
506 Beware: if multiple interpreter and/or thread states exist, these
507 are not wiped out; only the current thread and interpreter state
508 are deleted. But since everything else is deleted, those other
509 interpreter and thread states should no longer be used.
510
511 (XXX We should do better, e.g. wipe out all interpreters and
512 threads.)
513
514 Locking: as above.
515
516*/
517
518void
519Py_Finalize(void)
520{
521 PyInterpreterState *interp;
522 PyThreadState *tstate;
523
524 if (!initialized)
525 return;
526
527 wait_for_thread_shutdown();
528
529 /* The interpreter is still entirely intact at this point, and the
530 * exit funcs may be relying on that. In particular, if some thread
531 * or exit func is still waiting to do an import, the import machinery
532 * expects Py_IsInitialized() to return true. So don't say the
533 * interpreter is uninitialized until after the exit funcs have run.
534 * Note that Threading.py uses an exit func to do a join on all the
535 * threads created thru it, so this also protects pending imports in
536 * the threads created via Threading.
537 */
538 call_py_exitfuncs();
539
540 /* Get current thread state and interpreter pointer */
541 tstate = PyThreadState_GET();
542 interp = tstate->interp;
543
544 /* Remaining threads (e.g. daemon threads) will automatically exit
545 after taking the GIL (in PyEval_RestoreThread()). */
546 _Py_Finalizing = tstate;
547 initialized = 0;
548
Victor Stinnere0deff32015-03-24 13:46:18 +0100549 /* Flush sys.stdout and sys.stderr */
Nick Coghland6009512014-11-20 21:39:37 +1000550 flush_std_files();
551
552 /* Disable signal handling */
553 PyOS_FiniInterrupts();
554
555 /* Collect garbage. This may call finalizers; it's nice to call these
556 * before all modules are destroyed.
557 * XXX If a __del__ or weakref callback is triggered here, and tries to
558 * XXX import a module, bad things can happen, because Python no
559 * XXX longer believes it's initialized.
560 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
561 * XXX is easy to provoke that way. I've also seen, e.g.,
562 * XXX Exception exceptions.ImportError: 'No module named sha'
563 * XXX in <function callback at 0x008F5718> ignored
564 * XXX but I'm unclear on exactly how that one happens. In any case,
565 * XXX I haven't seen a real-life report of either of these.
566 */
567 PyGC_Collect();
568#ifdef COUNT_ALLOCS
569 /* With COUNT_ALLOCS, it helps to run GC multiple times:
570 each collection might release some types from the type
571 list, so they become garbage. */
572 while (PyGC_Collect() > 0)
573 /* nothing */;
574#endif
575 /* Destroy all modules */
576 PyImport_Cleanup();
577
Victor Stinnere0deff32015-03-24 13:46:18 +0100578 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Nick Coghland6009512014-11-20 21:39:37 +1000579 flush_std_files();
580
581 /* Collect final garbage. This disposes of cycles created by
582 * class definitions, for example.
583 * XXX This is disabled because it caused too many problems. If
584 * XXX a __del__ or weakref callback triggers here, Python code has
585 * XXX a hard time running, because even the sys module has been
586 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
587 * XXX One symptom is a sequence of information-free messages
588 * XXX coming from threads (if a __del__ or callback is invoked,
589 * XXX other threads can execute too, and any exception they encounter
590 * XXX triggers a comedy of errors as subsystem after subsystem
591 * XXX fails to find what it *expects* to find in sys to help report
592 * XXX the exception and consequent unexpected failures). I've also
593 * XXX seen segfaults then, after adding print statements to the
594 * XXX Python code getting called.
595 */
596#if 0
597 PyGC_Collect();
598#endif
599
600 /* Disable tracemalloc after all Python objects have been destroyed,
601 so it is possible to use tracemalloc in objects destructor. */
602 _PyTraceMalloc_Fini();
603
604 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
605 _PyImport_Fini();
606
607 /* Cleanup typeobject.c's internal caches. */
608 _PyType_Fini();
609
610 /* unload faulthandler module */
611 _PyFaulthandler_Fini();
612
613 /* Debugging stuff */
614#ifdef COUNT_ALLOCS
615 dump_counts(stdout);
616#endif
617 /* dump hash stats */
618 _PyHash_Fini();
619
620 _PY_DEBUG_PRINT_TOTAL_REFS();
621
622#ifdef Py_TRACE_REFS
623 /* Display all objects still alive -- this can invoke arbitrary
624 * __repr__ overrides, so requires a mostly-intact interpreter.
625 * Alas, a lot of stuff may still be alive now that will be cleaned
626 * up later.
627 */
628 if (Py_GETENV("PYTHONDUMPREFS"))
629 _Py_PrintReferences(stderr);
630#endif /* Py_TRACE_REFS */
631
632 /* Clear interpreter state and all thread states. */
633 PyInterpreterState_Clear(interp);
634
635 /* Now we decref the exception classes. After this point nothing
636 can raise an exception. That's okay, because each Fini() method
637 below has been checked to make sure no exceptions are ever
638 raised.
639 */
640
641 _PyExc_Fini();
642
643 /* Sundry finalizers */
644 PyMethod_Fini();
645 PyFrame_Fini();
646 PyCFunction_Fini();
647 PyTuple_Fini();
648 PyList_Fini();
649 PySet_Fini();
650 PyBytes_Fini();
651 PyByteArray_Fini();
652 PyLong_Fini();
653 PyFloat_Fini();
654 PyDict_Fini();
655 PySlice_Fini();
656 _PyGC_Fini();
657 _PyRandom_Fini();
658
659 /* Cleanup Unicode implementation */
660 _PyUnicode_Fini();
661
662 /* reset file system default encoding */
663 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
664 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
665 Py_FileSystemDefaultEncoding = NULL;
666 }
667
668 /* XXX Still allocated:
669 - various static ad-hoc pointers to interned strings
670 - int and float free list blocks
671 - whatever various modules and libraries allocate
672 */
673
674 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
675
676 /* Cleanup auto-thread-state */
677#ifdef WITH_THREAD
678 _PyGILState_Fini();
679#endif /* WITH_THREAD */
680
681 /* Delete current thread. After this, many C API calls become crashy. */
682 PyThreadState_Swap(NULL);
683 PyInterpreterState_Delete(interp);
684
685#ifdef Py_TRACE_REFS
686 /* Display addresses (& refcnts) of all objects still alive.
687 * An address can be used to find the repr of the object, printed
688 * above by _Py_PrintReferences.
689 */
690 if (Py_GETENV("PYTHONDUMPREFS"))
691 _Py_PrintReferenceAddresses(stderr);
692#endif /* Py_TRACE_REFS */
693#ifdef PYMALLOC_DEBUG
694 if (Py_GETENV("PYTHONMALLOCSTATS"))
695 _PyObject_DebugMallocStats(stderr);
696#endif
697
698 call_ll_exitfuncs();
699}
700
701/* Create and initialize a new interpreter and thread, and return the
702 new thread. This requires that Py_Initialize() has been called
703 first.
704
705 Unsuccessful initialization yields a NULL pointer. Note that *no*
706 exception information is available even in this case -- the
707 exception information is held in the thread, and there is no
708 thread.
709
710 Locking: as above.
711
712*/
713
714PyThreadState *
715Py_NewInterpreter(void)
716{
717 PyInterpreterState *interp;
718 PyThreadState *tstate, *save_tstate;
719 PyObject *bimod, *sysmod;
720
721 if (!initialized)
722 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
723
724 interp = PyInterpreterState_New();
725 if (interp == NULL)
726 return NULL;
727
728 tstate = PyThreadState_New(interp);
729 if (tstate == NULL) {
730 PyInterpreterState_Delete(interp);
731 return NULL;
732 }
733
734 save_tstate = PyThreadState_Swap(tstate);
735
736 /* XXX The following is lax in error checking */
737
738 interp->modules = PyDict_New();
739
740 bimod = _PyImport_FindBuiltin("builtins");
741 if (bimod != NULL) {
742 interp->builtins = PyModule_GetDict(bimod);
743 if (interp->builtins == NULL)
744 goto handle_error;
745 Py_INCREF(interp->builtins);
746 }
747
748 /* initialize builtin exceptions */
749 _PyExc_Init(bimod);
750
751 sysmod = _PyImport_FindBuiltin("sys");
752 if (bimod != NULL && sysmod != NULL) {
753 PyObject *pstderr;
754
755 interp->sysdict = PyModule_GetDict(sysmod);
756 if (interp->sysdict == NULL)
757 goto handle_error;
758 Py_INCREF(interp->sysdict);
759 PySys_SetPath(Py_GetPath());
760 PyDict_SetItemString(interp->sysdict, "modules",
761 interp->modules);
762 /* Set up a preliminary stderr printer until we have enough
763 infrastructure for the io module in place. */
764 pstderr = PyFile_NewStdPrinter(fileno(stderr));
765 if (pstderr == NULL)
766 Py_FatalError("Py_Initialize: can't set preliminary stderr");
767 _PySys_SetObjectId(&PyId_stderr, pstderr);
768 PySys_SetObject("__stderr__", pstderr);
769 Py_DECREF(pstderr);
770
771 _PyImportHooks_Init();
772
773 import_init(interp, sysmod);
774
775 if (initfsencoding(interp) < 0)
776 goto handle_error;
777
778 if (initstdio() < 0)
779 Py_FatalError(
780 "Py_Initialize: can't initialize sys standard streams");
781 initmain(interp);
782 if (!Py_NoSiteFlag)
783 initsite();
784 }
785
786 if (!PyErr_Occurred())
787 return tstate;
788
789handle_error:
790 /* Oops, it didn't work. Undo it all. */
791
792 PyErr_PrintEx(0);
793 PyThreadState_Clear(tstate);
794 PyThreadState_Swap(save_tstate);
795 PyThreadState_Delete(tstate);
796 PyInterpreterState_Delete(interp);
797
798 return NULL;
799}
800
801/* Delete an interpreter and its last thread. This requires that the
802 given thread state is current, that the thread has no remaining
803 frames, and that it is its interpreter's only remaining thread.
804 It is a fatal error to violate these constraints.
805
806 (Py_Finalize() doesn't have these constraints -- it zaps
807 everything, regardless.)
808
809 Locking: as above.
810
811*/
812
813void
814Py_EndInterpreter(PyThreadState *tstate)
815{
816 PyInterpreterState *interp = tstate->interp;
817
818 if (tstate != PyThreadState_GET())
819 Py_FatalError("Py_EndInterpreter: thread is not current");
820 if (tstate->frame != NULL)
821 Py_FatalError("Py_EndInterpreter: thread still has a frame");
822
823 wait_for_thread_shutdown();
824
825 if (tstate != interp->tstate_head || tstate->next != NULL)
826 Py_FatalError("Py_EndInterpreter: not the last thread");
827
828 PyImport_Cleanup();
829 PyInterpreterState_Clear(interp);
830 PyThreadState_Swap(NULL);
831 PyInterpreterState_Delete(interp);
832}
833
834#ifdef MS_WINDOWS
835static wchar_t *progname = L"python";
836#else
837static wchar_t *progname = L"python3";
838#endif
839
840void
841Py_SetProgramName(wchar_t *pn)
842{
843 if (pn && *pn)
844 progname = pn;
845}
846
847wchar_t *
848Py_GetProgramName(void)
849{
850 return progname;
851}
852
853static wchar_t *default_home = NULL;
854static wchar_t env_home[MAXPATHLEN+1];
855
856void
857Py_SetPythonHome(wchar_t *home)
858{
859 default_home = home;
860}
861
862wchar_t *
863Py_GetPythonHome(void)
864{
865 wchar_t *home = default_home;
866 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
867 char* chome = Py_GETENV("PYTHONHOME");
868 if (chome) {
869 size_t size = Py_ARRAY_LENGTH(env_home);
870 size_t r = mbstowcs(env_home, chome, size);
871 if (r != (size_t)-1 && r < size)
872 home = env_home;
873 }
874
875 }
876 return home;
877}
878
879/* Create __main__ module */
880
881static void
882initmain(PyInterpreterState *interp)
883{
884 PyObject *m, *d, *loader;
885 m = PyImport_AddModule("__main__");
886 if (m == NULL)
887 Py_FatalError("can't create __main__ module");
888 d = PyModule_GetDict(m);
889 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
890 PyObject *bimod = PyImport_ImportModule("builtins");
891 if (bimod == NULL) {
892 Py_FatalError("Failed to retrieve builtins module");
893 }
894 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
895 Py_FatalError("Failed to initialize __main__.__builtins__");
896 }
897 Py_DECREF(bimod);
898 }
899 /* Main is a little special - imp.is_builtin("__main__") will return
900 * False, but BuiltinImporter is still the most appropriate initial
901 * setting for its __loader__ attribute. A more suitable value will
902 * be set if __main__ gets further initialized later in the startup
903 * process.
904 */
905 loader = PyDict_GetItemString(d, "__loader__");
906 if (loader == NULL || loader == Py_None) {
907 PyObject *loader = PyObject_GetAttrString(interp->importlib,
908 "BuiltinImporter");
909 if (loader == NULL) {
910 Py_FatalError("Failed to retrieve BuiltinImporter");
911 }
912 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
913 Py_FatalError("Failed to initialize __main__.__loader__");
914 }
915 Py_DECREF(loader);
916 }
917}
918
919static int
920initfsencoding(PyInterpreterState *interp)
921{
922 PyObject *codec;
923
924 if (Py_FileSystemDefaultEncoding == NULL)
925 {
926 Py_FileSystemDefaultEncoding = get_locale_encoding();
927 if (Py_FileSystemDefaultEncoding == NULL)
928 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
929
930 Py_HasFileSystemDefaultEncoding = 0;
931 interp->fscodec_initialized = 1;
932 return 0;
933 }
934
935 /* the encoding is mbcs, utf-8 or ascii */
936 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
937 if (!codec) {
938 /* Such error can only occurs in critical situations: no more
939 * memory, import a module of the standard library failed,
940 * etc. */
941 return -1;
942 }
943 Py_DECREF(codec);
944 interp->fscodec_initialized = 1;
945 return 0;
946}
947
948/* Import the site module (not into __main__ though) */
949
950static void
951initsite(void)
952{
953 PyObject *m;
954 m = PyImport_ImportModule("site");
955 if (m == NULL) {
956 fprintf(stderr, "Failed to import the site module\n");
957 PyErr_Print();
958 Py_Finalize();
959 exit(1);
960 }
961 else {
962 Py_DECREF(m);
963 }
964}
965
966static PyObject*
967create_stdio(PyObject* io,
968 int fd, int write_mode, char* name,
969 char* encoding, char* errors)
970{
971 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
972 const char* mode;
973 const char* newline;
974 PyObject *line_buffering;
975 int buffering, isatty;
976 _Py_IDENTIFIER(open);
977 _Py_IDENTIFIER(isatty);
978 _Py_IDENTIFIER(TextIOWrapper);
979 _Py_IDENTIFIER(mode);
980
981 /* stdin is always opened in buffered mode, first because it shouldn't
982 make a difference in common use cases, second because TextIOWrapper
983 depends on the presence of a read1() method which only exists on
984 buffered streams.
985 */
986 if (Py_UnbufferedStdioFlag && write_mode)
987 buffering = 0;
988 else
989 buffering = -1;
990 if (write_mode)
991 mode = "wb";
992 else
993 mode = "rb";
994 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
995 fd, mode, buffering,
996 Py_None, Py_None, Py_None, 0);
997 if (buf == NULL)
998 goto error;
999
1000 if (buffering) {
1001 _Py_IDENTIFIER(raw);
1002 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1003 if (raw == NULL)
1004 goto error;
1005 }
1006 else {
1007 raw = buf;
1008 Py_INCREF(raw);
1009 }
1010
1011 text = PyUnicode_FromString(name);
1012 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1013 goto error;
1014 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
1015 if (res == NULL)
1016 goto error;
1017 isatty = PyObject_IsTrue(res);
1018 Py_DECREF(res);
1019 if (isatty == -1)
1020 goto error;
1021 if (isatty || Py_UnbufferedStdioFlag)
1022 line_buffering = Py_True;
1023 else
1024 line_buffering = Py_False;
1025
1026 Py_CLEAR(raw);
1027 Py_CLEAR(text);
1028
1029#ifdef MS_WINDOWS
1030 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1031 newlines to "\n".
1032 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1033 newline = NULL;
1034#else
1035 /* sys.stdin: split lines at "\n".
1036 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1037 newline = "\n";
1038#endif
1039
1040 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1041 buf, encoding, errors,
1042 newline, line_buffering);
1043 Py_CLEAR(buf);
1044 if (stream == NULL)
1045 goto error;
1046
1047 if (write_mode)
1048 mode = "w";
1049 else
1050 mode = "r";
1051 text = PyUnicode_FromString(mode);
1052 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1053 goto error;
1054 Py_CLEAR(text);
1055 return stream;
1056
1057error:
1058 Py_XDECREF(buf);
1059 Py_XDECREF(stream);
1060 Py_XDECREF(text);
1061 Py_XDECREF(raw);
1062 return NULL;
1063}
1064
1065static int
1066is_valid_fd(int fd)
1067{
1068 int dummy_fd;
1069 if (fd < 0 || !_PyVerify_fd(fd))
1070 return 0;
Steve Dower8fc89802015-04-12 00:26:27 -04001071 _Py_BEGIN_SUPPRESS_IPH
Nick Coghland6009512014-11-20 21:39:37 +10001072 dummy_fd = dup(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001073 if (dummy_fd >= 0)
1074 close(dummy_fd);
1075 _Py_END_SUPPRESS_IPH
1076 return dummy_fd >= 0;
Nick Coghland6009512014-11-20 21:39:37 +10001077}
1078
1079/* Initialize sys.stdin, stdout, stderr and builtins.open */
1080static int
1081initstdio(void)
1082{
1083 PyObject *iomod = NULL, *wrapper;
1084 PyObject *bimod = NULL;
1085 PyObject *m;
1086 PyObject *std = NULL;
1087 int status = 0, fd;
1088 PyObject * encoding_attr;
1089 char *pythonioencoding = NULL, *encoding, *errors;
1090
1091 /* Hack to avoid a nasty recursion issue when Python is invoked
1092 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1093 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1094 goto error;
1095 }
1096 Py_DECREF(m);
1097
1098 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1099 goto error;
1100 }
1101 Py_DECREF(m);
1102
1103 if (!(bimod = PyImport_ImportModule("builtins"))) {
1104 goto error;
1105 }
1106
1107 if (!(iomod = PyImport_ImportModule("io"))) {
1108 goto error;
1109 }
1110 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1111 goto error;
1112 }
1113
1114 /* Set builtins.open */
1115 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1116 Py_DECREF(wrapper);
1117 goto error;
1118 }
1119 Py_DECREF(wrapper);
1120
1121 encoding = _Py_StandardStreamEncoding;
1122 errors = _Py_StandardStreamErrors;
1123 if (!encoding || !errors) {
1124 if (!errors) {
1125 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1126 stdin and stdout use the surrogateescape error handler by
1127 default, instead of the strict error handler. */
1128 char *loc = setlocale(LC_CTYPE, NULL);
1129 if (loc != NULL && strcmp(loc, "C") == 0)
1130 errors = "surrogateescape";
1131 }
1132
1133 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1134 if (pythonioencoding) {
1135 char *err;
1136 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1137 if (pythonioencoding == NULL) {
1138 PyErr_NoMemory();
1139 goto error;
1140 }
1141 err = strchr(pythonioencoding, ':');
1142 if (err) {
1143 *err = '\0';
1144 err++;
1145 if (*err && !_Py_StandardStreamErrors) {
1146 errors = err;
1147 }
1148 }
1149 if (*pythonioencoding && !encoding) {
1150 encoding = pythonioencoding;
1151 }
1152 }
1153 }
1154
1155 /* Set sys.stdin */
1156 fd = fileno(stdin);
1157 /* Under some conditions stdin, stdout and stderr may not be connected
1158 * and fileno() may point to an invalid file descriptor. For example
1159 * GUI apps don't have valid standard streams by default.
1160 */
1161 if (!is_valid_fd(fd)) {
1162 std = Py_None;
1163 Py_INCREF(std);
1164 }
1165 else {
1166 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1167 if (std == NULL)
1168 goto error;
1169 } /* if (fd < 0) */
1170 PySys_SetObject("__stdin__", std);
1171 _PySys_SetObjectId(&PyId_stdin, std);
1172 Py_DECREF(std);
1173
1174 /* Set sys.stdout */
1175 fd = fileno(stdout);
1176 if (!is_valid_fd(fd)) {
1177 std = Py_None;
1178 Py_INCREF(std);
1179 }
1180 else {
1181 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1182 if (std == NULL)
1183 goto error;
1184 } /* if (fd < 0) */
1185 PySys_SetObject("__stdout__", std);
1186 _PySys_SetObjectId(&PyId_stdout, std);
1187 Py_DECREF(std);
1188
1189#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1190 /* Set sys.stderr, replaces the preliminary stderr */
1191 fd = fileno(stderr);
1192 if (!is_valid_fd(fd)) {
1193 std = Py_None;
1194 Py_INCREF(std);
1195 }
1196 else {
1197 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1198 if (std == NULL)
1199 goto error;
1200 } /* if (fd < 0) */
1201
1202 /* Same as hack above, pre-import stderr's codec to avoid recursion
1203 when import.c tries to write to stderr in verbose mode. */
1204 encoding_attr = PyObject_GetAttrString(std, "encoding");
1205 if (encoding_attr != NULL) {
1206 const char * std_encoding;
1207 std_encoding = _PyUnicode_AsString(encoding_attr);
1208 if (std_encoding != NULL) {
1209 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1210 Py_XDECREF(codec_info);
1211 }
1212 Py_DECREF(encoding_attr);
1213 }
1214 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1215
1216 if (PySys_SetObject("__stderr__", std) < 0) {
1217 Py_DECREF(std);
1218 goto error;
1219 }
1220 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1221 Py_DECREF(std);
1222 goto error;
1223 }
1224 Py_DECREF(std);
1225#endif
1226
1227 if (0) {
1228 error:
1229 status = -1;
1230 }
1231
1232 /* We won't need them anymore. */
1233 if (_Py_StandardStreamEncoding) {
1234 PyMem_RawFree(_Py_StandardStreamEncoding);
1235 _Py_StandardStreamEncoding = NULL;
1236 }
1237 if (_Py_StandardStreamErrors) {
1238 PyMem_RawFree(_Py_StandardStreamErrors);
1239 _Py_StandardStreamErrors = NULL;
1240 }
1241 PyMem_Free(pythonioencoding);
1242 Py_XDECREF(bimod);
1243 Py_XDECREF(iomod);
1244 return status;
1245}
1246
1247
Victor Stinner10dc4842015-03-24 12:01:30 +01001248/* Print the current exception (if an exception is set) with its traceback,
1249 * or display the current Python stack.
1250 *
1251 * Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1252 * called on catastrophic cases. */
1253
1254static void
1255_Py_PrintFatalError(int fd)
1256{
Victor Stinnere0deff32015-03-24 13:46:18 +01001257 PyObject *ferr, *res;
Victor Stinner10dc4842015-03-24 12:01:30 +01001258 PyObject *exception, *v, *tb;
1259 int has_tb;
1260 PyThreadState *tstate;
1261
1262 PyErr_Fetch(&exception, &v, &tb);
1263 if (exception == NULL) {
1264 /* No current exception */
1265 goto display_stack;
1266 }
1267
Victor Stinnere0deff32015-03-24 13:46:18 +01001268 ferr = _PySys_GetObjectId(&PyId_stderr);
1269 if (ferr == NULL || ferr == Py_None) {
1270 /* sys.stderr is not set yet or set to None,
1271 no need to try to display the exception */
1272 goto display_stack;
1273 }
1274
Victor Stinner10dc4842015-03-24 12:01:30 +01001275 PyErr_NormalizeException(&exception, &v, &tb);
1276 if (tb == NULL) {
1277 tb = Py_None;
1278 Py_INCREF(tb);
1279 }
1280 PyException_SetTraceback(v, tb);
1281 if (exception == NULL) {
Victor Stinnere0deff32015-03-24 13:46:18 +01001282 /* PyErr_NormalizeException() failed */
Victor Stinner10dc4842015-03-24 12:01:30 +01001283 goto display_stack;
1284 }
1285
Christian Heimese8e42832015-04-16 17:25:45 +02001286 has_tb = (tb != Py_None);
Victor Stinner10dc4842015-03-24 12:01:30 +01001287 PyErr_Display(exception, v, tb);
1288 Py_XDECREF(exception);
1289 Py_XDECREF(v);
1290 Py_XDECREF(tb);
Victor Stinnere0deff32015-03-24 13:46:18 +01001291
1292 /* sys.stderr may be buffered: call sys.stderr.flush() */
1293 res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
1294 if (res == NULL)
1295 PyErr_Clear();
1296 else
1297 Py_DECREF(res);
1298
Victor Stinner10dc4842015-03-24 12:01:30 +01001299 if (has_tb)
1300 return;
1301
1302display_stack:
Benjamin Peterson55c14352015-04-06 09:59:23 -04001303#ifdef WITH_THREAD
Victor Stinner10dc4842015-03-24 12:01:30 +01001304 /* PyGILState_GetThisThreadState() works even if the GIL was released */
1305 tstate = PyGILState_GetThisThreadState();
Benjamin Peterson55c14352015-04-06 09:59:23 -04001306#else
1307 tstate = PyThreadState_GET();
1308#endif
Victor Stinner10dc4842015-03-24 12:01:30 +01001309 if (tstate == NULL) {
1310 /* _Py_DumpTracebackThreads() requires the thread state to display
1311 * frames */
1312 return;
1313 }
1314
1315 fputc('\n', stderr);
1316 fflush(stderr);
1317
1318 /* display the current Python stack */
1319 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
1320}
Nick Coghland6009512014-11-20 21:39:37 +10001321/* Print fatal error message and abort */
1322
1323void
1324Py_FatalError(const char *msg)
1325{
1326 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001327 static int reentrant = 0;
1328#ifdef MS_WINDOWS
1329 size_t len;
1330 WCHAR* buffer;
1331 size_t i;
1332#endif
1333
1334 if (reentrant) {
1335 /* Py_FatalError() caused a second fatal error.
1336 Example: flush_std_files() raises a recursion error. */
1337 goto exit;
1338 }
1339 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001340
1341 fprintf(stderr, "Fatal Python error: %s\n", msg);
1342 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001343
Victor Stinnere0deff32015-03-24 13:46:18 +01001344 /* Print the exception (if an exception is set) with its traceback,
1345 * or display the current Python stack. */
Victor Stinner10dc4842015-03-24 12:01:30 +01001346 _Py_PrintFatalError(fd);
1347
Victor Stinnere0deff32015-03-24 13:46:18 +01001348 /* Flush sys.stdout and sys.stderr */
1349 flush_std_files();
1350
Victor Stinner10dc4842015-03-24 12:01:30 +01001351 /* The main purpose of faulthandler is to display the traceback. We already
Victor Stinnere0deff32015-03-24 13:46:18 +01001352 * did our best to display it. So faulthandler can now be disabled.
1353 * (Don't trigger it on abort().) */
Victor Stinner10dc4842015-03-24 12:01:30 +01001354 _PyFaulthandler_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001355
1356#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001357 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001358
Victor Stinner53345a42015-03-25 01:55:14 +01001359 /* Convert the message to wchar_t. This uses a simple one-to-one
1360 conversion, assuming that the this error message actually uses ASCII
1361 only. If this ceases to be true, we will have to convert. */
1362 buffer = alloca( (len+1) * (sizeof *buffer));
1363 for( i=0; i<=len; ++i)
1364 buffer[i] = msg[i];
1365 OutputDebugStringW(L"Fatal Python error: ");
1366 OutputDebugStringW(buffer);
1367 OutputDebugStringW(L"\n");
1368#endif /* MS_WINDOWS */
1369
1370exit:
1371#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001372 DebugBreak();
1373#endif
Nick Coghland6009512014-11-20 21:39:37 +10001374 abort();
1375}
1376
1377/* Clean up and exit */
1378
1379#ifdef WITH_THREAD
1380#include "pythread.h"
1381#endif
1382
1383static void (*pyexitfunc)(void) = NULL;
1384/* For the atexit module. */
1385void _Py_PyAtExit(void (*func)(void))
1386{
1387 pyexitfunc = func;
1388}
1389
1390static void
1391call_py_exitfuncs(void)
1392{
1393 if (pyexitfunc == NULL)
1394 return;
1395
1396 (*pyexitfunc)();
1397 PyErr_Clear();
1398}
1399
1400/* Wait until threading._shutdown completes, provided
1401 the threading module was imported in the first place.
1402 The shutdown routine will wait until all non-daemon
1403 "threading" threads have completed. */
1404static void
1405wait_for_thread_shutdown(void)
1406{
1407#ifdef WITH_THREAD
1408 _Py_IDENTIFIER(_shutdown);
1409 PyObject *result;
1410 PyThreadState *tstate = PyThreadState_GET();
1411 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1412 "threading");
1413 if (threading == NULL) {
1414 /* threading not imported */
1415 PyErr_Clear();
1416 return;
1417 }
1418 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1419 if (result == NULL) {
1420 PyErr_WriteUnraisable(threading);
1421 }
1422 else {
1423 Py_DECREF(result);
1424 }
1425 Py_DECREF(threading);
1426#endif
1427}
1428
1429#define NEXITFUNCS 32
1430static void (*exitfuncs[NEXITFUNCS])(void);
1431static int nexitfuncs = 0;
1432
1433int Py_AtExit(void (*func)(void))
1434{
1435 if (nexitfuncs >= NEXITFUNCS)
1436 return -1;
1437 exitfuncs[nexitfuncs++] = func;
1438 return 0;
1439}
1440
1441static void
1442call_ll_exitfuncs(void)
1443{
1444 while (nexitfuncs > 0)
1445 (*exitfuncs[--nexitfuncs])();
1446
1447 fflush(stdout);
1448 fflush(stderr);
1449}
1450
1451void
1452Py_Exit(int sts)
1453{
1454 Py_Finalize();
1455
1456 exit(sts);
1457}
1458
1459static void
1460initsigs(void)
1461{
1462#ifdef SIGPIPE
1463 PyOS_setsig(SIGPIPE, SIG_IGN);
1464#endif
1465#ifdef SIGXFZ
1466 PyOS_setsig(SIGXFZ, SIG_IGN);
1467#endif
1468#ifdef SIGXFSZ
1469 PyOS_setsig(SIGXFSZ, SIG_IGN);
1470#endif
1471 PyOS_InitInterrupts(); /* May imply initsignal() */
1472 if (PyErr_Occurred()) {
1473 Py_FatalError("Py_Initialize: can't import signal");
1474 }
1475}
1476
1477
1478/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1479 *
1480 * All of the code in this function must only use async-signal-safe functions,
1481 * listed at `man 7 signal` or
1482 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1483 */
1484void
1485_Py_RestoreSignals(void)
1486{
1487#ifdef SIGPIPE
1488 PyOS_setsig(SIGPIPE, SIG_DFL);
1489#endif
1490#ifdef SIGXFZ
1491 PyOS_setsig(SIGXFZ, SIG_DFL);
1492#endif
1493#ifdef SIGXFSZ
1494 PyOS_setsig(SIGXFSZ, SIG_DFL);
1495#endif
1496}
1497
1498
1499/*
1500 * The file descriptor fd is considered ``interactive'' if either
1501 * a) isatty(fd) is TRUE, or
1502 * b) the -i flag was given, and the filename associated with
1503 * the descriptor is NULL or "<stdin>" or "???".
1504 */
1505int
1506Py_FdIsInteractive(FILE *fp, const char *filename)
1507{
1508 if (isatty((int)fileno(fp)))
1509 return 1;
1510 if (!Py_InteractiveFlag)
1511 return 0;
1512 return (filename == NULL) ||
1513 (strcmp(filename, "<stdin>") == 0) ||
1514 (strcmp(filename, "???") == 0);
1515}
1516
1517
Nick Coghland6009512014-11-20 21:39:37 +10001518/* Wrappers around sigaction() or signal(). */
1519
1520PyOS_sighandler_t
1521PyOS_getsig(int sig)
1522{
1523#ifdef HAVE_SIGACTION
1524 struct sigaction context;
1525 if (sigaction(sig, NULL, &context) == -1)
1526 return SIG_ERR;
1527 return context.sa_handler;
1528#else
1529 PyOS_sighandler_t handler;
1530/* Special signal handling for the secure CRT in Visual Studio 2005 */
1531#if defined(_MSC_VER) && _MSC_VER >= 1400
1532 switch (sig) {
1533 /* Only these signals are valid */
1534 case SIGINT:
1535 case SIGILL:
1536 case SIGFPE:
1537 case SIGSEGV:
1538 case SIGTERM:
1539 case SIGBREAK:
1540 case SIGABRT:
1541 break;
1542 /* Don't call signal() with other values or it will assert */
1543 default:
1544 return SIG_ERR;
1545 }
1546#endif /* _MSC_VER && _MSC_VER >= 1400 */
1547 handler = signal(sig, SIG_IGN);
1548 if (handler != SIG_ERR)
1549 signal(sig, handler);
1550 return handler;
1551#endif
1552}
1553
1554/*
1555 * All of the code in this function must only use async-signal-safe functions,
1556 * listed at `man 7 signal` or
1557 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1558 */
1559PyOS_sighandler_t
1560PyOS_setsig(int sig, PyOS_sighandler_t handler)
1561{
1562#ifdef HAVE_SIGACTION
1563 /* Some code in Modules/signalmodule.c depends on sigaction() being
1564 * used here if HAVE_SIGACTION is defined. Fix that if this code
1565 * changes to invalidate that assumption.
1566 */
1567 struct sigaction context, ocontext;
1568 context.sa_handler = handler;
1569 sigemptyset(&context.sa_mask);
1570 context.sa_flags = 0;
1571 if (sigaction(sig, &context, &ocontext) == -1)
1572 return SIG_ERR;
1573 return ocontext.sa_handler;
1574#else
1575 PyOS_sighandler_t oldhandler;
1576 oldhandler = signal(sig, handler);
1577#ifdef HAVE_SIGINTERRUPT
1578 siginterrupt(sig, 1);
1579#endif
1580 return oldhandler;
1581#endif
1582}
1583
1584#ifdef __cplusplus
1585}
1586#endif