Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/signal_unix.go

Documentation: runtime

     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.
     4  
     5  // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
     6  
     7  package runtime
     8  
     9  import (
    10  	"runtime/internal/atomic"
    11  	"unsafe"
    12  )
    13  
    14  // sigTabT is the type of an entry in the global sigtable array.
    15  // sigtable is inherently system dependent, and appears in OS-specific files,
    16  // but sigTabT is the same for all Unixy systems.
    17  // The sigtable array is indexed by a system signal number to get the flags
    18  // and printable name of each signal.
    19  type sigTabT struct {
    20  	flags int32
    21  	name  string
    22  }
    23  
    24  //go:linkname os_sigpipe os.sigpipe
    25  func os_sigpipe() {
    26  	systemstack(sigpipe)
    27  }
    28  
    29  func signame(sig uint32) string {
    30  	if sig >= uint32(len(sigtable)) {
    31  		return ""
    32  	}
    33  	return sigtable[sig].name
    34  }
    35  
    36  const (
    37  	_SIG_DFL uintptr = 0
    38  	_SIG_IGN uintptr = 1
    39  )
    40  
    41  // sigPreempt is the signal used for non-cooperative preemption.
    42  //
    43  // There's no good way to choose this signal, but there are some
    44  // heuristics:
    45  //
    46  // 1. It should be a signal that's passed-through by debuggers by
    47  // default. On Linux, this is SIGALRM, SIGURG, SIGCHLD, SIGIO,
    48  // SIGVTALRM, SIGPROF, and SIGWINCH, plus some glibc-internal signals.
    49  //
    50  // 2. It shouldn't be used internally by libc in mixed Go/C binaries
    51  // because libc may assume it's the only thing that can handle these
    52  // signals. For example SIGCANCEL or SIGSETXID.
    53  //
    54  // 3. It should be a signal that can happen spuriously without
    55  // consequences. For example, SIGALRM is a bad choice because the
    56  // signal handler can't tell if it was caused by the real process
    57  // alarm or not (arguably this means the signal is broken, but I
    58  // digress). SIGUSR1 and SIGUSR2 are also bad because those are often
    59  // used in meaningful ways by applications.
    60  //
    61  // 4. We need to deal with platforms without real-time signals (like
    62  // macOS), so those are out.
    63  //
    64  // We use SIGURG because it meets all of these criteria, is extremely
    65  // unlikely to be used by an application for its "real" meaning (both
    66  // because out-of-band data is basically unused and because SIGURG
    67  // doesn't report which socket has the condition, making it pretty
    68  // useless), and even if it is, the application has to be ready for
    69  // spurious SIGURG. SIGIO wouldn't be a bad choice either, but is more
    70  // likely to be used for real.
    71  const sigPreempt = _SIGURG
    72  
    73  // Stores the signal handlers registered before Go installed its own.
    74  // These signal handlers will be invoked in cases where Go doesn't want to
    75  // handle a particular signal (e.g., signal occurred on a non-Go thread).
    76  // See sigfwdgo for more information on when the signals are forwarded.
    77  //
    78  // This is read by the signal handler; accesses should use
    79  // atomic.Loaduintptr and atomic.Storeuintptr.
    80  var fwdSig [_NSIG]uintptr
    81  
    82  // handlingSig is indexed by signal number and is non-zero if we are
    83  // currently handling the signal. Or, to put it another way, whether
    84  // the signal handler is currently set to the Go signal handler or not.
    85  // This is uint32 rather than bool so that we can use atomic instructions.
    86  var handlingSig [_NSIG]uint32
    87  
    88  // channels for synchronizing signal mask updates with the signal mask
    89  // thread
    90  var (
    91  	disableSigChan  chan uint32
    92  	enableSigChan   chan uint32
    93  	maskUpdatedChan chan struct{}
    94  )
    95  
    96  func init() {
    97  	// _NSIG is the number of signals on this operating system.
    98  	// sigtable should describe what to do for all the possible signals.
    99  	if len(sigtable) != _NSIG {
   100  		print("runtime: len(sigtable)=", len(sigtable), " _NSIG=", _NSIG, "\n")
   101  		throw("bad sigtable len")
   102  	}
   103  }
   104  
   105  var signalsOK bool
   106  
   107  // Initialize signals.
   108  // Called by libpreinit so runtime may not be initialized.
   109  //go:nosplit
   110  //go:nowritebarrierrec
   111  func initsig(preinit bool) {
   112  	if !preinit {
   113  		// It's now OK for signal handlers to run.
   114  		signalsOK = true
   115  	}
   116  
   117  	// For c-archive/c-shared this is called by libpreinit with
   118  	// preinit == true.
   119  	if (isarchive || islibrary) && !preinit {
   120  		return
   121  	}
   122  
   123  	for i := uint32(0); i < _NSIG; i++ {
   124  		t := &sigtable[i]
   125  		if t.flags == 0 || t.flags&_SigDefault != 0 {
   126  			continue
   127  		}
   128  
   129  		// We don't need to use atomic operations here because
   130  		// there shouldn't be any other goroutines running yet.
   131  		fwdSig[i] = getsig(i)
   132  
   133  		if !sigInstallGoHandler(i) {
   134  			// Even if we are not installing a signal handler,
   135  			// set SA_ONSTACK if necessary.
   136  			if fwdSig[i] != _SIG_DFL && fwdSig[i] != _SIG_IGN {
   137  				setsigstack(i)
   138  			} else if fwdSig[i] == _SIG_IGN {
   139  				sigInitIgnored(i)
   140  			}
   141  			continue
   142  		}
   143  
   144  		handlingSig[i] = 1
   145  		setsig(i, funcPC(sighandler))
   146  	}
   147  }
   148  
   149  //go:nosplit
   150  //go:nowritebarrierrec
   151  func sigInstallGoHandler(sig uint32) bool {
   152  	// For some signals, we respect an inherited SIG_IGN handler
   153  	// rather than insist on installing our own default handler.
   154  	// Even these signals can be fetched using the os/signal package.
   155  	switch sig {
   156  	case _SIGHUP, _SIGINT:
   157  		if atomic.Loaduintptr(&fwdSig[sig]) == _SIG_IGN {
   158  			return false
   159  		}
   160  	}
   161  
   162  	t := &sigtable[sig]
   163  	if t.flags&_SigSetStack != 0 {
   164  		return false
   165  	}
   166  
   167  	// When built using c-archive or c-shared, only install signal
   168  	// handlers for synchronous signals and SIGPIPE.
   169  	if (isarchive || islibrary) && t.flags&_SigPanic == 0 && sig != _SIGPIPE {
   170  		return false
   171  	}
   172  
   173  	return true
   174  }
   175  
   176  // sigenable enables the Go signal handler to catch the signal sig.
   177  // It is only called while holding the os/signal.handlers lock,
   178  // via os/signal.enableSignal and signal_enable.
   179  func sigenable(sig uint32) {
   180  	if sig >= uint32(len(sigtable)) {
   181  		return
   182  	}
   183  
   184  	// SIGPROF is handled specially for profiling.
   185  	if sig == _SIGPROF {
   186  		return
   187  	}
   188  
   189  	t := &sigtable[sig]
   190  	if t.flags&_SigNotify != 0 {
   191  		ensureSigM()
   192  		enableSigChan <- sig
   193  		<-maskUpdatedChan
   194  		if atomic.Cas(&handlingSig[sig], 0, 1) {
   195  			atomic.Storeuintptr(&fwdSig[sig], getsig(sig))
   196  			setsig(sig, funcPC(sighandler))
   197  		}
   198  	}
   199  }
   200  
   201  // sigdisable disables the Go signal handler for the signal sig.
   202  // It is only called while holding the os/signal.handlers lock,
   203  // via os/signal.disableSignal and signal_disable.
   204  func sigdisable(sig uint32) {
   205  	if sig >= uint32(len(sigtable)) {
   206  		return
   207  	}
   208  
   209  	// SIGPROF is handled specially for profiling.
   210  	if sig == _SIGPROF {
   211  		return
   212  	}
   213  
   214  	t := &sigtable[sig]
   215  	if t.flags&_SigNotify != 0 {
   216  		ensureSigM()
   217  		disableSigChan <- sig
   218  		<-maskUpdatedChan
   219  
   220  		// If initsig does not install a signal handler for a
   221  		// signal, then to go back to the state before Notify
   222  		// we should remove the one we installed.
   223  		if !sigInstallGoHandler(sig) {
   224  			atomic.Store(&handlingSig[sig], 0)
   225  			setsig(sig, atomic.Loaduintptr(&fwdSig[sig]))
   226  		}
   227  	}
   228  }
   229  
   230  // sigignore ignores the signal sig.
   231  // It is only called while holding the os/signal.handlers lock,
   232  // via os/signal.ignoreSignal and signal_ignore.
   233  func sigignore(sig uint32) {
   234  	if sig >= uint32(len(sigtable)) {
   235  		return
   236  	}
   237  
   238  	// SIGPROF is handled specially for profiling.
   239  	if sig == _SIGPROF {
   240  		return
   241  	}
   242  
   243  	t := &sigtable[sig]
   244  	if t.flags&_SigNotify != 0 {
   245  		atomic.Store(&handlingSig[sig], 0)
   246  		setsig(sig, _SIG_IGN)
   247  	}
   248  }
   249  
   250  // clearSignalHandlers clears all signal handlers that are not ignored
   251  // back to the default. This is called by the child after a fork, so that
   252  // we can enable the signal mask for the exec without worrying about
   253  // running a signal handler in the child.
   254  //go:nosplit
   255  //go:nowritebarrierrec
   256  func clearSignalHandlers() {
   257  	for i := uint32(0); i < _NSIG; i++ {
   258  		if atomic.Load(&handlingSig[i]) != 0 {
   259  			setsig(i, _SIG_DFL)
   260  		}
   261  	}
   262  }
   263  
   264  // setProcessCPUProfiler is called when the profiling timer changes.
   265  // It is called with prof.lock held. hz is the new timer, and is 0 if
   266  // profiling is being disabled. Enable or disable the signal as
   267  // required for -buildmode=c-archive.
   268  func setProcessCPUProfiler(hz int32) {
   269  	if hz != 0 {
   270  		// Enable the Go signal handler if not enabled.
   271  		if atomic.Cas(&handlingSig[_SIGPROF], 0, 1) {
   272  			atomic.Storeuintptr(&fwdSig[_SIGPROF], getsig(_SIGPROF))
   273  			setsig(_SIGPROF, funcPC(sighandler))
   274  		}
   275  	} else {
   276  		// If the Go signal handler should be disabled by default,
   277  		// switch back to the signal handler that was installed
   278  		// when we enabled profiling. We don't try to handle the case
   279  		// of a program that changes the SIGPROF handler while Go
   280  		// profiling is enabled.
   281  		//
   282  		// If no signal handler was installed before, then start
   283  		// ignoring SIGPROF signals. We do this, rather than change
   284  		// to SIG_DFL, because there may be a pending SIGPROF
   285  		// signal that has not yet been delivered to some other thread.
   286  		// If we change to SIG_DFL here, the program will crash
   287  		// when that SIGPROF is delivered. We assume that programs
   288  		// that use profiling don't want to crash on a stray SIGPROF.
   289  		// See issue 19320.
   290  		if !sigInstallGoHandler(_SIGPROF) {
   291  			if atomic.Cas(&handlingSig[_SIGPROF], 1, 0) {
   292  				h := atomic.Loaduintptr(&fwdSig[_SIGPROF])
   293  				if h == _SIG_DFL {
   294  					h = _SIG_IGN
   295  				}
   296  				setsig(_SIGPROF, h)
   297  			}
   298  		}
   299  	}
   300  }
   301  
   302  // setThreadCPUProfiler makes any thread-specific changes required to
   303  // implement profiling at a rate of hz.
   304  func setThreadCPUProfiler(hz int32) {
   305  	var it itimerval
   306  	if hz == 0 {
   307  		setitimer(_ITIMER_PROF, &it, nil)
   308  	} else {
   309  		it.it_interval.tv_sec = 0
   310  		it.it_interval.set_usec(1000000 / hz)
   311  		it.it_value = it.it_interval
   312  		setitimer(_ITIMER_PROF, &it, nil)
   313  	}
   314  	_g_ := getg()
   315  	_g_.m.profilehz = hz
   316  }
   317  
   318  func sigpipe() {
   319  	if signal_ignored(_SIGPIPE) || sigsend(_SIGPIPE) {
   320  		return
   321  	}
   322  	dieFromSignal(_SIGPIPE)
   323  }
   324  
   325  // doSigPreempt handles a preemption signal on gp.
   326  func doSigPreempt(gp *g, ctxt *sigctxt) {
   327  	// Check if this G wants to be preempted and is safe to
   328  	// preempt.
   329  	if wantAsyncPreempt(gp) && isAsyncSafePoint(gp, ctxt.sigpc(), ctxt.sigsp(), ctxt.siglr()) {
   330  		// Inject a call to asyncPreempt.
   331  		ctxt.pushCall(funcPC(asyncPreempt))
   332  	}
   333  
   334  	// Acknowledge the preemption.
   335  	atomic.Xadd(&gp.m.preemptGen, 1)
   336  	atomic.Store(&gp.m.signalPending, 0)
   337  }
   338  
   339  const preemptMSupported = pushCallSupported
   340  
   341  // preemptM sends a preemption request to mp. This request may be
   342  // handled asynchronously and may be coalesced with other requests to
   343  // the M. When the request is received, if the running G or P are
   344  // marked for preemption and the goroutine is at an asynchronous
   345  // safe-point, it will preempt the goroutine. It always atomically
   346  // increments mp.preemptGen after handling a preemption request.
   347  func preemptM(mp *m) {
   348  	if !pushCallSupported {
   349  		// This architecture doesn't support ctxt.pushCall
   350  		// yet, so doSigPreempt won't work.
   351  		return
   352  	}
   353  	if GOOS == "darwin" && (GOARCH == "arm" || GOARCH == "arm64") && !iscgo {
   354  		// On darwin, we use libc calls, and cgo is required on ARM and ARM64
   355  		// so we have TLS set up to save/restore G during C calls. If cgo is
   356  		// absent, we cannot save/restore G in TLS, and if a signal is
   357  		// received during C execution we cannot get the G. Therefore don't
   358  		// send signals.
   359  		// This can only happen in the go_bootstrap program (otherwise cgo is
   360  		// required).
   361  		return
   362  	}
   363  	if atomic.Cas(&mp.signalPending, 0, 1) {
   364  		// If multiple threads are preempting the same M, it may send many
   365  		// signals to the same M such that it hardly make progress, causing
   366  		// live-lock problem. Apparently this could happen on darwin. See
   367  		// issue #37741.
   368  		// Only send a signal if there isn't already one pending.
   369  		signalM(mp, sigPreempt)
   370  	}
   371  }
   372  
   373  // sigFetchG fetches the value of G safely when running in a signal handler.
   374  // On some architectures, the g value may be clobbered when running in a VDSO.
   375  // See issue #32912.
   376  //
   377  //go:nosplit
   378  func sigFetchG(c *sigctxt) *g {
   379  	switch GOARCH {
   380  	case "arm", "arm64":
   381  		if !iscgo && inVDSOPage(c.sigpc()) {
   382  			// When using cgo, we save the g on TLS and load it from there
   383  			// in sigtramp. Just use that.
   384  			// Otherwise, before making a VDSO call we save the g to the
   385  			// bottom of the signal stack. Fetch from there.
   386  			// TODO: in efence mode, stack is sysAlloc'd, so this wouldn't
   387  			// work.
   388  			sp := getcallersp()
   389  			s := spanOf(sp)
   390  			if s != nil && s.state.get() == mSpanManual && s.base() < sp && sp < s.limit {
   391  				gp := *(**g)(unsafe.Pointer(s.base()))
   392  				return gp
   393  			}
   394  			return nil
   395  		}
   396  	}
   397  	return getg()
   398  }
   399  
   400  // sigtrampgo is called from the signal handler function, sigtramp,
   401  // written in assembly code.
   402  // This is called by the signal handler, and the world may be stopped.
   403  //
   404  // It must be nosplit because getg() is still the G that was running
   405  // (if any) when the signal was delivered, but it's (usually) called
   406  // on the gsignal stack. Until this switches the G to gsignal, the
   407  // stack bounds check won't work.
   408  //
   409  //go:nosplit
   410  //go:nowritebarrierrec
   411  func sigtrampgo(sig uint32, info *siginfo, ctx unsafe.Pointer) {
   412  	if sigfwdgo(sig, info, ctx) {
   413  		return
   414  	}
   415  	c := &sigctxt{info, ctx}
   416  	g := sigFetchG(c)
   417  	setg(g)
   418  	if g == nil {
   419  		if sig == _SIGPROF {
   420  			sigprofNonGoPC(c.sigpc())
   421  			return
   422  		}
   423  		if sig == sigPreempt && preemptMSupported && debug.asyncpreemptoff == 0 {
   424  			// This is probably a signal from preemptM sent
   425  			// while executing Go code but received while
   426  			// executing non-Go code.
   427  			// We got past sigfwdgo, so we know that there is
   428  			// no non-Go signal handler for sigPreempt.
   429  			// The default behavior for sigPreempt is to ignore
   430  			// the signal, so badsignal will be a no-op anyway.
   431  			return
   432  		}
   433  		c.fixsigcode(sig)
   434  		badsignal(uintptr(sig), c)
   435  		return
   436  	}
   437  
   438  	// If some non-Go code called sigaltstack, adjust.
   439  	var gsignalStack gsignalStack
   440  	setStack := adjustSignalStack(sig, g.m, &gsignalStack)
   441  	if setStack {
   442  		g.m.gsignal.stktopsp = getcallersp()
   443  	}
   444  
   445  	setg(g.m.gsignal)
   446  
   447  	if g.stackguard0 == stackFork {
   448  		signalDuringFork(sig)
   449  	}
   450  
   451  	c.fixsigcode(sig)
   452  	sighandler(sig, info, ctx, g)
   453  	setg(g)
   454  	if setStack {
   455  		restoreGsignalStack(&gsignalStack)
   456  	}
   457  }
   458  
   459  // adjustSignalStack adjusts the current stack guard based on the
   460  // stack pointer that is actually in use while handling a signal.
   461  // We do this in case some non-Go code called sigaltstack.
   462  // This reports whether the stack was adjusted, and if so stores the old
   463  // signal stack in *gsigstack.
   464  //go:nosplit
   465  func adjustSignalStack(sig uint32, mp *m, gsigStack *gsignalStack) bool {
   466  	sp := uintptr(unsafe.Pointer(&sig))
   467  	if sp >= mp.gsignal.stack.lo && sp < mp.gsignal.stack.hi {
   468  		return false
   469  	}
   470  
   471  	if sp >= mp.g0.stack.lo && sp < mp.g0.stack.hi {
   472  		// The signal was delivered on the g0 stack.
   473  		// This can happen when linked with C code
   474  		// using the thread sanitizer, which collects
   475  		// signals then delivers them itself by calling
   476  		// the signal handler directly when C code,
   477  		// including C code called via cgo, calls a
   478  		// TSAN-intercepted function such as malloc.
   479  		st := stackt{ss_size: mp.g0.stack.hi - mp.g0.stack.lo}
   480  		setSignalstackSP(&st, mp.g0.stack.lo)
   481  		setGsignalStack(&st, gsigStack)
   482  		return true
   483  	}
   484  
   485  	var st stackt
   486  	sigaltstack(nil, &st)
   487  	if st.ss_flags&_SS_DISABLE != 0 {
   488  		setg(nil)
   489  		needm(0)
   490  		noSignalStack(sig)
   491  		dropm()
   492  	}
   493  	stsp := uintptr(unsafe.Pointer(st.ss_sp))
   494  	if sp < stsp || sp >= stsp+st.ss_size {
   495  		setg(nil)
   496  		needm(0)
   497  		sigNotOnStack(sig)
   498  		dropm()
   499  	}
   500  	setGsignalStack(&st, gsigStack)
   501  	return true
   502  }
   503  
   504  // crashing is the number of m's we have waited for when implementing
   505  // GOTRACEBACK=crash when a signal is received.
   506  var crashing int32
   507  
   508  // testSigtrap and testSigusr1 are used by the runtime tests. If
   509  // non-nil, it is called on SIGTRAP/SIGUSR1. If it returns true, the
   510  // normal behavior on this signal is suppressed.
   511  var testSigtrap func(info *siginfo, ctxt *sigctxt, gp *g) bool
   512  var testSigusr1 func(gp *g) bool
   513  
   514  // sighandler is invoked when a signal occurs. The global g will be
   515  // set to a gsignal goroutine and we will be running on the alternate
   516  // signal stack. The parameter g will be the value of the global g
   517  // when the signal occurred. The sig, info, and ctxt parameters are
   518  // from the system signal handler: they are the parameters passed when
   519  // the SA is passed to the sigaction system call.
   520  //
   521  // The garbage collector may have stopped the world, so write barriers
   522  // are not allowed.
   523  //
   524  //go:nowritebarrierrec
   525  func sighandler(sig uint32, info *siginfo, ctxt unsafe.Pointer, gp *g) {
   526  	_g_ := getg()
   527  	c := &sigctxt{info, ctxt}
   528  
   529  	if sig == _SIGPROF {
   530  		sigprof(c.sigpc(), c.sigsp(), c.siglr(), gp, _g_.m)
   531  		return
   532  	}
   533  
   534  	if sig == _SIGTRAP && testSigtrap != nil && testSigtrap(info, (*sigctxt)(noescape(unsafe.Pointer(c))), gp) {
   535  		return
   536  	}
   537  
   538  	if sig == _SIGUSR1 && testSigusr1 != nil && testSigusr1(gp) {
   539  		return
   540  	}
   541  
   542  	if sig == sigPreempt {
   543  		// Might be a preemption signal.
   544  		doSigPreempt(gp, c)
   545  		// Even if this was definitely a preemption signal, it
   546  		// may have been coalesced with another signal, so we
   547  		// still let it through to the application.
   548  	}
   549  
   550  	flags := int32(_SigThrow)
   551  	if sig < uint32(len(sigtable)) {
   552  		flags = sigtable[sig].flags
   553  	}
   554  	if flags&_SigPanic != 0 && gp.throwsplit {
   555  		// We can't safely sigpanic because it may grow the
   556  		// stack. Abort in the signal handler instead.
   557  		flags = (flags &^ _SigPanic) | _SigThrow
   558  	}
   559  	if isAbortPC(c.sigpc()) {
   560  		// On many architectures, the abort function just
   561  		// causes a memory fault. Don't turn that into a panic.
   562  		flags = _SigThrow
   563  	}
   564  	if c.sigcode() != _SI_USER && flags&_SigPanic != 0 {
   565  		// The signal is going to cause a panic.
   566  		// Arrange the stack so that it looks like the point
   567  		// where the signal occurred made a call to the
   568  		// function sigpanic. Then set the PC to sigpanic.
   569  
   570  		// Have to pass arguments out of band since
   571  		// augmenting the stack frame would break
   572  		// the unwinding code.
   573  		gp.sig = sig
   574  		gp.sigcode0 = uintptr(c.sigcode())
   575  		gp.sigcode1 = uintptr(c.fault())
   576  		gp.sigpc = c.sigpc()
   577  
   578  		c.preparePanic(sig, gp)
   579  		return
   580  	}
   581  
   582  	if c.sigcode() == _SI_USER || flags&_SigNotify != 0 {
   583  		if sigsend(sig) {
   584  			return
   585  		}
   586  	}
   587  
   588  	if c.sigcode() == _SI_USER && signal_ignored(sig) {
   589  		return
   590  	}
   591  
   592  	if flags&_SigKill != 0 {
   593  		dieFromSignal(sig)
   594  	}
   595  
   596  	if flags&_SigThrow == 0 {
   597  		return
   598  	}
   599  
   600  	_g_.m.throwing = 1
   601  	_g_.m.caughtsig.set(gp)
   602  
   603  	if crashing == 0 {
   604  		startpanic_m()
   605  	}
   606  
   607  	if sig < uint32(len(sigtable)) {
   608  		print(sigtable[sig].name, "\n")
   609  	} else {
   610  		print("Signal ", sig, "\n")
   611  	}
   612  
   613  	print("PC=", hex(c.sigpc()), " m=", _g_.m.id, " sigcode=", c.sigcode(), "\n")
   614  	if _g_.m.lockedg != 0 && _g_.m.ncgo > 0 && gp == _g_.m.g0 {
   615  		print("signal arrived during cgo execution\n")
   616  		gp = _g_.m.lockedg.ptr()
   617  	}
   618  	print("\n")
   619  
   620  	level, _, docrash := gotraceback()
   621  	if level > 0 {
   622  		goroutineheader(gp)
   623  		tracebacktrap(c.sigpc(), c.sigsp(), c.siglr(), gp)
   624  		if crashing > 0 && gp != _g_.m.curg && _g_.m.curg != nil && readgstatus(_g_.m.curg)&^_Gscan == _Grunning {
   625  			// tracebackothers on original m skipped this one; trace it now.
   626  			goroutineheader(_g_.m.curg)
   627  			traceback(^uintptr(0), ^uintptr(0), 0, _g_.m.curg)
   628  		} else if crashing == 0 {
   629  			tracebackothers(gp)
   630  			print("\n")
   631  		}
   632  		dumpregs(c)
   633  	}
   634  
   635  	if docrash {
   636  		crashing++
   637  		if crashing < mcount()-int32(extraMCount) {
   638  			// There are other m's that need to dump their stacks.
   639  			// Relay SIGQUIT to the next m by sending it to the current process.
   640  			// All m's that have already received SIGQUIT have signal masks blocking
   641  			// receipt of any signals, so the SIGQUIT will go to an m that hasn't seen it yet.
   642  			// When the last m receives the SIGQUIT, it will fall through to the call to
   643  			// crash below. Just in case the relaying gets botched, each m involved in
   644  			// the relay sleeps for 5 seconds and then does the crash/exit itself.
   645  			// In expected operation, the last m has received the SIGQUIT and run
   646  			// crash/exit and the process is gone, all long before any of the
   647  			// 5-second sleeps have finished.
   648  			print("\n-----\n\n")
   649  			raiseproc(_SIGQUIT)
   650  			usleep(5 * 1000 * 1000)
   651  		}
   652  		crash()
   653  	}
   654  
   655  	printDebugLog()
   656  
   657  	exit(2)
   658  }
   659  
   660  // sigpanic turns a synchronous signal into a run-time panic.
   661  // If the signal handler sees a synchronous panic, it arranges the
   662  // stack to look like the function where the signal occurred called
   663  // sigpanic, sets the signal's PC value to sigpanic, and returns from
   664  // the signal handler. The effect is that the program will act as
   665  // though the function that got the signal simply called sigpanic
   666  // instead.
   667  //
   668  // This must NOT be nosplit because the linker doesn't know where
   669  // sigpanic calls can be injected.
   670  //
   671  // The signal handler must not inject a call to sigpanic if
   672  // getg().throwsplit, since sigpanic may need to grow the stack.
   673  //
   674  // This is exported via linkname to assembly in runtime/cgo.
   675  //go:linkname sigpanic
   676  func sigpanic() {
   677  	g := getg()
   678  	if !canpanic(g) {
   679  		throw("unexpected signal during runtime execution")
   680  	}
   681  
   682  	switch g.sig {
   683  	case _SIGBUS:
   684  		if g.sigcode0 == _BUS_ADRERR && g.sigcode1 < 0x1000 {
   685  			panicmem()
   686  		}
   687  		// Support runtime/debug.SetPanicOnFault.
   688  		if g.paniconfault {
   689  			panicmem()
   690  		}
   691  		print("unexpected fault address ", hex(g.sigcode1), "\n")
   692  		throw("fault")
   693  	case _SIGSEGV:
   694  		if (g.sigcode0 == 0 || g.sigcode0 == _SEGV_MAPERR || g.sigcode0 == _SEGV_ACCERR) && g.sigcode1 < 0x1000 {
   695  			panicmem()
   696  		}
   697  		// Support runtime/debug.SetPanicOnFault.
   698  		if g.paniconfault {
   699  			panicmem()
   700  		}
   701  		print("unexpected fault address ", hex(g.sigcode1), "\n")
   702  		throw("fault")
   703  	case _SIGFPE:
   704  		switch g.sigcode0 {
   705  		case _FPE_INTDIV:
   706  			panicdivide()
   707  		case _FPE_INTOVF:
   708  			panicoverflow()
   709  		}
   710  		panicfloat()
   711  	}
   712  
   713  	if g.sig >= uint32(len(sigtable)) {
   714  		// can't happen: we looked up g.sig in sigtable to decide to call sigpanic
   715  		throw("unexpected signal value")
   716  	}
   717  	panic(errorString(sigtable[g.sig].name))
   718  }
   719  
   720  // dieFromSignal kills the program with a signal.
   721  // This provides the expected exit status for the shell.
   722  // This is only called with fatal signals expected to kill the process.
   723  //go:nosplit
   724  //go:nowritebarrierrec
   725  func dieFromSignal(sig uint32) {
   726  	unblocksig(sig)
   727  	// Mark the signal as unhandled to ensure it is forwarded.
   728  	atomic.Store(&handlingSig[sig], 0)
   729  	raise(sig)
   730  
   731  	// That should have killed us. On some systems, though, raise
   732  	// sends the signal to the whole process rather than to just
   733  	// the current thread, which means that the signal may not yet
   734  	// have been delivered. Give other threads a chance to run and
   735  	// pick up the signal.
   736  	osyield()
   737  	osyield()
   738  	osyield()
   739  
   740  	// If that didn't work, try _SIG_DFL.
   741  	setsig(sig, _SIG_DFL)
   742  	raise(sig)
   743  
   744  	osyield()
   745  	osyield()
   746  	osyield()
   747  
   748  	// If we are still somehow running, just exit with the wrong status.
   749  	exit(2)
   750  }
   751  
   752  // raisebadsignal is called when a signal is received on a non-Go
   753  // thread, and the Go program does not want to handle it (that is, the
   754  // program has not called os/signal.Notify for the signal).
   755  func raisebadsignal(sig uint32, c *sigctxt) {
   756  	if sig == _SIGPROF {
   757  		// Ignore profiling signals that arrive on non-Go threads.
   758  		return
   759  	}
   760  
   761  	var handler uintptr
   762  	if sig >= _NSIG {
   763  		handler = _SIG_DFL
   764  	} else {
   765  		handler = atomic.Loaduintptr(&fwdSig[sig])
   766  	}
   767  
   768  	// Reset the signal handler and raise the signal.
   769  	// We are currently running inside a signal handler, so the
   770  	// signal is blocked. We need to unblock it before raising the
   771  	// signal, or the signal we raise will be ignored until we return
   772  	// from the signal handler. We know that the signal was unblocked
   773  	// before entering the handler, or else we would not have received
   774  	// it. That means that we don't have to worry about blocking it
   775  	// again.
   776  	unblocksig(sig)
   777  	setsig(sig, handler)
   778  
   779  	// If we're linked into a non-Go program we want to try to
   780  	// avoid modifying the original context in which the signal
   781  	// was raised. If the handler is the default, we know it
   782  	// is non-recoverable, so we don't have to worry about
   783  	// re-installing sighandler. At this point we can just
   784  	// return and the signal will be re-raised and caught by
   785  	// the default handler with the correct context.
   786  	//
   787  	// On FreeBSD, the libthr sigaction code prevents
   788  	// this from working so we fall through to raise.
   789  	if GOOS != "freebsd" && (isarchive || islibrary) && handler == _SIG_DFL && c.sigcode() != _SI_USER {
   790  		return
   791  	}
   792  
   793  	raise(sig)
   794  
   795  	// Give the signal a chance to be delivered.
   796  	// In almost all real cases the program is about to crash,
   797  	// so sleeping here is not a waste of time.
   798  	usleep(1000)
   799  
   800  	// If the signal didn't cause the program to exit, restore the
   801  	// Go signal handler and carry on.
   802  	//
   803  	// We may receive another instance of the signal before we
   804  	// restore the Go handler, but that is not so bad: we know
   805  	// that the Go program has been ignoring the signal.
   806  	setsig(sig, funcPC(sighandler))
   807  }
   808  
   809  //go:nosplit
   810  func crash() {
   811  	// OS X core dumps are linear dumps of the mapped memory,
   812  	// from the first virtual byte to the last, with zeros in the gaps.
   813  	// Because of the way we arrange the address space on 64-bit systems,
   814  	// this means the OS X core file will be >128 GB and even on a zippy
   815  	// workstation can take OS X well over an hour to write (uninterruptible).
   816  	// Save users from making that mistake.
   817  	if GOOS == "darwin" && GOARCH == "amd64" {
   818  		return
   819  	}
   820  
   821  	dieFromSignal(_SIGABRT)
   822  }
   823  
   824  // ensureSigM starts one global, sleeping thread to make sure at least one thread
   825  // is available to catch signals enabled for os/signal.
   826  func ensureSigM() {
   827  	if maskUpdatedChan != nil {
   828  		return
   829  	}
   830  	maskUpdatedChan = make(chan struct{})
   831  	disableSigChan = make(chan uint32)
   832  	enableSigChan = make(chan uint32)
   833  	go func() {
   834  		// Signal masks are per-thread, so make sure this goroutine stays on one
   835  		// thread.
   836  		LockOSThread()
   837  		defer UnlockOSThread()
   838  		// The sigBlocked mask contains the signals not active for os/signal,
   839  		// initially all signals except the essential. When signal.Notify()/Stop is called,
   840  		// sigenable/sigdisable in turn notify this thread to update its signal
   841  		// mask accordingly.
   842  		sigBlocked := sigset_all
   843  		for i := range sigtable {
   844  			if !blockableSig(uint32(i)) {
   845  				sigdelset(&sigBlocked, i)
   846  			}
   847  		}
   848  		sigprocmask(_SIG_SETMASK, &sigBlocked, nil)
   849  		for {
   850  			select {
   851  			case sig := <-enableSigChan:
   852  				if sig > 0 {
   853  					sigdelset(&sigBlocked, int(sig))
   854  				}
   855  			case sig := <-disableSigChan:
   856  				if sig > 0 && blockableSig(sig) {
   857  					sigaddset(&sigBlocked, int(sig))
   858  				}
   859  			}
   860  			sigprocmask(_SIG_SETMASK, &sigBlocked, nil)
   861  			maskUpdatedChan <- struct{}{}
   862  		}
   863  	}()
   864  }
   865  
   866  // This is called when we receive a signal when there is no signal stack.
   867  // This can only happen if non-Go code calls sigaltstack to disable the
   868  // signal stack.
   869  func noSignalStack(sig uint32) {
   870  	println("signal", sig, "received on thread with no signal stack")
   871  	throw("non-Go code disabled sigaltstack")
   872  }
   873  
   874  // This is called if we receive a signal when there is a signal stack
   875  // but we are not on it. This can only happen if non-Go code called
   876  // sigaction without setting the SS_ONSTACK flag.
   877  func sigNotOnStack(sig uint32) {
   878  	println("signal", sig, "received but handler not on signal stack")
   879  	throw("non-Go code set up signal handler without SA_ONSTACK flag")
   880  }
   881  
   882  // signalDuringFork is called if we receive a signal while doing a fork.
   883  // We do not want signals at that time, as a signal sent to the process
   884  // group may be delivered to the child process, causing confusion.
   885  // This should never be called, because we block signals across the fork;
   886  // this function is just a safety check. See issue 18600 for background.
   887  func signalDuringFork(sig uint32) {
   888  	println("signal", sig, "received during fork")
   889  	throw("signal received during fork")
   890  }
   891  
   892  var badginsignalMsg = "fatal: bad g in signal handler\n"
   893  
   894  // This runs on a foreign stack, without an m or a g. No stack split.
   895  //go:nosplit
   896  //go:norace
   897  //go:nowritebarrierrec
   898  func badsignal(sig uintptr, c *sigctxt) {
   899  	if !iscgo && !cgoHasExtraM {
   900  		// There is no extra M. needm will not be able to grab
   901  		// an M. Instead of hanging, just crash.
   902  		// Cannot call split-stack function as there is no G.
   903  		s := stringStructOf(&badginsignalMsg)
   904  		write(2, s.str, int32(s.len))
   905  		exit(2)
   906  		*(*uintptr)(unsafe.Pointer(uintptr(123))) = 2
   907  	}
   908  	needm(0)
   909  	if !sigsend(uint32(sig)) {
   910  		// A foreign thread received the signal sig, and the
   911  		// Go code does not want to handle it.
   912  		raisebadsignal(uint32(sig), c)
   913  	}
   914  	dropm()
   915  }
   916  
   917  //go:noescape
   918  func sigfwd(fn uintptr, sig uint32, info *siginfo, ctx unsafe.Pointer)
   919  
   920  // Determines if the signal should be handled by Go and if not, forwards the
   921  // signal to the handler that was installed before Go's. Returns whether the
   922  // signal was forwarded.
   923  // This is called by the signal handler, and the world may be stopped.
   924  //go:nosplit
   925  //go:nowritebarrierrec
   926  func sigfwdgo(sig uint32, info *siginfo, ctx unsafe.Pointer) bool {
   927  	if sig >= uint32(len(sigtable)) {
   928  		return false
   929  	}
   930  	fwdFn := atomic.Loaduintptr(&fwdSig[sig])
   931  	flags := sigtable[sig].flags
   932  
   933  	// If we aren't handling the signal, forward it.
   934  	if atomic.Load(&handlingSig[sig]) == 0 || !signalsOK {
   935  		// If the signal is ignored, doing nothing is the same as forwarding.
   936  		if fwdFn == _SIG_IGN || (fwdFn == _SIG_DFL && flags&_SigIgn != 0) {
   937  			return true
   938  		}
   939  		// We are not handling the signal and there is no other handler to forward to.
   940  		// Crash with the default behavior.
   941  		if fwdFn == _SIG_DFL {
   942  			setsig(sig, _SIG_DFL)
   943  			dieFromSignal(sig)
   944  			return false
   945  		}
   946  
   947  		sigfwd(fwdFn, sig, info, ctx)
   948  		return true
   949  	}
   950  
   951  	// This function and its caller sigtrampgo assumes SIGPIPE is delivered on the
   952  	// originating thread. This property does not hold on macOS (golang.org/issue/33384),
   953  	// so we have no choice but to ignore SIGPIPE.
   954  	if GOOS == "darwin" && sig == _SIGPIPE {
   955  		return true
   956  	}
   957  
   958  	// If there is no handler to forward to, no need to forward.
   959  	if fwdFn == _SIG_DFL {
   960  		return false
   961  	}
   962  
   963  	c := &sigctxt{info, ctx}
   964  	// Only forward synchronous signals and SIGPIPE.
   965  	// Unfortunately, user generated SIGPIPEs will also be forwarded, because si_code
   966  	// is set to _SI_USER even for a SIGPIPE raised from a write to a closed socket
   967  	// or pipe.
   968  	if (c.sigcode() == _SI_USER || flags&_SigPanic == 0) && sig != _SIGPIPE {
   969  		return false
   970  	}
   971  	// Determine if the signal occurred inside Go code. We test that:
   972  	//   (1) we weren't in VDSO page,
   973  	//   (2) we were in a goroutine (i.e., m.curg != nil), and
   974  	//   (3) we weren't in CGO.
   975  	g := sigFetchG(c)
   976  	if g != nil && g.m != nil && g.m.curg != nil && !g.m.incgo {
   977  		return false
   978  	}
   979  
   980  	// Signal not handled by Go, forward it.
   981  	if fwdFn != _SIG_IGN {
   982  		sigfwd(fwdFn, sig, info, ctx)
   983  	}
   984  
   985  	return true
   986  }
   987  
   988  // msigsave saves the current thread's signal mask into mp.sigmask.
   989  // This is used to preserve the non-Go signal mask when a non-Go
   990  // thread calls a Go function.
   991  // This is nosplit and nowritebarrierrec because it is called by needm
   992  // which may be called on a non-Go thread with no g available.
   993  //go:nosplit
   994  //go:nowritebarrierrec
   995  func msigsave(mp *m) {
   996  	sigprocmask(_SIG_SETMASK, nil, &mp.sigmask)
   997  }
   998  
   999  // msigrestore sets the current thread's signal mask to sigmask.
  1000  // This is used to restore the non-Go signal mask when a non-Go thread
  1001  // calls a Go function.
  1002  // This is nosplit and nowritebarrierrec because it is called by dropm
  1003  // after g has been cleared.
  1004  //go:nosplit
  1005  //go:nowritebarrierrec
  1006  func msigrestore(sigmask sigset) {
  1007  	sigprocmask(_SIG_SETMASK, &sigmask, nil)
  1008  }
  1009  
  1010  // sigblock blocks all signals in the current thread's signal mask.
  1011  // This is used to block signals while setting up and tearing down g
  1012  // when a non-Go thread calls a Go function.
  1013  // The OS-specific code is expected to define sigset_all.
  1014  // This is nosplit and nowritebarrierrec because it is called by needm
  1015  // which may be called on a non-Go thread with no g available.
  1016  //go:nosplit
  1017  //go:nowritebarrierrec
  1018  func sigblock() {
  1019  	sigprocmask(_SIG_SETMASK, &sigset_all, nil)
  1020  }
  1021  
  1022  // unblocksig removes sig from the current thread's signal mask.
  1023  // This is nosplit and nowritebarrierrec because it is called from
  1024  // dieFromSignal, which can be called by sigfwdgo while running in the
  1025  // signal handler, on the signal stack, with no g available.
  1026  //go:nosplit
  1027  //go:nowritebarrierrec
  1028  func unblocksig(sig uint32) {
  1029  	var set sigset
  1030  	sigaddset(&set, int(sig))
  1031  	sigprocmask(_SIG_UNBLOCK, &set, nil)
  1032  }
  1033  
  1034  // minitSignals is called when initializing a new m to set the
  1035  // thread's alternate signal stack and signal mask.
  1036  func minitSignals() {
  1037  	minitSignalStack()
  1038  	minitSignalMask()
  1039  }
  1040  
  1041  // minitSignalStack is called when initializing a new m to set the
  1042  // alternate signal stack. If the alternate signal stack is not set
  1043  // for the thread (the normal case) then set the alternate signal
  1044  // stack to the gsignal stack. If the alternate signal stack is set
  1045  // for the thread (the case when a non-Go thread sets the alternate
  1046  // signal stack and then calls a Go function) then set the gsignal
  1047  // stack to the alternate signal stack. We also set the alternate
  1048  // signal stack to the gsignal stack if cgo is not used (regardless
  1049  // of whether it is already set). Record which choice was made in
  1050  // newSigstack, so that it can be undone in unminit.
  1051  func minitSignalStack() {
  1052  	_g_ := getg()
  1053  	var st stackt
  1054  	sigaltstack(nil, &st)
  1055  	if st.ss_flags&_SS_DISABLE != 0 || !iscgo {
  1056  		signalstack(&_g_.m.gsignal.stack)
  1057  		_g_.m.newSigstack = true
  1058  	} else {
  1059  		setGsignalStack(&st, &_g_.m.goSigStack)
  1060  		_g_.m.newSigstack = false
  1061  	}
  1062  }
  1063  
  1064  // minitSignalMask is called when initializing a new m to set the
  1065  // thread's signal mask. When this is called all signals have been
  1066  // blocked for the thread.  This starts with m.sigmask, which was set
  1067  // either from initSigmask for a newly created thread or by calling
  1068  // msigsave if this is a non-Go thread calling a Go function. It
  1069  // removes all essential signals from the mask, thus causing those
  1070  // signals to not be blocked. Then it sets the thread's signal mask.
  1071  // After this is called the thread can receive signals.
  1072  func minitSignalMask() {
  1073  	nmask := getg().m.sigmask
  1074  	for i := range sigtable {
  1075  		if !blockableSig(uint32(i)) {
  1076  			sigdelset(&nmask, i)
  1077  		}
  1078  	}
  1079  	sigprocmask(_SIG_SETMASK, &nmask, nil)
  1080  }
  1081  
  1082  // unminitSignals is called from dropm, via unminit, to undo the
  1083  // effect of calling minit on a non-Go thread.
  1084  //go:nosplit
  1085  func unminitSignals() {
  1086  	if getg().m.newSigstack {
  1087  		st := stackt{ss_flags: _SS_DISABLE}
  1088  		sigaltstack(&st, nil)
  1089  	} else {
  1090  		// We got the signal stack from someone else. Restore
  1091  		// the Go-allocated stack in case this M gets reused
  1092  		// for another thread (e.g., it's an extram). Also, on
  1093  		// Android, libc allocates a signal stack for all
  1094  		// threads, so it's important to restore the Go stack
  1095  		// even on Go-created threads so we can free it.
  1096  		restoreGsignalStack(&getg().m.goSigStack)
  1097  	}
  1098  }
  1099  
  1100  // blockableSig reports whether sig may be blocked by the signal mask.
  1101  // We never want to block the signals marked _SigUnblock;
  1102  // these are the synchronous signals that turn into a Go panic.
  1103  // In a Go program--not a c-archive/c-shared--we never want to block
  1104  // the signals marked _SigKill or _SigThrow, as otherwise it's possible
  1105  // for all running threads to block them and delay their delivery until
  1106  // we start a new thread. When linked into a C program we let the C code
  1107  // decide on the disposition of those signals.
  1108  func blockableSig(sig uint32) bool {
  1109  	flags := sigtable[sig].flags
  1110  	if flags&_SigUnblock != 0 {
  1111  		return false
  1112  	}
  1113  	if isarchive || islibrary {
  1114  		return true
  1115  	}
  1116  	return flags&(_SigKill|_SigThrow) == 0
  1117  }
  1118  
  1119  // gsignalStack saves the fields of the gsignal stack changed by
  1120  // setGsignalStack.
  1121  type gsignalStack struct {
  1122  	stack       stack
  1123  	stackguard0 uintptr
  1124  	stackguard1 uintptr
  1125  	stktopsp    uintptr
  1126  }
  1127  
  1128  // setGsignalStack sets the gsignal stack of the current m to an
  1129  // alternate signal stack returned from the sigaltstack system call.
  1130  // It saves the old values in *old for use by restoreGsignalStack.
  1131  // This is used when handling a signal if non-Go code has set the
  1132  // alternate signal stack.
  1133  //go:nosplit
  1134  //go:nowritebarrierrec
  1135  func setGsignalStack(st *stackt, old *gsignalStack) {
  1136  	g := getg()
  1137  	if old != nil {
  1138  		old.stack = g.m.gsignal.stack
  1139  		old.stackguard0 = g.m.gsignal.stackguard0
  1140  		old.stackguard1 = g.m.gsignal.stackguard1
  1141  		old.stktopsp = g.m.gsignal.stktopsp
  1142  	}
  1143  	stsp := uintptr(unsafe.Pointer(st.ss_sp))
  1144  	g.m.gsignal.stack.lo = stsp
  1145  	g.m.gsignal.stack.hi = stsp + st.ss_size
  1146  	g.m.gsignal.stackguard0 = stsp + _StackGuard
  1147  	g.m.gsignal.stackguard1 = stsp + _StackGuard
  1148  }
  1149  
  1150  // restoreGsignalStack restores the gsignal stack to the value it had
  1151  // before entering the signal handler.
  1152  //go:nosplit
  1153  //go:nowritebarrierrec
  1154  func restoreGsignalStack(st *gsignalStack) {
  1155  	gp := getg().m.gsignal
  1156  	gp.stack = st.stack
  1157  	gp.stackguard0 = st.stackguard0
  1158  	gp.stackguard1 = st.stackguard1
  1159  	gp.stktopsp = st.stktopsp
  1160  }
  1161  
  1162  // signalstack sets the current thread's alternate signal stack to s.
  1163  //go:nosplit
  1164  func signalstack(s *stack) {
  1165  	st := stackt{ss_size: s.hi - s.lo}
  1166  	setSignalstackSP(&st, s.lo)
  1167  	sigaltstack(&st, nil)
  1168  }
  1169  
  1170  // setsigsegv is used on darwin/arm{,64} to fake a segmentation fault.
  1171  //
  1172  // This is exported via linkname to assembly in runtime/cgo.
  1173  //
  1174  //go:nosplit
  1175  //go:linkname setsigsegv
  1176  func setsigsegv(pc uintptr) {
  1177  	g := getg()
  1178  	g.sig = _SIGSEGV
  1179  	g.sigpc = pc
  1180  	g.sigcode0 = _SEGV_MAPERR
  1181  	g.sigcode1 = 0 // TODO: emulate si_addr
  1182  }
  1183  

View as plain text