1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
10 "runtime/internal/atomic"
14 // For gccgo's C code to call:
15 //go:linkname initsig runtime.initsig
16 //go:linkname sigtrampgo runtime.sigtrampgo
18 // sigTabT is the type of an entry in the global sigtable array.
19 // sigtable is inherently system dependent, and appears in OS-specific files,
20 // but sigTabT is the same for all Unixy systems.
21 // The sigtable array is indexed by a system signal number to get the flags
22 // and printable name of each signal.
28 //go:linkname os_sigpipe os.sigpipe
33 func signame(sig
uint32) string {
34 if sig
>= uint32(len(sigtable
)) {
37 return sigtable
[sig
].name
45 // Stores the signal handlers registered before Go installed its own.
46 // These signal handlers will be invoked in cases where Go doesn't want to
47 // handle a particular signal (e.g., signal occurred on a non-Go thread).
48 // See sigfwdgo for more information on when the signals are forwarded.
50 // This is read by the signal handler; accesses should use
51 // atomic.Loaduintptr and atomic.Storeuintptr.
52 var fwdSig
[_NSIG
]uintptr
54 // handlingSig is indexed by signal number and is non-zero if we are
55 // currently handling the signal. Or, to put it another way, whether
56 // the signal handler is currently set to the Go signal handler or not.
57 // This is uint32 rather than bool so that we can use atomic instructions.
58 var handlingSig
[_NSIG
]uint32
60 // channels for synchronizing signal mask updates with the signal mask
63 disableSigChan
chan uint32
64 enableSigChan
chan uint32
65 maskUpdatedChan
chan struct{}
69 // _NSIG is the number of signals on this operating system.
70 // sigtable should describe what to do for all the possible signals.
71 if len(sigtable
) != _NSIG
{
72 print("runtime: len(sigtable)=", len(sigtable
), " _NSIG=", _NSIG
, "\n")
73 throw("bad sigtable len")
79 // Initialize signals.
80 // Called by libpreinit so runtime may not be initialized.
82 //go:nowritebarrierrec
83 func initsig(preinit
bool) {
85 // preinit is only passed as true if isarchive should be true.
90 // It's now OK for signal handlers to run.
94 // For c-archive/c-shared this is called by libpreinit with
96 if (isarchive || islibrary
) && !preinit
{
100 for i
:= uint32(0); i
< _NSIG
; i
++ {
102 if t
.flags
== 0 || t
.flags
&_SigDefault
!= 0 {
106 // We don't need to use atomic operations here because
107 // there shouldn't be any other goroutines running yet.
108 fwdSig
[i
] = getsig(i
)
110 if !sigInstallGoHandler(i
) {
111 // Even if we are not installing a signal handler,
112 // set SA_ONSTACK if necessary.
113 if fwdSig
[i
] != _SIG_DFL
&& fwdSig
[i
] != _SIG_IGN
{
120 setsig(i
, getSigtramp())
125 //go:nowritebarrierrec
126 func sigInstallGoHandler(sig
uint32) bool {
127 // For some signals, we respect an inherited SIG_IGN handler
128 // rather than insist on installing our own default handler.
129 // Even these signals can be fetched using the os/signal package.
131 case _SIGHUP
, _SIGINT
:
132 if atomic
.Loaduintptr(&fwdSig
[sig
]) == _SIG_IGN
{
138 if t
.flags
&_SigSetStack
!= 0 {
142 // When built using c-archive or c-shared, only install signal
143 // handlers for synchronous signals and SIGPIPE.
144 if (isarchive || islibrary
) && t
.flags
&_SigPanic
== 0 && sig
!= _SIGPIPE
{
151 // sigenable enables the Go signal handler to catch the signal sig.
152 // It is only called while holding the os/signal.handlers lock,
153 // via os/signal.enableSignal and signal_enable.
154 func sigenable(sig
uint32) {
155 if sig
>= uint32(len(sigtable
)) {
159 // SIGPROF is handled specially for profiling.
165 if t
.flags
&_SigNotify
!= 0 {
169 if atomic
.Cas(&handlingSig
[sig
], 0, 1) {
170 atomic
.Storeuintptr(&fwdSig
[sig
], getsig(sig
))
171 setsig(sig
, getSigtramp())
176 // sigdisable disables the Go signal handler for the signal sig.
177 // It is only called while holding the os/signal.handlers lock,
178 // via os/signal.disableSignal and signal_disable.
179 func sigdisable(sig
uint32) {
180 if sig
>= uint32(len(sigtable
)) {
184 // SIGPROF is handled specially for profiling.
190 if t
.flags
&_SigNotify
!= 0 {
192 disableSigChan
<- sig
195 // If initsig does not install a signal handler for a
196 // signal, then to go back to the state before Notify
197 // we should remove the one we installed.
198 if !sigInstallGoHandler(sig
) {
199 atomic
.Store(&handlingSig
[sig
], 0)
200 setsig(sig
, atomic
.Loaduintptr(&fwdSig
[sig
]))
205 // sigignore ignores the signal sig.
206 // It is only called while holding the os/signal.handlers lock,
207 // via os/signal.ignoreSignal and signal_ignore.
208 func sigignore(sig
uint32) {
209 if sig
>= uint32(len(sigtable
)) {
213 // SIGPROF is handled specially for profiling.
219 if t
.flags
&_SigNotify
!= 0 {
220 atomic
.Store(&handlingSig
[sig
], 0)
221 setsig(sig
, _SIG_IGN
)
225 // clearSignalHandlers clears all signal handlers that are not ignored
226 // back to the default. This is called by the child after a fork, so that
227 // we can enable the signal mask for the exec without worrying about
228 // running a signal handler in the child.
230 //go:nowritebarrierrec
231 func clearSignalHandlers() {
232 for i
:= uint32(0); i
< _NSIG
; i
++ {
233 if atomic
.Load(&handlingSig
[i
]) != 0 {
239 // setProcessCPUProfiler is called when the profiling timer changes.
240 // It is called with prof.lock held. hz is the new timer, and is 0 if
241 // profiling is being disabled. Enable or disable the signal as
242 // required for -buildmode=c-archive.
243 func setProcessCPUProfiler(hz
int32) {
245 // Enable the Go signal handler if not enabled.
246 if atomic
.Cas(&handlingSig
[_SIGPROF
], 0, 1) {
247 atomic
.Storeuintptr(&fwdSig
[_SIGPROF
], getsig(_SIGPROF
))
248 setsig(_SIGPROF
, getSigtramp())
251 // If the Go signal handler should be disabled by default,
252 // disable it if it is enabled.
253 if !sigInstallGoHandler(_SIGPROF
) {
254 if atomic
.Cas(&handlingSig
[_SIGPROF
], 1, 0) {
255 setsig(_SIGPROF
, atomic
.Loaduintptr(&fwdSig
[_SIGPROF
]))
261 // setThreadCPUProfiler makes any thread-specific changes required to
262 // implement profiling at a rate of hz.
263 func setThreadCPUProfiler(hz
int32) {
266 setitimer(_ITIMER_PROF
, &it
, nil)
268 it
.it_interval
.tv_sec
= 0
269 it
.it_interval
.set_usec(1000000 / hz
)
270 it
.it_value
= it
.it_interval
271 setitimer(_ITIMER_PROF
, &it
, nil)
278 if sigsend(_SIGPIPE
) {
281 dieFromSignal(_SIGPIPE
)
284 // sigtrampgo is called from the signal handler function, sigtramp,
285 // written in assembly code.
286 // This is called by the signal handler, and the world may be stopped.
288 // It must be nosplit because getg() is still the G that was running
289 // (if any) when the signal was delivered, but it's (usually) called
290 // on the gsignal stack. Until this switches the G to gsignal, the
291 // stack bounds check won't work.
294 //go:nowritebarrierrec
295 func sigtrampgo(sig
uint32, info
*_siginfo_t
, ctx unsafe
.Pointer
) {
296 if sigfwdgo(sig
, info
, ctx
) {
301 c
:= sigctxt
{info
, ctx
}
303 _
, pc
:= getSiginfo(info
, ctx
)
307 badsignal(uintptr(sig
), &c
)
312 sighandler(sig
, info
, ctx
, g
)
316 // sigpanic turns a synchronous signal into a run-time panic.
317 // If the signal handler sees a synchronous panic, it arranges the
318 // stack to look like the function where the signal occurred called
319 // sigpanic, sets the signal's PC value to sigpanic, and returns from
320 // the signal handler. The effect is that the program will act as
321 // though the function that got the signal simply called sigpanic
324 // This must NOT be nosplit because the linker doesn't know where
325 // sigpanic calls can be injected.
327 // The signal handler must not inject a call to sigpanic if
328 // getg().throwsplit, since sigpanic may need to grow the stack.
332 throw("unexpected signal during runtime execution")
337 if g
.sigcode0
== _BUS_ADRERR
&& g
.sigcode1
< 0x1000 {
340 // Support runtime/debug.SetPanicOnFault.
344 print("unexpected fault address ", hex(g
.sigcode1
), "\n")
347 if (g
.sigcode0
== 0 || g
.sigcode0
== _SEGV_MAPERR || g
.sigcode0
== _SEGV_ACCERR
) && g
.sigcode1
< 0x1000 {
350 // Support runtime/debug.SetPanicOnFault.
354 print("unexpected fault address ", hex(g
.sigcode1
), "\n")
366 if g
.sig
>= uint32(len(sigtable
)) {
367 // can't happen: we looked up g.sig in sigtable to decide to call sigpanic
368 throw("unexpected signal value")
370 panic(errorString(sigtable
[g
.sig
].name
))
373 // dieFromSignal kills the program with a signal.
374 // This provides the expected exit status for the shell.
375 // This is only called with fatal signals expected to kill the process.
377 //go:nowritebarrierrec
378 func dieFromSignal(sig
uint32) {
380 // Mark the signal as unhandled to ensure it is forwarded.
381 atomic
.Store(&handlingSig
[sig
], 0)
384 // That should have killed us. On some systems, though, raise
385 // sends the signal to the whole process rather than to just
386 // the current thread, which means that the signal may not yet
387 // have been delivered. Give other threads a chance to run and
388 // pick up the signal.
393 // If that didn't work, try _SIG_DFL.
394 setsig(sig
, _SIG_DFL
)
401 // On Darwin we may still fail to die, because raise sends the
402 // signal to the whole process rather than just the current thread,
403 // and osyield just sleeps briefly rather than letting all other
404 // threads run. See issue 20315. Sleep longer.
405 if GOOS
== "darwin" {
409 // If we are still somehow running, just exit with the wrong status.
413 // raisebadsignal is called when a signal is received on a non-Go
414 // thread, and the Go program does not want to handle it (that is, the
415 // program has not called os/signal.Notify for the signal).
416 func raisebadsignal(sig
uint32, c
*sigctxt
) {
418 // Ignore profiling signals that arrive on non-Go threads.
426 handler
= atomic
.Loaduintptr(&fwdSig
[sig
])
429 // Reset the signal handler and raise the signal.
430 // We are currently running inside a signal handler, so the
431 // signal is blocked. We need to unblock it before raising the
432 // signal, or the signal we raise will be ignored until we return
433 // from the signal handler. We know that the signal was unblocked
434 // before entering the handler, or else we would not have received
435 // it. That means that we don't have to worry about blocking it
440 // If we're linked into a non-Go program we want to try to
441 // avoid modifying the original context in which the signal
442 // was raised. If the handler is the default, we know it
443 // is non-recoverable, so we don't have to worry about
444 // re-installing sighandler. At this point we can just
445 // return and the signal will be re-raised and caught by
446 // the default handler with the correct context.
447 if (isarchive || islibrary
) && handler
== _SIG_DFL
&& c
.sigcode() != _SI_USER
{
453 // Give the signal a chance to be delivered.
454 // In almost all real cases the program is about to crash,
455 // so sleeping here is not a waste of time.
458 // If the signal didn't cause the program to exit, restore the
459 // Go signal handler and carry on.
461 // We may receive another instance of the signal before we
462 // restore the Go handler, but that is not so bad: we know
463 // that the Go program has been ignoring the signal.
464 setsig(sig
, getSigtramp())
468 if GOOS
== "darwin" {
469 // OS X core dumps are linear dumps of the mapped memory,
470 // from the first virtual byte to the last, with zeros in the gaps.
471 // Because of the way we arrange the address space on 64-bit systems,
472 // this means the OS X core file will be >128 GB and even on a zippy
473 // workstation can take OS X well over an hour to write (uninterruptible).
474 // Save users from making that mistake.
475 if GOARCH
== "amd64" {
480 dieFromSignal(_SIGABRT
)
483 // ensureSigM starts one global, sleeping thread to make sure at least one thread
484 // is available to catch signals enabled for os/signal.
486 if maskUpdatedChan
!= nil {
489 maskUpdatedChan
= make(chan struct{})
490 disableSigChan
= make(chan uint32)
491 enableSigChan
= make(chan uint32)
493 // Signal masks are per-thread, so make sure this goroutine stays on one
496 defer UnlockOSThread()
497 // The sigBlocked mask contains the signals not active for os/signal,
498 // initially all signals except the essential. When signal.Notify()/Stop is called,
499 // sigenable/sigdisable in turn notify this thread to update its signal
501 var sigBlocked sigset
502 sigfillset(&sigBlocked
)
503 for i
:= range sigtable
{
504 if !blockableSig(uint32(i
)) {
505 sigdelset(&sigBlocked
, i
)
508 sigprocmask(_SIG_SETMASK
, &sigBlocked
, nil)
511 case sig
:= <-enableSigChan
:
513 sigdelset(&sigBlocked
, int(sig
))
515 case sig
:= <-disableSigChan
:
516 if sig
> 0 && blockableSig(sig
) {
517 sigaddset(&sigBlocked
, int(sig
))
520 sigprocmask(_SIG_SETMASK
, &sigBlocked
, nil)
521 maskUpdatedChan
<- struct{}{}
526 // This is called when we receive a signal when there is no signal stack.
527 // This can only happen if non-Go code calls sigaltstack to disable the
529 func noSignalStack(sig
uint32) {
530 println("signal", sig
, "received on thread with no signal stack")
531 throw("non-Go code disabled sigaltstack")
534 // This is called if we receive a signal when there is a signal stack
535 // but we are not on it. This can only happen if non-Go code called
536 // sigaction without setting the SS_ONSTACK flag.
537 func sigNotOnStack(sig
uint32) {
538 println("signal", sig
, "received but handler not on signal stack")
539 throw("non-Go code set up signal handler without SA_ONSTACK flag")
542 // signalDuringFork is called if we receive a signal while doing a fork.
543 // We do not want signals at that time, as a signal sent to the process
544 // group may be delivered to the child process, causing confusion.
545 // This should never be called, because we block signals across the fork;
546 // this function is just a safety check. See issue 18600 for background.
547 func signalDuringFork(sig
uint32) {
548 println("signal", sig
, "received during fork")
549 throw("signal received during fork")
552 // This runs on a foreign stack, without an m or a g. No stack split.
555 //go:nowritebarrierrec
556 func badsignal(sig
uintptr, c
*sigctxt
) {
558 if !sigsend(uint32(sig
)) {
559 // A foreign thread received the signal sig, and the
560 // Go code does not want to handle it.
561 raisebadsignal(uint32(sig
), c
)
566 // Determines if the signal should be handled by Go and if not, forwards the
567 // signal to the handler that was installed before Go's. Returns whether the
568 // signal was forwarded.
569 // This is called by the signal handler, and the world may be stopped.
571 //go:nowritebarrierrec
572 func sigfwdgo(sig
uint32, info
*_siginfo_t
, ctx unsafe
.Pointer
) bool {
573 if sig
>= uint32(len(sigtable
)) {
576 fwdFn
:= atomic
.Loaduintptr(&fwdSig
[sig
])
577 flags
:= sigtable
[sig
].flags
579 // If we aren't handling the signal, forward it.
580 if atomic
.Load(&handlingSig
[sig
]) == 0 ||
!signalsOK
{
581 // If the signal is ignored, doing nothing is the same as forwarding.
582 if fwdFn
== _SIG_IGN ||
(fwdFn
== _SIG_DFL
&& flags
&_SigIgn
!= 0) {
585 // We are not handling the signal and there is no other handler to forward to.
586 // Crash with the default behavior.
587 if fwdFn
== _SIG_DFL
{
588 setsig(sig
, _SIG_DFL
)
593 sigfwd(fwdFn
, sig
, info
, ctx
)
597 // If there is no handler to forward to, no need to forward.
598 if fwdFn
== _SIG_DFL
{
602 c
:= sigctxt
{info
, ctx
}
603 // Only forward synchronous signals and SIGPIPE.
604 // Unfortunately, user generated SIGPIPEs will also be forwarded, because si_code
605 // is set to _SI_USER even for a SIGPIPE raised from a write to a closed socket
607 if (c
.sigcode() == _SI_USER || flags
&_SigPanic
== 0) && sig
!= _SIGPIPE
{
610 // Determine if the signal occurred inside Go code. We test that:
611 // (1) we were in a goroutine (i.e., m.curg != nil), and
612 // (2) we weren't in CGO.
614 if g
!= nil && g
.m
!= nil && g
.m
.curg
!= nil && !g
.m
.incgo
{
618 // Signal not handled by Go, forward it.
619 if fwdFn
!= _SIG_IGN
{
620 sigfwd(fwdFn
, sig
, info
, ctx
)
626 // msigsave saves the current thread's signal mask into mp.sigmask.
627 // This is used to preserve the non-Go signal mask when a non-Go
628 // thread calls a Go function.
629 // This is nosplit and nowritebarrierrec because it is called by needm
630 // which may be called on a non-Go thread with no g available.
632 //go:nowritebarrierrec
633 func msigsave(mp
*m
) {
634 sigprocmask(_SIG_SETMASK
, nil, &mp
.sigmask
)
637 // msigrestore sets the current thread's signal mask to sigmask.
638 // This is used to restore the non-Go signal mask when a non-Go thread
639 // calls a Go function.
640 // This is nosplit and nowritebarrierrec because it is called by dropm
641 // after g has been cleared.
643 //go:nowritebarrierrec
644 func msigrestore(sigmask sigset
) {
645 sigprocmask(_SIG_SETMASK
, &sigmask
, nil)
648 // sigblock blocks all signals in the current thread's signal mask.
649 // This is used to block signals while setting up and tearing down g
650 // when a non-Go thread calls a Go function.
651 // The OS-specific code is expected to define sigset_all.
652 // This is nosplit and nowritebarrierrec because it is called by needm
653 // which may be called on a non-Go thread with no g available.
655 //go:nowritebarrierrec
659 sigprocmask(_SIG_SETMASK
, &set
, nil)
662 // unblocksig removes sig from the current thread's signal mask.
663 // This is nosplit and nowritebarrierrec because it is called from
664 // dieFromSignal, which can be called by sigfwdgo while running in the
665 // signal handler, on the signal stack, with no g available.
667 //go:nowritebarrierrec
668 func unblocksig(sig
uint32) {
671 sigaddset(&set
, int(sig
))
672 sigprocmask(_SIG_UNBLOCK
, &set
, nil)
675 // minitSignals is called when initializing a new m to set the
676 // thread's alternate signal stack and signal mask.
677 func minitSignals() {
682 // minitSignalStack is called when initializing a new m to set the
683 // alternate signal stack. If the alternate signal stack is not set
684 // for the thread (the normal case) then set the alternate signal
685 // stack to the gsignal stack. If the alternate signal stack is set
686 // for the thread (the case when a non-Go thread sets the alternate
687 // signal stack and then calls a Go function) then set the gsignal
688 // stack to the alternate signal stack. Record which choice was made
689 // in newSigstack, so that it can be undone in unminit.
690 func minitSignalStack() {
693 sigaltstack(nil, &st
)
694 if st
.ss_flags
&_SS_DISABLE
!= 0 {
695 signalstack(_g_
.m
.gsignalstack
, _g_
.m
.gsignalstacksize
)
696 _g_
.m
.newSigstack
= true
698 _g_
.m
.newSigstack
= false
702 // minitSignalMask is called when initializing a new m to set the
703 // thread's signal mask. When this is called all signals have been
704 // blocked for the thread. This starts with m.sigmask, which was set
705 // either from initSigmask for a newly created thread or by calling
706 // msigsave if this is a non-Go thread calling a Go function. It
707 // removes all essential signals from the mask, thus causing those
708 // signals to not be blocked. Then it sets the thread's signal mask.
709 // After this is called the thread can receive signals.
710 func minitSignalMask() {
711 nmask
:= getg().m
.sigmask
712 for i
:= range sigtable
{
713 if !blockableSig(uint32(i
)) {
717 sigprocmask(_SIG_SETMASK
, &nmask
, nil)
720 // unminitSignals is called from dropm, via unminit, to undo the
721 // effect of calling minit on a non-Go thread.
723 //go:nowritebarrierrec
724 func unminitSignals() {
725 if getg().m
.newSigstack
{
730 // blockableSig returns whether sig may be blocked by the signal mask.
731 // We never want to block the signals marked _SigUnblock;
732 // these are the synchronous signals that turn into a Go panic.
733 // In a Go program--not a c-archive/c-shared--we never want to block
734 // the signals marked _SigKill or _SigThrow, as otherwise it's possible
735 // for all running threads to block them and delay their delivery until
736 // we start a new thread. When linked into a C program we let the C code
737 // decide on the disposition of those signals.
738 func blockableSig(sig
uint32) bool {
739 flags
:= sigtable
[sig
].flags
740 if flags
&_SigUnblock
!= 0 {
743 if isarchive || islibrary
{
746 return flags
&(_SigKill|_SigThrow
) == 0