blob: 25a4a60f2ed2f31b76c8ac18f367b5b0d8426b97 [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
408 import_init(interp, sysmod);
409
410 /* initialize the faulthandler module */
411 if (_PyFaulthandler_Init())
412 Py_FatalError("Py_Initialize: can't initialize faulthandler");
413
414 if (_PyTime_Init() < 0)
415 Py_FatalError("Py_Initialize: can't initialize time");
416
417 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
549 /* Flush stdout+stderr */
550 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
578 /* Flush stdout+stderr (again, in case more was printed) */
579 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;
1071 dummy_fd = dup(fd);
1072 if (dummy_fd < 0)
1073 return 0;
1074 close(dummy_fd);
1075 return 1;
1076}
1077
1078/* Initialize sys.stdin, stdout, stderr and builtins.open */
1079static int
1080initstdio(void)
1081{
1082 PyObject *iomod = NULL, *wrapper;
1083 PyObject *bimod = NULL;
1084 PyObject *m;
1085 PyObject *std = NULL;
1086 int status = 0, fd;
1087 PyObject * encoding_attr;
1088 char *pythonioencoding = NULL, *encoding, *errors;
1089
1090 /* Hack to avoid a nasty recursion issue when Python is invoked
1091 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1092 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1093 goto error;
1094 }
1095 Py_DECREF(m);
1096
1097 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1098 goto error;
1099 }
1100 Py_DECREF(m);
1101
1102 if (!(bimod = PyImport_ImportModule("builtins"))) {
1103 goto error;
1104 }
1105
1106 if (!(iomod = PyImport_ImportModule("io"))) {
1107 goto error;
1108 }
1109 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1110 goto error;
1111 }
1112
1113 /* Set builtins.open */
1114 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1115 Py_DECREF(wrapper);
1116 goto error;
1117 }
1118 Py_DECREF(wrapper);
1119
1120 encoding = _Py_StandardStreamEncoding;
1121 errors = _Py_StandardStreamErrors;
1122 if (!encoding || !errors) {
1123 if (!errors) {
1124 /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
1125 stdin and stdout use the surrogateescape error handler by
1126 default, instead of the strict error handler. */
1127 char *loc = setlocale(LC_CTYPE, NULL);
1128 if (loc != NULL && strcmp(loc, "C") == 0)
1129 errors = "surrogateescape";
1130 }
1131
1132 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1133 if (pythonioencoding) {
1134 char *err;
1135 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1136 if (pythonioencoding == NULL) {
1137 PyErr_NoMemory();
1138 goto error;
1139 }
1140 err = strchr(pythonioencoding, ':');
1141 if (err) {
1142 *err = '\0';
1143 err++;
1144 if (*err && !_Py_StandardStreamErrors) {
1145 errors = err;
1146 }
1147 }
1148 if (*pythonioencoding && !encoding) {
1149 encoding = pythonioencoding;
1150 }
1151 }
1152 }
1153
1154 /* Set sys.stdin */
1155 fd = fileno(stdin);
1156 /* Under some conditions stdin, stdout and stderr may not be connected
1157 * and fileno() may point to an invalid file descriptor. For example
1158 * GUI apps don't have valid standard streams by default.
1159 */
1160 if (!is_valid_fd(fd)) {
1161 std = Py_None;
1162 Py_INCREF(std);
1163 }
1164 else {
1165 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1166 if (std == NULL)
1167 goto error;
1168 } /* if (fd < 0) */
1169 PySys_SetObject("__stdin__", std);
1170 _PySys_SetObjectId(&PyId_stdin, std);
1171 Py_DECREF(std);
1172
1173 /* Set sys.stdout */
1174 fd = fileno(stdout);
1175 if (!is_valid_fd(fd)) {
1176 std = Py_None;
1177 Py_INCREF(std);
1178 }
1179 else {
1180 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1181 if (std == NULL)
1182 goto error;
1183 } /* if (fd < 0) */
1184 PySys_SetObject("__stdout__", std);
1185 _PySys_SetObjectId(&PyId_stdout, std);
1186 Py_DECREF(std);
1187
1188#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1189 /* Set sys.stderr, replaces the preliminary stderr */
1190 fd = fileno(stderr);
1191 if (!is_valid_fd(fd)) {
1192 std = Py_None;
1193 Py_INCREF(std);
1194 }
1195 else {
1196 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1197 if (std == NULL)
1198 goto error;
1199 } /* if (fd < 0) */
1200
1201 /* Same as hack above, pre-import stderr's codec to avoid recursion
1202 when import.c tries to write to stderr in verbose mode. */
1203 encoding_attr = PyObject_GetAttrString(std, "encoding");
1204 if (encoding_attr != NULL) {
1205 const char * std_encoding;
1206 std_encoding = _PyUnicode_AsString(encoding_attr);
1207 if (std_encoding != NULL) {
1208 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1209 Py_XDECREF(codec_info);
1210 }
1211 Py_DECREF(encoding_attr);
1212 }
1213 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1214
1215 if (PySys_SetObject("__stderr__", std) < 0) {
1216 Py_DECREF(std);
1217 goto error;
1218 }
1219 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1220 Py_DECREF(std);
1221 goto error;
1222 }
1223 Py_DECREF(std);
1224#endif
1225
1226 if (0) {
1227 error:
1228 status = -1;
1229 }
1230
1231 /* We won't need them anymore. */
1232 if (_Py_StandardStreamEncoding) {
1233 PyMem_RawFree(_Py_StandardStreamEncoding);
1234 _Py_StandardStreamEncoding = NULL;
1235 }
1236 if (_Py_StandardStreamErrors) {
1237 PyMem_RawFree(_Py_StandardStreamErrors);
1238 _Py_StandardStreamErrors = NULL;
1239 }
1240 PyMem_Free(pythonioencoding);
1241 Py_XDECREF(bimod);
1242 Py_XDECREF(iomod);
1243 return status;
1244}
1245
1246
1247/* Print fatal error message and abort */
1248
1249void
1250Py_FatalError(const char *msg)
1251{
1252 const int fd = fileno(stderr);
1253 PyThreadState *tstate;
1254
1255 fprintf(stderr, "Fatal Python error: %s\n", msg);
1256 fflush(stderr); /* it helps in Windows debug build */
1257 if (PyErr_Occurred()) {
1258 PyErr_PrintEx(0);
1259 }
1260 else {
1261 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
1262 if (tstate != NULL) {
1263 fputc('\n', stderr);
1264 fflush(stderr);
1265 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
1266 }
1267 _PyFaulthandler_Fini();
1268 }
1269
1270#ifdef MS_WINDOWS
1271 {
1272 size_t len = strlen(msg);
1273 WCHAR* buffer;
1274 size_t i;
1275
1276 /* Convert the message to wchar_t. This uses a simple one-to-one
1277 conversion, assuming that the this error message actually uses ASCII
1278 only. If this ceases to be true, we will have to convert. */
1279 buffer = alloca( (len+1) * (sizeof *buffer));
1280 for( i=0; i<=len; ++i)
1281 buffer[i] = msg[i];
1282 OutputDebugStringW(L"Fatal Python error: ");
1283 OutputDebugStringW(buffer);
1284 OutputDebugStringW(L"\n");
1285 }
1286#ifdef _DEBUG
1287 DebugBreak();
1288#endif
1289#endif /* MS_WINDOWS */
1290 abort();
1291}
1292
1293/* Clean up and exit */
1294
1295#ifdef WITH_THREAD
1296#include "pythread.h"
1297#endif
1298
1299static void (*pyexitfunc)(void) = NULL;
1300/* For the atexit module. */
1301void _Py_PyAtExit(void (*func)(void))
1302{
1303 pyexitfunc = func;
1304}
1305
1306static void
1307call_py_exitfuncs(void)
1308{
1309 if (pyexitfunc == NULL)
1310 return;
1311
1312 (*pyexitfunc)();
1313 PyErr_Clear();
1314}
1315
1316/* Wait until threading._shutdown completes, provided
1317 the threading module was imported in the first place.
1318 The shutdown routine will wait until all non-daemon
1319 "threading" threads have completed. */
1320static void
1321wait_for_thread_shutdown(void)
1322{
1323#ifdef WITH_THREAD
1324 _Py_IDENTIFIER(_shutdown);
1325 PyObject *result;
1326 PyThreadState *tstate = PyThreadState_GET();
1327 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1328 "threading");
1329 if (threading == NULL) {
1330 /* threading not imported */
1331 PyErr_Clear();
1332 return;
1333 }
1334 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
1335 if (result == NULL) {
1336 PyErr_WriteUnraisable(threading);
1337 }
1338 else {
1339 Py_DECREF(result);
1340 }
1341 Py_DECREF(threading);
1342#endif
1343}
1344
1345#define NEXITFUNCS 32
1346static void (*exitfuncs[NEXITFUNCS])(void);
1347static int nexitfuncs = 0;
1348
1349int Py_AtExit(void (*func)(void))
1350{
1351 if (nexitfuncs >= NEXITFUNCS)
1352 return -1;
1353 exitfuncs[nexitfuncs++] = func;
1354 return 0;
1355}
1356
1357static void
1358call_ll_exitfuncs(void)
1359{
1360 while (nexitfuncs > 0)
1361 (*exitfuncs[--nexitfuncs])();
1362
1363 fflush(stdout);
1364 fflush(stderr);
1365}
1366
1367void
1368Py_Exit(int sts)
1369{
1370 Py_Finalize();
1371
1372 exit(sts);
1373}
1374
1375static void
1376initsigs(void)
1377{
1378#ifdef SIGPIPE
1379 PyOS_setsig(SIGPIPE, SIG_IGN);
1380#endif
1381#ifdef SIGXFZ
1382 PyOS_setsig(SIGXFZ, SIG_IGN);
1383#endif
1384#ifdef SIGXFSZ
1385 PyOS_setsig(SIGXFSZ, SIG_IGN);
1386#endif
1387 PyOS_InitInterrupts(); /* May imply initsignal() */
1388 if (PyErr_Occurred()) {
1389 Py_FatalError("Py_Initialize: can't import signal");
1390 }
1391}
1392
1393
1394/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1395 *
1396 * All of the code in this function must only use async-signal-safe functions,
1397 * listed at `man 7 signal` or
1398 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1399 */
1400void
1401_Py_RestoreSignals(void)
1402{
1403#ifdef SIGPIPE
1404 PyOS_setsig(SIGPIPE, SIG_DFL);
1405#endif
1406#ifdef SIGXFZ
1407 PyOS_setsig(SIGXFZ, SIG_DFL);
1408#endif
1409#ifdef SIGXFSZ
1410 PyOS_setsig(SIGXFSZ, SIG_DFL);
1411#endif
1412}
1413
1414
1415/*
1416 * The file descriptor fd is considered ``interactive'' if either
1417 * a) isatty(fd) is TRUE, or
1418 * b) the -i flag was given, and the filename associated with
1419 * the descriptor is NULL or "<stdin>" or "???".
1420 */
1421int
1422Py_FdIsInteractive(FILE *fp, const char *filename)
1423{
1424 if (isatty((int)fileno(fp)))
1425 return 1;
1426 if (!Py_InteractiveFlag)
1427 return 0;
1428 return (filename == NULL) ||
1429 (strcmp(filename, "<stdin>") == 0) ||
1430 (strcmp(filename, "???") == 0);
1431}
1432
1433
Nick Coghland6009512014-11-20 21:39:37 +10001434/* Wrappers around sigaction() or signal(). */
1435
1436PyOS_sighandler_t
1437PyOS_getsig(int sig)
1438{
1439#ifdef HAVE_SIGACTION
1440 struct sigaction context;
1441 if (sigaction(sig, NULL, &context) == -1)
1442 return SIG_ERR;
1443 return context.sa_handler;
1444#else
1445 PyOS_sighandler_t handler;
1446/* Special signal handling for the secure CRT in Visual Studio 2005 */
1447#if defined(_MSC_VER) && _MSC_VER >= 1400
1448 switch (sig) {
1449 /* Only these signals are valid */
1450 case SIGINT:
1451 case SIGILL:
1452 case SIGFPE:
1453 case SIGSEGV:
1454 case SIGTERM:
1455 case SIGBREAK:
1456 case SIGABRT:
1457 break;
1458 /* Don't call signal() with other values or it will assert */
1459 default:
1460 return SIG_ERR;
1461 }
1462#endif /* _MSC_VER && _MSC_VER >= 1400 */
1463 handler = signal(sig, SIG_IGN);
1464 if (handler != SIG_ERR)
1465 signal(sig, handler);
1466 return handler;
1467#endif
1468}
1469
1470/*
1471 * All of the code in this function must only use async-signal-safe functions,
1472 * listed at `man 7 signal` or
1473 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1474 */
1475PyOS_sighandler_t
1476PyOS_setsig(int sig, PyOS_sighandler_t handler)
1477{
1478#ifdef HAVE_SIGACTION
1479 /* Some code in Modules/signalmodule.c depends on sigaction() being
1480 * used here if HAVE_SIGACTION is defined. Fix that if this code
1481 * changes to invalidate that assumption.
1482 */
1483 struct sigaction context, ocontext;
1484 context.sa_handler = handler;
1485 sigemptyset(&context.sa_mask);
1486 context.sa_flags = 0;
1487 if (sigaction(sig, &context, &ocontext) == -1)
1488 return SIG_ERR;
1489 return ocontext.sa_handler;
1490#else
1491 PyOS_sighandler_t oldhandler;
1492 oldhandler = signal(sig, handler);
1493#ifdef HAVE_SIGINTERRUPT
1494 siginterrupt(sig, 1);
1495#endif
1496 return oldhandler;
1497#endif
1498}
1499
1500#ifdef __cplusplus
1501}
1502#endif