Daily bump.
[official-gcc.git] / libgo / go / runtime / signal_unix.go
blob3237e18765f104679319ea1c2240da282e91a7a4
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
7 package runtime
9 import (
10 "runtime/internal/atomic"
11 "runtime/internal/sys"
12 "unsafe"
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
20 func os_sigpipe() {
21 systemstack(sigpipe)
24 func signame(sig uint32) string {
25 if sig >= uint32(len(sigtable)) {
26 return ""
28 return sigtable[sig].name
31 const (
32 _SIG_DFL uintptr = 0
33 _SIG_IGN uintptr = 1
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
52 // thread
53 var (
54 disableSigChan chan uint32
55 enableSigChan chan uint32
56 maskUpdatedChan chan struct{}
59 func init() {
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")
68 var signalsOK bool
70 // Initialize signals.
71 // Called by libpreinit so runtime may not be initialized.
72 //go:nosplit
73 //go:nowritebarrierrec
74 func initsig(preinit bool) {
75 if preinit {
76 // preinit is only passed as true if isarchive should be true.
77 isarchive = true
80 if !preinit {
81 // It's now OK for signal handlers to run.
82 signalsOK = true
85 // For c-archive/c-shared this is called by libpreinit with
86 // preinit == true.
87 if (isarchive || islibrary) && !preinit {
88 return
91 for i := uint32(0); i < _NSIG; i++ {
92 t := &sigtable[i]
93 if t.flags == 0 || t.flags&_SigDefault != 0 {
94 continue
97 // We don't need to use atomic operations here because
98 // there shouldn't be any other goroutines running yet.
99 fwdSig[i] = getsig(i)
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 {
105 setsigstack(i)
107 continue
110 handlingSig[i] = 1
111 setsig(i, getSigtramp())
115 //go:nosplit
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.
121 switch sig {
122 case _SIGHUP, _SIGINT:
123 if atomic.Loaduintptr(&fwdSig[sig]) == _SIG_IGN {
124 return false
128 t := &sigtable[sig]
129 if t.flags&_SigSetStack != 0 {
130 return false
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 {
136 return false
139 return true
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)) {
147 return
150 // SIGPROF is handled specially for profiling.
151 if sig == _SIGPROF {
152 return
155 t := &sigtable[sig]
156 if t.flags&_SigNotify != 0 {
157 ensureSigM()
158 enableSigChan <- sig
159 <-maskUpdatedChan
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)) {
172 return
175 // SIGPROF is handled specially for profiling.
176 if sig == _SIGPROF {
177 return
180 t := &sigtable[sig]
181 if t.flags&_SigNotify != 0 {
182 ensureSigM()
183 disableSigChan <- sig
184 <-maskUpdatedChan
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)) {
201 return
204 // SIGPROF is handled specially for profiling.
205 if sig == _SIGPROF {
206 return
209 t := &sigtable[sig]
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.
220 //go:nosplit
221 //go:nowritebarrierrec
222 func clearSignalHandlers() {
223 for i := uint32(0); i < _NSIG; i++ {
224 if atomic.Load(&handlingSig[i]) != 0 {
225 setsig(i, _SIG_DFL)
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) {
235 if hz != 0 {
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))
241 } else {
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) {
255 var it _itimerval
256 if hz == 0 {
257 setitimer(_ITIMER_PROF, &it, nil)
258 } else {
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)
264 _g_ := getg()
265 _g_.m.profilehz = hz
268 func sigpipe() {
269 if sigsend(_SIGPIPE) {
270 return
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.
278 //go:nosplit
279 //go:nowritebarrierrec
280 func sigtrampgo(sig uint32, info *_siginfo_t, ctx unsafe.Pointer) {
281 if sigfwdgo(sig, info, ctx) {
282 return
284 g := getg()
285 if g == nil {
286 c := sigctxt{info, ctx}
287 if sig == _SIGPROF {
288 _, pc := getSiginfo(info, ctx)
289 sigprofNonGo(pc)
290 return
292 badsignal(uintptr(sig), &c)
293 return
296 setg(g.m.gsignal)
297 sighandler(sig, info, ctx, g)
298 setg(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
307 // instead.
308 func sigpanic() {
309 g := getg()
310 if !canpanic(g) {
311 throw("unexpected signal during runtime execution")
314 switch g.sig {
315 case _SIGBUS:
316 if g.sigcode0 == _BUS_ADRERR && g.sigcode1 < 0x1000 {
317 panicmem()
319 // Support runtime/debug.SetPanicOnFault.
320 if g.paniconfault {
321 panicmem()
323 print("unexpected fault address ", hex(g.sigcode1), "\n")
324 throw("fault")
325 case _SIGSEGV:
326 if (g.sigcode0 == 0 || g.sigcode0 == _SEGV_MAPERR || g.sigcode0 == _SEGV_ACCERR) && g.sigcode1 < 0x1000 {
327 panicmem()
329 // Support runtime/debug.SetPanicOnFault.
330 if g.paniconfault {
331 panicmem()
333 print("unexpected fault address ", hex(g.sigcode1), "\n")
334 throw("fault")
335 case _SIGFPE:
336 switch g.sigcode0 {
337 case _FPE_INTDIV:
338 panicdivide()
339 case _FPE_INTOVF:
340 panicoverflow()
342 panicfloat()
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.
355 //go:nosplit
356 //go:nowritebarrierrec
357 func dieFromSignal(sig uint32) {
358 setsig(sig, _SIG_DFL)
359 unblocksig(sig)
360 raise(sig)
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.
367 osyield()
368 osyield()
369 osyield()
371 // If we are still somehow running, just exit with the wrong status.
372 exit(2)
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) {
379 if sig == _SIGPROF {
380 // Ignore profiling signals that arrive on non-Go threads.
381 return
384 var handler uintptr
385 if sig >= _NSIG {
386 handler = _SIG_DFL
387 } else {
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
398 // again.
399 unblocksig(sig)
400 setsig(sig, handler)
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 {
410 return
413 raise(sig)
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.
418 usleep(1000)
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())
429 func crash() {
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 {
438 return
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.
447 func ensureSigM() {
448 if maskUpdatedChan != nil {
449 return
451 maskUpdatedChan = make(chan struct{})
452 disableSigChan = make(chan uint32)
453 enableSigChan = make(chan uint32)
454 go func() {
455 // Signal masks are per-thread, so make sure this goroutine stays on one
456 // thread.
457 LockOSThread()
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
462 // mask accordingly.
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)
471 for {
472 select {
473 case sig := <-enableSigChan:
474 if sig > 0 {
475 sigdelset(&sigBlocked, int(sig))
477 case sig := <-disableSigChan:
478 if sig > 0 {
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
490 // signal stack.
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.
515 //go:nosplit
516 //go:norace
517 //go:nowritebarrierrec
518 func badsignal(sig uintptr, c *sigctxt) {
519 needm(0)
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)
525 dropm()
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.
532 //go:nosplit
533 //go:nowritebarrierrec
534 func sigfwdgo(sig uint32, info *_siginfo_t, ctx unsafe.Pointer) bool {
535 if sig >= uint32(len(sigtable)) {
536 return false
538 fwdFn := atomic.Loaduintptr(&fwdSig[sig])
540 if !signalsOK {
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
544 // been initialized.
545 if fwdFn == _SIG_DFL {
546 dieFromSignal(sig)
547 } else {
548 sigfwd(fwdFn, sig, info, ctx)
550 return true
553 // If there is no handler to forward to, no need to forward.
554 if fwdFn == _SIG_DFL {
555 return false
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)
565 return true
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
574 // or pipe.
575 if (c.sigcode() == _SI_USER || flags&_SigPanic == 0) && sig != _SIGPIPE {
576 return false
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.
581 g := getg()
582 if g != nil && g.m != nil && g.m.curg != nil && !g.m.incgo {
583 return false
586 // Signal not handled by Go, forward it.
587 if fwdFn != _SIG_IGN {
588 sigfwd(fwdFn, sig, info, ctx)
591 return true
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.
599 //go:nosplit
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.
610 //go:nosplit
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.
622 //go:nosplit
623 //go:nowritebarrierrec
624 func sigblock() {
625 var set sigset
626 sigfillset(&set)
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.
634 //go:nosplit
635 //go:nowritebarrierrec
636 func unblocksig(sig uint32) {
637 var set sigset
638 sigemptyset(&set)
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() {
646 minitSignalStack()
647 minitSignalMask()
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() {
659 _g_ := getg()
660 var st _stack_t
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
665 } else {
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 {
682 sigdelset(&nmask, i)
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.
690 //go:nosplit
691 //go:nowritebarrierrec
692 func unminitSignals() {
693 if getg().m.newSigstack {
694 signalstack(nil, 0)