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
, funcPC(sighandler
))
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
326 throw("unexpected signal during runtime execution")
331 if g
.sigcode0
== _BUS_ADRERR
&& g
.sigcode1
< 0x1000 {
334 // Support runtime/debug.SetPanicOnFault.
338 print("unexpected fault address ", hex(g
.sigcode1
), "\n")
341 if (g
.sigcode0
== 0 || g
.sigcode0
== _SEGV_MAPERR || g
.sigcode0
== _SEGV_ACCERR
) && g
.sigcode1
< 0x1000 {
344 // Support runtime/debug.SetPanicOnFault.
348 print("unexpected fault address ", hex(g
.sigcode1
), "\n")
360 if g
.sig
>= uint32(len(sigtable
)) {
361 // can't happen: we looked up g.sig in sigtable to decide to call sigpanic
362 throw("unexpected signal value")
364 panic(errorString(sigtable
[g
.sig
].name
))
367 // dieFromSignal kills the program with a signal.
368 // This provides the expected exit status for the shell.
369 // This is only called with fatal signals expected to kill the process.
371 //go:nowritebarrierrec
372 func dieFromSignal(sig
uint32) {
374 // Mark the signal as unhandled to ensure it is forwarded.
375 atomic
.Store(&handlingSig
[sig
], 0)
378 // That should have killed us. On some systems, though, raise
379 // sends the signal to the whole process rather than to just
380 // the current thread, which means that the signal may not yet
381 // have been delivered. Give other threads a chance to run and
382 // pick up the signal.
387 // If that didn't work, try _SIG_DFL.
388 setsig(sig
, _SIG_DFL
)
395 // On Darwin we may still fail to die, because raise sends the
396 // signal to the whole process rather than just the current thread,
397 // and osyield just sleeps briefly rather than letting all other
398 // threads run. See issue 20315. Sleep longer.
399 if GOOS
== "darwin" {
403 // If we are still somehow running, just exit with the wrong status.
407 // raisebadsignal is called when a signal is received on a non-Go
408 // thread, and the Go program does not want to handle it (that is, the
409 // program has not called os/signal.Notify for the signal).
410 func raisebadsignal(sig
uint32, c
*sigctxt
) {
412 // Ignore profiling signals that arrive on non-Go threads.
420 handler
= atomic
.Loaduintptr(&fwdSig
[sig
])
423 // Reset the signal handler and raise the signal.
424 // We are currently running inside a signal handler, so the
425 // signal is blocked. We need to unblock it before raising the
426 // signal, or the signal we raise will be ignored until we return
427 // from the signal handler. We know that the signal was unblocked
428 // before entering the handler, or else we would not have received
429 // it. That means that we don't have to worry about blocking it
434 // If we're linked into a non-Go program we want to try to
435 // avoid modifying the original context in which the signal
436 // was raised. If the handler is the default, we know it
437 // is non-recoverable, so we don't have to worry about
438 // re-installing sighandler. At this point we can just
439 // return and the signal will be re-raised and caught by
440 // the default handler with the correct context.
441 if (isarchive || islibrary
) && handler
== _SIG_DFL
&& c
.sigcode() != _SI_USER
{
447 // Give the signal a chance to be delivered.
448 // In almost all real cases the program is about to crash,
449 // so sleeping here is not a waste of time.
452 // If the signal didn't cause the program to exit, restore the
453 // Go signal handler and carry on.
455 // We may receive another instance of the signal before we
456 // restore the Go handler, but that is not so bad: we know
457 // that the Go program has been ignoring the signal.
458 setsig(sig
, getSigtramp())
462 if GOOS
== "darwin" {
463 // OS X core dumps are linear dumps of the mapped memory,
464 // from the first virtual byte to the last, with zeros in the gaps.
465 // Because of the way we arrange the address space on 64-bit systems,
466 // this means the OS X core file will be >128 GB and even on a zippy
467 // workstation can take OS X well over an hour to write (uninterruptible).
468 // Save users from making that mistake.
469 if GOARCH
== "amd64" {
474 dieFromSignal(_SIGABRT
)
477 // ensureSigM starts one global, sleeping thread to make sure at least one thread
478 // is available to catch signals enabled for os/signal.
480 if maskUpdatedChan
!= nil {
483 maskUpdatedChan
= make(chan struct{})
484 disableSigChan
= make(chan uint32)
485 enableSigChan
= make(chan uint32)
487 // Signal masks are per-thread, so make sure this goroutine stays on one
490 defer UnlockOSThread()
491 // The sigBlocked mask contains the signals not active for os/signal,
492 // initially all signals except the essential. When signal.Notify()/Stop is called,
493 // sigenable/sigdisable in turn notify this thread to update its signal
495 var sigBlocked sigset
496 sigfillset(&sigBlocked
)
497 for i
:= range sigtable
{
498 if !blockableSig(uint32(i
)) {
499 sigdelset(&sigBlocked
, i
)
502 sigprocmask(_SIG_SETMASK
, &sigBlocked
, nil)
505 case sig
:= <-enableSigChan
:
507 sigdelset(&sigBlocked
, int(sig
))
509 case sig
:= <-disableSigChan
:
510 if sig
> 0 && blockableSig(sig
) {
511 sigaddset(&sigBlocked
, int(sig
))
514 sigprocmask(_SIG_SETMASK
, &sigBlocked
, nil)
515 maskUpdatedChan
<- struct{}{}
520 // This is called when we receive a signal when there is no signal stack.
521 // This can only happen if non-Go code calls sigaltstack to disable the
523 func noSignalStack(sig
uint32) {
524 println("signal", sig
, "received on thread with no signal stack")
525 throw("non-Go code disabled sigaltstack")
528 // This is called if we receive a signal when there is a signal stack
529 // but we are not on it. This can only happen if non-Go code called
530 // sigaction without setting the SS_ONSTACK flag.
531 func sigNotOnStack(sig
uint32) {
532 println("signal", sig
, "received but handler not on signal stack")
533 throw("non-Go code set up signal handler without SA_ONSTACK flag")
536 // signalDuringFork is called if we receive a signal while doing a fork.
537 // We do not want signals at that time, as a signal sent to the process
538 // group may be delivered to the child process, causing confusion.
539 // This should never be called, because we block signals across the fork;
540 // this function is just a safety check. See issue 18600 for background.
541 func signalDuringFork(sig
uint32) {
542 println("signal", sig
, "received during fork")
543 throw("signal received during fork")
546 // This runs on a foreign stack, without an m or a g. No stack split.
549 //go:nowritebarrierrec
550 func badsignal(sig
uintptr, c
*sigctxt
) {
552 if !sigsend(uint32(sig
)) {
553 // A foreign thread received the signal sig, and the
554 // Go code does not want to handle it.
555 raisebadsignal(uint32(sig
), c
)
560 // Determines if the signal should be handled by Go and if not, forwards the
561 // signal to the handler that was installed before Go's. Returns whether the
562 // signal was forwarded.
563 // This is called by the signal handler, and the world may be stopped.
565 //go:nowritebarrierrec
566 func sigfwdgo(sig
uint32, info
*_siginfo_t
, ctx unsafe
.Pointer
) bool {
567 if sig
>= uint32(len(sigtable
)) {
570 fwdFn
:= atomic
.Loaduintptr(&fwdSig
[sig
])
571 flags
:= sigtable
[sig
].flags
573 // If we aren't handling the signal, forward it.
574 if atomic
.Load(&handlingSig
[sig
]) == 0 ||
!signalsOK
{
575 // If the signal is ignored, doing nothing is the same as forwarding.
576 if fwdFn
== _SIG_IGN ||
(fwdFn
== _SIG_DFL
&& flags
&_SigIgn
!= 0) {
579 // We are not handling the signal and there is no other handler to forward to.
580 // Crash with the default behavior.
581 if fwdFn
== _SIG_DFL
{
582 setsig(sig
, _SIG_DFL
)
587 sigfwd(fwdFn
, sig
, info
, ctx
)
591 // If there is no handler to forward to, no need to forward.
592 if fwdFn
== _SIG_DFL
{
596 c
:= sigctxt
{info
, ctx
}
597 // Only forward synchronous signals and SIGPIPE.
598 // Unfortunately, user generated SIGPIPEs will also be forwarded, because si_code
599 // is set to _SI_USER even for a SIGPIPE raised from a write to a closed socket
601 if (c
.sigcode() == _SI_USER || flags
&_SigPanic
== 0) && sig
!= _SIGPIPE
{
604 // Determine if the signal occurred inside Go code. We test that:
605 // (1) we were in a goroutine (i.e., m.curg != nil), and
606 // (2) we weren't in CGO.
608 if g
!= nil && g
.m
!= nil && g
.m
.curg
!= nil && !g
.m
.incgo
{
612 // Signal not handled by Go, forward it.
613 if fwdFn
!= _SIG_IGN
{
614 sigfwd(fwdFn
, sig
, info
, ctx
)
620 // msigsave saves the current thread's signal mask into mp.sigmask.
621 // This is used to preserve the non-Go signal mask when a non-Go
622 // thread calls a Go function.
623 // This is nosplit and nowritebarrierrec because it is called by needm
624 // which may be called on a non-Go thread with no g available.
626 //go:nowritebarrierrec
627 func msigsave(mp
*m
) {
628 sigprocmask(_SIG_SETMASK
, nil, &mp
.sigmask
)
631 // msigrestore sets the current thread's signal mask to sigmask.
632 // This is used to restore the non-Go signal mask when a non-Go thread
633 // calls a Go function.
634 // This is nosplit and nowritebarrierrec because it is called by dropm
635 // after g has been cleared.
637 //go:nowritebarrierrec
638 func msigrestore(sigmask sigset
) {
639 sigprocmask(_SIG_SETMASK
, &sigmask
, nil)
642 // sigblock blocks all signals in the current thread's signal mask.
643 // This is used to block signals while setting up and tearing down g
644 // when a non-Go thread calls a Go function.
645 // The OS-specific code is expected to define sigset_all.
646 // This is nosplit and nowritebarrierrec because it is called by needm
647 // which may be called on a non-Go thread with no g available.
649 //go:nowritebarrierrec
653 sigprocmask(_SIG_SETMASK
, &set
, nil)
656 // unblocksig removes sig from the current thread's signal mask.
657 // This is nosplit and nowritebarrierrec because it is called from
658 // dieFromSignal, which can be called by sigfwdgo while running in the
659 // signal handler, on the signal stack, with no g available.
661 //go:nowritebarrierrec
662 func unblocksig(sig
uint32) {
665 sigaddset(&set
, int(sig
))
666 sigprocmask(_SIG_UNBLOCK
, &set
, nil)
669 // minitSignals is called when initializing a new m to set the
670 // thread's alternate signal stack and signal mask.
671 func minitSignals() {
676 // minitSignalStack is called when initializing a new m to set the
677 // alternate signal stack. If the alternate signal stack is not set
678 // for the thread (the normal case) then set the alternate signal
679 // stack to the gsignal stack. If the alternate signal stack is set
680 // for the thread (the case when a non-Go thread sets the alternate
681 // signal stack and then calls a Go function) then set the gsignal
682 // stack to the alternate signal stack. Record which choice was made
683 // in newSigstack, so that it can be undone in unminit.
684 func minitSignalStack() {
687 sigaltstack(nil, &st
)
688 if st
.ss_flags
&_SS_DISABLE
!= 0 {
689 signalstack(_g_
.m
.gsignalstack
, _g_
.m
.gsignalstacksize
)
690 _g_
.m
.newSigstack
= true
692 _g_
.m
.newSigstack
= false
696 // minitSignalMask is called when initializing a new m to set the
697 // thread's signal mask. When this is called all signals have been
698 // blocked for the thread. This starts with m.sigmask, which was set
699 // either from initSigmask for a newly created thread or by calling
700 // msigsave if this is a non-Go thread calling a Go function. It
701 // removes all essential signals from the mask, thus causing those
702 // signals to not be blocked. Then it sets the thread's signal mask.
703 // After this is called the thread can receive signals.
704 func minitSignalMask() {
705 nmask
:= getg().m
.sigmask
706 for i
:= range sigtable
{
707 if !blockableSig(uint32(i
)) {
711 sigprocmask(_SIG_SETMASK
, &nmask
, nil)
714 // unminitSignals is called from dropm, via unminit, to undo the
715 // effect of calling minit on a non-Go thread.
717 //go:nowritebarrierrec
718 func unminitSignals() {
719 if getg().m
.newSigstack
{
724 // blockableSig returns whether sig may be blocked by the signal mask.
725 // We never want to block the signals marked _SigUnblock;
726 // these are the synchronous signals that turn into a Go panic.
727 // In a Go program--not a c-archive/c-shared--we never want to block
728 // the signals marked _SigKill or _SigThrow, as otherwise it's possible
729 // for all running threads to block them and delay their delivery until
730 // we start a new thread. When linked into a C program we let the C code
731 // decide on the disposition of those signals.
732 func blockableSig(sig
uint32) bool {
733 flags
:= sigtable
[sig
].flags
734 if flags
&_SigUnblock
!= 0 {
737 if isarchive || islibrary
{
740 return flags
&(_SigKill|_SigThrow
) == 0