runtime: scan register backing store on ia64
[official-gcc.git] / libgo / go / runtime / signal_unix.go
blob02d53488807a433f7847a105c5ceec9c199efc0b
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 "unsafe"
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.
23 type sigTabT struct {
24 flags int32
25 name string
28 //go:linkname os_sigpipe os.sigpipe
29 func os_sigpipe() {
30 systemstack(sigpipe)
33 func signame(sig uint32) string {
34 if sig >= uint32(len(sigtable)) {
35 return ""
37 return sigtable[sig].name
40 const (
41 _SIG_DFL uintptr = 0
42 _SIG_IGN uintptr = 1
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
61 // thread
62 var (
63 disableSigChan chan uint32
64 enableSigChan chan uint32
65 maskUpdatedChan chan struct{}
68 func init() {
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")
77 var signalsOK bool
79 // Initialize signals.
80 // Called by libpreinit so runtime may not be initialized.
81 //go:nosplit
82 //go:nowritebarrierrec
83 func initsig(preinit bool) {
84 if preinit {
85 // preinit is only passed as true if isarchive should be true.
86 isarchive = true
89 if !preinit {
90 // It's now OK for signal handlers to run.
91 signalsOK = true
94 // For c-archive/c-shared this is called by libpreinit with
95 // preinit == true.
96 if (isarchive || islibrary) && !preinit {
97 return
100 for i := uint32(0); i < _NSIG; i++ {
101 t := &sigtable[i]
102 if t.flags == 0 || t.flags&_SigDefault != 0 {
103 continue
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 {
114 setsigstack(i)
116 continue
119 handlingSig[i] = 1
120 setsig(i, getSigtramp())
124 //go:nosplit
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.
130 switch sig {
131 case _SIGHUP, _SIGINT:
132 if atomic.Loaduintptr(&fwdSig[sig]) == _SIG_IGN {
133 return false
137 t := &sigtable[sig]
138 if t.flags&_SigSetStack != 0 {
139 return false
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 {
145 return false
148 return true
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)) {
156 return
159 // SIGPROF is handled specially for profiling.
160 if sig == _SIGPROF {
161 return
164 t := &sigtable[sig]
165 if t.flags&_SigNotify != 0 {
166 ensureSigM()
167 enableSigChan <- sig
168 <-maskUpdatedChan
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)) {
181 return
184 // SIGPROF is handled specially for profiling.
185 if sig == _SIGPROF {
186 return
189 t := &sigtable[sig]
190 if t.flags&_SigNotify != 0 {
191 ensureSigM()
192 disableSigChan <- sig
193 <-maskUpdatedChan
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)) {
210 return
213 // SIGPROF is handled specially for profiling.
214 if sig == _SIGPROF {
215 return
218 t := &sigtable[sig]
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.
229 //go:nosplit
230 //go:nowritebarrierrec
231 func clearSignalHandlers() {
232 for i := uint32(0); i < _NSIG; i++ {
233 if atomic.Load(&handlingSig[i]) != 0 {
234 setsig(i, _SIG_DFL)
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) {
244 if hz != 0 {
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))
250 } else {
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) {
264 var it _itimerval
265 if hz == 0 {
266 setitimer(_ITIMER_PROF, &it, nil)
267 } else {
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)
273 _g_ := getg()
274 _g_.m.profilehz = hz
277 func sigpipe() {
278 if sigsend(_SIGPIPE) {
279 return
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.
293 //go:nosplit
294 //go:nowritebarrierrec
295 func sigtrampgo(sig uint32, info *_siginfo_t, ctx unsafe.Pointer) {
296 if sigfwdgo(sig, info, ctx) {
297 return
299 g := getg()
300 if g == nil {
301 c := sigctxt{info, ctx}
302 if sig == _SIGPROF {
303 _, pc := getSiginfo(info, ctx)
304 sigprofNonGo(pc)
305 return
307 badsignal(uintptr(sig), &c)
308 return
311 setg(g.m.gsignal)
312 sighandler(sig, info, ctx, g)
313 setg(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
322 // instead.
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.
329 func sigpanic() {
330 g := getg()
331 if !canpanic(g) {
332 throw("unexpected signal during runtime execution")
335 switch g.sig {
336 case _SIGBUS:
337 if g.sigcode0 == _BUS_ADRERR && g.sigcode1 < 0x1000 {
338 panicmem()
340 // Support runtime/debug.SetPanicOnFault.
341 if g.paniconfault {
342 panicmem()
344 print("unexpected fault address ", hex(g.sigcode1), "\n")
345 throw("fault")
346 case _SIGSEGV:
347 if (g.sigcode0 == 0 || g.sigcode0 == _SEGV_MAPERR || g.sigcode0 == _SEGV_ACCERR) && g.sigcode1 < 0x1000 {
348 panicmem()
350 // Support runtime/debug.SetPanicOnFault.
351 if g.paniconfault {
352 panicmem()
354 print("unexpected fault address ", hex(g.sigcode1), "\n")
355 throw("fault")
356 case _SIGFPE:
357 switch g.sigcode0 {
358 case _FPE_INTDIV:
359 panicdivide()
360 case _FPE_INTOVF:
361 panicoverflow()
363 panicfloat()
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.
376 //go:nosplit
377 //go:nowritebarrierrec
378 func dieFromSignal(sig uint32) {
379 unblocksig(sig)
380 // Mark the signal as unhandled to ensure it is forwarded.
381 atomic.Store(&handlingSig[sig], 0)
382 raise(sig)
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.
389 osyield()
390 osyield()
391 osyield()
393 // If that didn't work, try _SIG_DFL.
394 setsig(sig, _SIG_DFL)
395 raise(sig)
397 osyield()
398 osyield()
399 osyield()
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" {
406 usleep(100)
409 // If we are still somehow running, just exit with the wrong status.
410 exit(2)
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) {
417 if sig == _SIGPROF {
418 // Ignore profiling signals that arrive on non-Go threads.
419 return
422 var handler uintptr
423 if sig >= _NSIG {
424 handler = _SIG_DFL
425 } else {
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
436 // again.
437 unblocksig(sig)
438 setsig(sig, handler)
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 {
448 return
451 raise(sig)
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.
456 usleep(1000)
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())
467 func crash() {
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" {
476 return
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.
485 func ensureSigM() {
486 if maskUpdatedChan != nil {
487 return
489 maskUpdatedChan = make(chan struct{})
490 disableSigChan = make(chan uint32)
491 enableSigChan = make(chan uint32)
492 go func() {
493 // Signal masks are per-thread, so make sure this goroutine stays on one
494 // thread.
495 LockOSThread()
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
500 // mask accordingly.
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)
509 for {
510 select {
511 case sig := <-enableSigChan:
512 if sig > 0 {
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
528 // signal stack.
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.
553 //go:nosplit
554 //go:norace
555 //go:nowritebarrierrec
556 func badsignal(sig uintptr, c *sigctxt) {
557 needm(0)
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)
563 dropm()
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.
570 //go:nosplit
571 //go:nowritebarrierrec
572 func sigfwdgo(sig uint32, info *_siginfo_t, ctx unsafe.Pointer) bool {
573 if sig >= uint32(len(sigtable)) {
574 return false
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) {
583 return true
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)
589 dieFromSignal(sig)
590 return false
593 sigfwd(fwdFn, sig, info, ctx)
594 return true
597 // If there is no handler to forward to, no need to forward.
598 if fwdFn == _SIG_DFL {
599 return false
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
606 // or pipe.
607 if (c.sigcode() == _SI_USER || flags&_SigPanic == 0) && sig != _SIGPIPE {
608 return false
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.
613 g := getg()
614 if g != nil && g.m != nil && g.m.curg != nil && !g.m.incgo {
615 return false
618 // Signal not handled by Go, forward it.
619 if fwdFn != _SIG_IGN {
620 sigfwd(fwdFn, sig, info, ctx)
623 return true
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.
631 //go:nosplit
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.
642 //go:nosplit
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.
654 //go:nosplit
655 //go:nowritebarrierrec
656 func sigblock() {
657 var set sigset
658 sigfillset(&set)
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.
666 //go:nosplit
667 //go:nowritebarrierrec
668 func unblocksig(sig uint32) {
669 var set sigset
670 sigemptyset(&set)
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() {
678 minitSignalStack()
679 minitSignalMask()
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() {
691 _g_ := getg()
692 var st _stack_t
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
697 } else {
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)) {
714 sigdelset(&nmask, 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.
722 //go:nosplit
723 //go:nowritebarrierrec
724 func unminitSignals() {
725 if getg().m.newSigstack {
726 signalstack(nil, 0)
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 {
741 return false
743 if isarchive || islibrary {
744 return true
746 return flags&(_SigKill|_SigThrow) == 0