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"
11 "runtime/internal/sys"
15 // For gccgo's C code to call:
16 //go:linkname initsig runtime.initsig
17 //go:linkname sigtrampgo runtime.sigtrampgo
19 //go:linkname os_sigpipe os.sigpipe
24 func signame(sig
uint32) string {
25 if sig
>= uint32(len(sigtable
)) {
28 return sigtable
[sig
].name
36 // Stores the signal handlers registered before Go installed its own.
37 // These signal handlers will be invoked in cases where Go doesn't want to
38 // handle a particular signal (e.g., signal occurred on a non-Go thread).
39 // See sigfwdgo for more information on when the signals are forwarded.
41 // This is read by the signal handler; accesses should use
42 // atomic.Loaduintptr and atomic.Storeuintptr.
43 var fwdSig
[_NSIG
]uintptr
45 // handlingSig is indexed by signal number and is non-zero if we are
46 // currently handling the signal. Or, to put it another way, whether
47 // the signal handler is currently set to the Go signal handler or not.
48 // This is uint32 rather than bool so that we can use atomic instructions.
49 var handlingSig
[_NSIG
]uint32
51 // channels for synchronizing signal mask updates with the signal mask
54 disableSigChan
chan uint32
55 enableSigChan
chan uint32
56 maskUpdatedChan
chan struct{}
60 // _NSIG is the number of signals on this operating system.
61 // sigtable should describe what to do for all the possible signals.
62 if len(sigtable
) != _NSIG
{
63 print("runtime: len(sigtable)=", len(sigtable
), " _NSIG=", _NSIG
, "\n")
64 throw("bad sigtable len")
70 // Initialize signals.
71 // Called by libpreinit so runtime may not be initialized.
73 //go:nowritebarrierrec
74 func initsig(preinit
bool) {
76 // preinit is only passed as true if isarchive should be true.
81 // It's now OK for signal handlers to run.
85 // For c-archive/c-shared this is called by libpreinit with
87 if (isarchive || islibrary
) && !preinit
{
91 for i
:= uint32(0); i
< _NSIG
; i
++ {
93 if t
.flags
== 0 || t
.flags
&_SigDefault
!= 0 {
97 // We don't need to use atomic operations here because
98 // there shouldn't be any other goroutines running yet.
101 if !sigInstallGoHandler(i
) {
102 // Even if we are not installing a signal handler,
103 // set SA_ONSTACK if necessary.
104 if fwdSig
[i
] != _SIG_DFL
&& fwdSig
[i
] != _SIG_IGN
{
111 setsig(i
, getSigtramp())
116 //go:nowritebarrierrec
117 func sigInstallGoHandler(sig
uint32) bool {
118 // For some signals, we respect an inherited SIG_IGN handler
119 // rather than insist on installing our own default handler.
120 // Even these signals can be fetched using the os/signal package.
122 case _SIGHUP
, _SIGINT
:
123 if atomic
.Loaduintptr(&fwdSig
[sig
]) == _SIG_IGN
{
129 if t
.flags
&_SigSetStack
!= 0 {
133 // When built using c-archive or c-shared, only install signal
134 // handlers for synchronous signals and SIGPIPE.
135 if (isarchive || islibrary
) && t
.flags
&_SigPanic
== 0 && sig
!= _SIGPIPE
{
142 // sigenable enables the Go signal handler to catch the signal sig.
143 // It is only called while holding the os/signal.handlers lock,
144 // via os/signal.enableSignal and signal_enable.
145 func sigenable(sig
uint32) {
146 if sig
>= uint32(len(sigtable
)) {
150 // SIGPROF is handled specially for profiling.
156 if t
.flags
&_SigNotify
!= 0 {
160 if atomic
.Cas(&handlingSig
[sig
], 0, 1) {
161 atomic
.Storeuintptr(&fwdSig
[sig
], getsig(sig
))
162 setsig(sig
, getSigtramp())
167 // sigdisable disables the Go signal handler for the signal sig.
168 // It is only called while holding the os/signal.handlers lock,
169 // via os/signal.disableSignal and signal_disable.
170 func sigdisable(sig
uint32) {
171 if sig
>= uint32(len(sigtable
)) {
175 // SIGPROF is handled specially for profiling.
181 if t
.flags
&_SigNotify
!= 0 {
183 disableSigChan
<- sig
186 // If initsig does not install a signal handler for a
187 // signal, then to go back to the state before Notify
188 // we should remove the one we installed.
189 if !sigInstallGoHandler(sig
) {
190 atomic
.Store(&handlingSig
[sig
], 0)
191 setsig(sig
, atomic
.Loaduintptr(&fwdSig
[sig
]))
196 // sigignore ignores the signal sig.
197 // It is only called while holding the os/signal.handlers lock,
198 // via os/signal.ignoreSignal and signal_ignore.
199 func sigignore(sig
uint32) {
200 if sig
>= uint32(len(sigtable
)) {
204 // SIGPROF is handled specially for profiling.
210 if t
.flags
&_SigNotify
!= 0 {
211 atomic
.Store(&handlingSig
[sig
], 0)
212 setsig(sig
, _SIG_IGN
)
216 // clearSignalHandlers clears all signal handlers that are not ignored
217 // back to the default. This is called by the child after a fork, so that
218 // we can enable the signal mask for the exec without worrying about
219 // running a signal handler in the child.
221 //go:nowritebarrierrec
222 func clearSignalHandlers() {
223 for i
:= uint32(0); i
< _NSIG
; i
++ {
224 if atomic
.Load(&handlingSig
[i
]) != 0 {
230 // setProcessCPUProfiler is called when the profiling timer changes.
231 // It is called with prof.lock held. hz is the new timer, and is 0 if
232 // profiling is being disabled. Enable or disable the signal as
233 // required for -buildmode=c-archive.
234 func setProcessCPUProfiler(hz
int32) {
236 // Enable the Go signal handler if not enabled.
237 if atomic
.Cas(&handlingSig
[_SIGPROF
], 0, 1) {
238 atomic
.Storeuintptr(&fwdSig
[_SIGPROF
], getsig(_SIGPROF
))
239 setsig(_SIGPROF
, funcPC(sighandler
))
242 // If the Go signal handler should be disabled by default,
243 // disable it if it is enabled.
244 if !sigInstallGoHandler(_SIGPROF
) {
245 if atomic
.Cas(&handlingSig
[_SIGPROF
], 1, 0) {
246 setsig(_SIGPROF
, atomic
.Loaduintptr(&fwdSig
[_SIGPROF
]))
252 // setThreadCPUProfiler makes any thread-specific changes required to
253 // implement profiling at a rate of hz.
254 func setThreadCPUProfiler(hz
int32) {
257 setitimer(_ITIMER_PROF
, &it
, nil)
259 it
.it_interval
.tv_sec
= 0
260 it
.it_interval
.set_usec(1000000 / hz
)
261 it
.it_value
= it
.it_interval
262 setitimer(_ITIMER_PROF
, &it
, nil)
269 if sigsend(_SIGPIPE
) {
272 dieFromSignal(_SIGPIPE
)
275 // sigtrampgo is called from the signal handler function, sigtramp,
276 // written in assembly code.
277 // This is called by the signal handler, and the world may be stopped.
279 //go:nowritebarrierrec
280 func sigtrampgo(sig
uint32, info
*_siginfo_t
, ctx unsafe
.Pointer
) {
281 if sigfwdgo(sig
, info
, ctx
) {
286 c
:= sigctxt
{info
, ctx
}
288 _
, pc
:= getSiginfo(info
, ctx
)
292 badsignal(uintptr(sig
), &c
)
297 sighandler(sig
, info
, ctx
, g
)
301 // sigpanic turns a synchronous signal into a run-time panic.
302 // If the signal handler sees a synchronous panic, it arranges the
303 // stack to look like the function where the signal occurred called
304 // sigpanic, sets the signal's PC value to sigpanic, and returns from
305 // the signal handler. The effect is that the program will act as
306 // though the function that got the signal simply called sigpanic
311 throw("unexpected signal during runtime execution")
316 if g
.sigcode0
== _BUS_ADRERR
&& g
.sigcode1
< 0x1000 {
319 // Support runtime/debug.SetPanicOnFault.
323 print("unexpected fault address ", hex(g
.sigcode1
), "\n")
326 if (g
.sigcode0
== 0 || g
.sigcode0
== _SEGV_MAPERR || g
.sigcode0
== _SEGV_ACCERR
) && g
.sigcode1
< 0x1000 {
329 // Support runtime/debug.SetPanicOnFault.
333 print("unexpected fault address ", hex(g
.sigcode1
), "\n")
345 if g
.sig
>= uint32(len(sigtable
)) {
346 // can't happen: we looked up g.sig in sigtable to decide to call sigpanic
347 throw("unexpected signal value")
349 panic(errorString(sigtable
[g
.sig
].name
))
352 // dieFromSignal kills the program with a signal.
353 // This provides the expected exit status for the shell.
354 // This is only called with fatal signals expected to kill the process.
356 //go:nowritebarrierrec
357 func dieFromSignal(sig
uint32) {
358 setsig(sig
, _SIG_DFL
)
362 // That should have killed us. On some systems, though, raise
363 // sends the signal to the whole process rather than to just
364 // the current thread, which means that the signal may not yet
365 // have been delivered. Give other threads a chance to run and
366 // pick up the signal.
371 // If we are still somehow running, just exit with the wrong status.
375 // raisebadsignal is called when a signal is received on a non-Go
376 // thread, and the Go program does not want to handle it (that is, the
377 // program has not called os/signal.Notify for the signal).
378 func raisebadsignal(sig
uint32, c
*sigctxt
) {
380 // Ignore profiling signals that arrive on non-Go threads.
388 handler
= atomic
.Loaduintptr(&fwdSig
[sig
])
391 // Reset the signal handler and raise the signal.
392 // We are currently running inside a signal handler, so the
393 // signal is blocked. We need to unblock it before raising the
394 // signal, or the signal we raise will be ignored until we return
395 // from the signal handler. We know that the signal was unblocked
396 // before entering the handler, or else we would not have received
397 // it. That means that we don't have to worry about blocking it
402 // If we're linked into a non-Go program we want to try to
403 // avoid modifying the original context in which the signal
404 // was raised. If the handler is the default, we know it
405 // is non-recoverable, so we don't have to worry about
406 // re-installing sighandler. At this point we can just
407 // return and the signal will be re-raised and caught by
408 // the default handler with the correct context.
409 if (isarchive || islibrary
) && handler
== _SIG_DFL
&& c
.sigcode() != _SI_USER
{
415 // Give the signal a chance to be delivered.
416 // In almost all real cases the program is about to crash,
417 // so sleeping here is not a waste of time.
420 // If the signal didn't cause the program to exit, restore the
421 // Go signal handler and carry on.
423 // We may receive another instance of the signal before we
424 // restore the Go handler, but that is not so bad: we know
425 // that the Go program has been ignoring the signal.
426 setsig(sig
, getSigtramp())
430 if GOOS
== "darwin" {
431 // OS X core dumps are linear dumps of the mapped memory,
432 // from the first virtual byte to the last, with zeros in the gaps.
433 // Because of the way we arrange the address space on 64-bit systems,
434 // this means the OS X core file will be >128 GB and even on a zippy
435 // workstation can take OS X well over an hour to write (uninterruptible).
436 // Save users from making that mistake.
437 if sys
.PtrSize
== 8 {
442 dieFromSignal(_SIGABRT
)
445 // ensureSigM starts one global, sleeping thread to make sure at least one thread
446 // is available to catch signals enabled for os/signal.
448 if maskUpdatedChan
!= nil {
451 maskUpdatedChan
= make(chan struct{})
452 disableSigChan
= make(chan uint32)
453 enableSigChan
= make(chan uint32)
455 // Signal masks are per-thread, so make sure this goroutine stays on one
458 defer UnlockOSThread()
459 // The sigBlocked mask contains the signals not active for os/signal,
460 // initially all signals except the essential. When signal.Notify()/Stop is called,
461 // sigenable/sigdisable in turn notify this thread to update its signal
463 var sigBlocked sigset
464 sigfillset(&sigBlocked
)
465 for i
:= range sigtable
{
466 if sigtable
[i
].flags
&_SigUnblock
!= 0 {
467 sigdelset(&sigBlocked
, i
)
470 sigprocmask(_SIG_SETMASK
, &sigBlocked
, nil)
473 case sig
:= <-enableSigChan
:
475 sigdelset(&sigBlocked
, int(sig
))
477 case sig
:= <-disableSigChan
:
479 sigaddset(&sigBlocked
, int(sig
))
482 sigprocmask(_SIG_SETMASK
, &sigBlocked
, nil)
483 maskUpdatedChan
<- struct{}{}
488 // This is called when we receive a signal when there is no signal stack.
489 // This can only happen if non-Go code calls sigaltstack to disable the
491 func noSignalStack(sig
uint32) {
492 println("signal", sig
, "received on thread with no signal stack")
493 throw("non-Go code disabled sigaltstack")
496 // This is called if we receive a signal when there is a signal stack
497 // but we are not on it. This can only happen if non-Go code called
498 // sigaction without setting the SS_ONSTACK flag.
499 func sigNotOnStack(sig
uint32) {
500 println("signal", sig
, "received but handler not on signal stack")
501 throw("non-Go code set up signal handler without SA_ONSTACK flag")
504 // signalDuringFork is called if we receive a signal while doing a fork.
505 // We do not want signals at that time, as a signal sent to the process
506 // group may be delivered to the child process, causing confusion.
507 // This should never be called, because we block signals across the fork;
508 // this function is just a safety check. See issue 18600 for background.
509 func signalDuringFork(sig
uint32) {
510 println("signal", sig
, "received during fork")
511 throw("signal received during fork")
514 // This runs on a foreign stack, without an m or a g. No stack split.
517 //go:nowritebarrierrec
518 func badsignal(sig
uintptr, c
*sigctxt
) {
520 if !sigsend(uint32(sig
)) {
521 // A foreign thread received the signal sig, and the
522 // Go code does not want to handle it.
523 raisebadsignal(uint32(sig
), c
)
528 // Determines if the signal should be handled by Go and if not, forwards the
529 // signal to the handler that was installed before Go's. Returns whether the
530 // signal was forwarded.
531 // This is called by the signal handler, and the world may be stopped.
533 //go:nowritebarrierrec
534 func sigfwdgo(sig
uint32, info
*_siginfo_t
, ctx unsafe
.Pointer
) bool {
535 if sig
>= uint32(len(sigtable
)) {
538 fwdFn
:= atomic
.Loaduintptr(&fwdSig
[sig
])
541 // The only way we can get here is if we are in a
542 // library or archive, we installed a signal handler
543 // at program startup, but the Go runtime has not yet
545 if fwdFn
== _SIG_DFL
{
548 sigfwd(fwdFn
, sig
, info
, ctx
)
553 // If there is no handler to forward to, no need to forward.
554 if fwdFn
== _SIG_DFL
{
558 // If we aren't handling the signal, forward it.
559 // Really if we aren't handling the signal, we shouldn't get here,
560 // but on Darwin setsigstack can lead us here because it sets
561 // the sa_tramp field. The sa_tramp field is not returned by
562 // sigaction, so the fix for that is non-obvious.
563 if atomic
.Load(&handlingSig
[sig
]) == 0 {
564 sigfwd(fwdFn
, sig
, info
, ctx
)
568 flags
:= sigtable
[sig
].flags
570 c
:= sigctxt
{info
, ctx
}
571 // Only forward synchronous signals and SIGPIPE.
572 // Unfortunately, user generated SIGPIPEs will also be forwarded, because si_code
573 // is set to _SI_USER even for a SIGPIPE raised from a write to a closed socket
575 if (c
.sigcode() == _SI_USER || flags
&_SigPanic
== 0) && sig
!= _SIGPIPE
{
578 // Determine if the signal occurred inside Go code. We test that:
579 // (1) we were in a goroutine (i.e., m.curg != nil), and
580 // (2) we weren't in CGO.
582 if g
!= nil && g
.m
!= nil && g
.m
.curg
!= nil && !g
.m
.incgo
{
586 // Signal not handled by Go, forward it.
587 if fwdFn
!= _SIG_IGN
{
588 sigfwd(fwdFn
, sig
, info
, ctx
)
594 // msigsave saves the current thread's signal mask into mp.sigmask.
595 // This is used to preserve the non-Go signal mask when a non-Go
596 // thread calls a Go function.
597 // This is nosplit and nowritebarrierrec because it is called by needm
598 // which may be called on a non-Go thread with no g available.
600 //go:nowritebarrierrec
601 func msigsave(mp
*m
) {
602 sigprocmask(_SIG_SETMASK
, nil, &mp
.sigmask
)
605 // msigrestore sets the current thread's signal mask to sigmask.
606 // This is used to restore the non-Go signal mask when a non-Go thread
607 // calls a Go function.
608 // This is nosplit and nowritebarrierrec because it is called by dropm
609 // after g has been cleared.
611 //go:nowritebarrierrec
612 func msigrestore(sigmask sigset
) {
613 sigprocmask(_SIG_SETMASK
, &sigmask
, nil)
616 // sigblock blocks all signals in the current thread's signal mask.
617 // This is used to block signals while setting up and tearing down g
618 // when a non-Go thread calls a Go function.
619 // The OS-specific code is expected to define sigset_all.
620 // This is nosplit and nowritebarrierrec because it is called by needm
621 // which may be called on a non-Go thread with no g available.
623 //go:nowritebarrierrec
627 sigprocmask(_SIG_SETMASK
, &set
, nil)
630 // unblocksig removes sig from the current thread's signal mask.
631 // This is nosplit and nowritebarrierrec because it is called from
632 // dieFromSignal, which can be called by sigfwdgo while running in the
633 // signal handler, on the signal stack, with no g available.
635 //go:nowritebarrierrec
636 func unblocksig(sig
uint32) {
639 sigaddset(&set
, int(sig
))
640 sigprocmask(_SIG_UNBLOCK
, &set
, nil)
643 // minitSignals is called when initializing a new m to set the
644 // thread's alternate signal stack and signal mask.
645 func minitSignals() {
650 // minitSignalStack is called when initializing a new m to set the
651 // alternate signal stack. If the alternate signal stack is not set
652 // for the thread (the normal case) then set the alternate signal
653 // stack to the gsignal stack. If the alternate signal stack is set
654 // for the thread (the case when a non-Go thread sets the alternate
655 // signal stack and then calls a Go function) then set the gsignal
656 // stack to the alternate signal stack. Record which choice was made
657 // in newSigstack, so that it can be undone in unminit.
658 func minitSignalStack() {
661 sigaltstack(nil, &st
)
662 if st
.ss_flags
&_SS_DISABLE
!= 0 {
663 signalstack(_g_
.m
.gsignalstack
, _g_
.m
.gsignalstacksize
)
664 _g_
.m
.newSigstack
= true
666 _g_
.m
.newSigstack
= false
670 // minitSignalMask is called when initializing a new m to set the
671 // thread's signal mask. When this is called all signals have been
672 // blocked for the thread. This starts with m.sigmask, which was set
673 // either from initSigmask for a newly created thread or by calling
674 // msigsave if this is a non-Go thread calling a Go function. It
675 // removes all essential signals from the mask, thus causing those
676 // signals to not be blocked. Then it sets the thread's signal mask.
677 // After this is called the thread can receive signals.
678 func minitSignalMask() {
679 nmask
:= getg().m
.sigmask
680 for i
:= range sigtable
{
681 if sigtable
[i
].flags
&_SigUnblock
!= 0 {
685 sigprocmask(_SIG_SETMASK
, &nmask
, nil)
688 // unminitSignals is called from dropm, via unminit, to undo the
689 // effect of calling minit on a non-Go thread.
691 //go:nowritebarrierrec
692 func unminitSignals() {
693 if getg().m
.newSigstack
{