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