Source file src/runtime/signal_unix.go

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

View as plain text