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
7package runtime
8
9import (
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.
19type sigTabT struct {
20	flags int32
21	name  string
22}
23
24//go:linkname os_sigpipe os.sigpipe
25func os_sigpipe() {
26	systemstack(sigpipe)
27}
28
29func signame(sig uint32) string {
30	if sig >= uint32(len(sigtable)) {
31		return ""
32	}
33	return sigtable[sig].name
34}
35
36const (
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.
71const 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.
80var 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.
86var handlingSig [_NSIG]uint32
87
88// channels for synchronizing signal mask updates with the signal mask
89// thread
90var (
91	disableSigChan  chan uint32
92	enableSigChan   chan uint32
93	maskUpdatedChan chan struct{}
94)
95
96func 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
105var signalsOK bool
106
107// Initialize signals.
108// Called by libpreinit so runtime may not be initialized.
109//go:nosplit
110//go:nowritebarrierrec
111func 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
151func 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.
179func 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.
204func 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.
233func 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
256func 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.
268func 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.
304func 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
318func sigpipe() {
319	if signal_ignored(_SIGPIPE) || sigsend(_SIGPIPE) {
320		return
321	}
322	dieFromSignal(_SIGPIPE)
323}
324
325// doSigPreempt handles a preemption signal on gp.
326func 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}
337
338const preemptMSupported = pushCallSupported
339
340// preemptM sends a preemption request to mp. This request may be
341// handled asynchronously and may be coalesced with other requests to
342// the M. When the request is received, if the running G or P are
343// marked for preemption and the goroutine is at an asynchronous
344// safe-point, it will preempt the goroutine. It always atomically
345// increments mp.preemptGen after handling a preemption request.
346func preemptM(mp *m) {
347	if !pushCallSupported {
348		// This architecture doesn't support ctxt.pushCall
349		// yet, so doSigPreempt won't work.
350		return
351	}
352	if GOOS == "darwin" && (GOARCH == "arm" || GOARCH == "arm64") && !iscgo {
353		// On darwin, we use libc calls, and cgo is required on ARM and ARM64
354		// so we have TLS set up to save/restore G during C calls. If cgo is
355		// absent, we cannot save/restore G in TLS, and if a signal is
356		// received during C execution we cannot get the G. Therefore don't
357		// send signals.
358		// This can only happen in the go_bootstrap program (otherwise cgo is
359		// required).
360		return
361	}
362	signalM(mp, sigPreempt)
363}
364
365// sigFetchG fetches the value of G safely when running in a signal handler.
366// On some architectures, the g value may be clobbered when running in a VDSO.
367// See issue #32912.
368//
369//go:nosplit
370func sigFetchG(c *sigctxt) *g {
371	switch GOARCH {
372	case "arm", "arm64":
373		if !iscgo && inVDSOPage(c.sigpc()) {
374			// When using cgo, we save the g on TLS and load it from there
375			// in sigtramp. Just use that.
376			// Otherwise, before making a VDSO call we save the g to the
377			// bottom of the signal stack. Fetch from there.
378			// TODO: in efence mode, stack is sysAlloc'd, so this wouldn't
379			// work.
380			sp := getcallersp()
381			s := spanOf(sp)
382			if s != nil && s.state.get() == mSpanManual && s.base() < sp && sp < s.limit {
383				gp := *(**g)(unsafe.Pointer(s.base()))
384				return gp
385			}
386			return nil
387		}
388	}
389	return getg()
390}
391
392// sigtrampgo is called from the signal handler function, sigtramp,
393// written in assembly code.
394// This is called by the signal handler, and the world may be stopped.
395//
396// It must be nosplit because getg() is still the G that was running
397// (if any) when the signal was delivered, but it's (usually) called
398// on the gsignal stack. Until this switches the G to gsignal, the
399// stack bounds check won't work.
400//
401//go:nosplit
402//go:nowritebarrierrec
403func sigtrampgo(sig uint32, info *siginfo, ctx unsafe.Pointer) {
404	if sigfwdgo(sig, info, ctx) {
405		return
406	}
407	c := &sigctxt{info, ctx}
408	g := sigFetchG(c)
409	setg(g)
410	if g == nil {
411		if sig == _SIGPROF {
412			sigprofNonGoPC(c.sigpc())
413			return
414		}
415		if sig == sigPreempt && preemptMSupported && debug.asyncpreemptoff == 0 {
416			// This is probably a signal from preemptM sent
417			// while executing Go code but received while
418			// executing non-Go code.
419			// We got past sigfwdgo, so we know that there is
420			// no non-Go signal handler for sigPreempt.
421			// The default behavior for sigPreempt is to ignore
422			// the signal, so badsignal will be a no-op anyway.
423			return
424		}
425		c.fixsigcode(sig)
426		badsignal(uintptr(sig), c)
427		return
428	}
429
430	// If some non-Go code called sigaltstack, adjust.
431	var gsignalStack gsignalStack
432	setStack := adjustSignalStack(sig, g.m, &gsignalStack)
433	if setStack {
434		g.m.gsignal.stktopsp = getcallersp()
435	}
436
437	setg(g.m.gsignal)
438
439	if g.stackguard0 == stackFork {
440		signalDuringFork(sig)
441	}
442
443	c.fixsigcode(sig)
444	sighandler(sig, info, ctx, g)
445	setg(g)
446	if setStack {
447		restoreGsignalStack(&gsignalStack)
448	}
449}
450
451// adjustSignalStack adjusts the current stack guard based on the
452// stack pointer that is actually in use while handling a signal.
453// We do this in case some non-Go code called sigaltstack.
454// This reports whether the stack was adjusted, and if so stores the old
455// signal stack in *gsigstack.
456//go:nosplit
457func adjustSignalStack(sig uint32, mp *m, gsigStack *gsignalStack) bool {
458	sp := uintptr(unsafe.Pointer(&sig))
459	if sp >= mp.gsignal.stack.lo && sp < mp.gsignal.stack.hi {
460		return false
461	}
462
463	if sp >= mp.g0.stack.lo && sp < mp.g0.stack.hi {
464		// The signal was delivered on the g0 stack.
465		// This can happen when linked with C code
466		// using the thread sanitizer, which collects
467		// signals then delivers them itself by calling
468		// the signal handler directly when C code,
469		// including C code called via cgo, calls a
470		// TSAN-intercepted function such as malloc.
471		st := stackt{ss_size: mp.g0.stack.hi - mp.g0.stack.lo}
472		setSignalstackSP(&st, mp.g0.stack.lo)
473		setGsignalStack(&st, gsigStack)
474		return true
475	}
476
477	var st stackt
478	sigaltstack(nil, &st)
479	if st.ss_flags&_SS_DISABLE != 0 {
480		setg(nil)
481		needm(0)
482		noSignalStack(sig)
483		dropm()
484	}
485	stsp := uintptr(unsafe.Pointer(st.ss_sp))
486	if sp < stsp || sp >= stsp+st.ss_size {
487		setg(nil)
488		needm(0)
489		sigNotOnStack(sig)
490		dropm()
491	}
492	setGsignalStack(&st, gsigStack)
493	return true
494}
495
496// crashing is the number of m's we have waited for when implementing
497// GOTRACEBACK=crash when a signal is received.
498var crashing int32
499
500// testSigtrap and testSigusr1 are used by the runtime tests. If
501// non-nil, it is called on SIGTRAP/SIGUSR1. If it returns true, the
502// normal behavior on this signal is suppressed.
503var testSigtrap func(info *siginfo, ctxt *sigctxt, gp *g) bool
504var testSigusr1 func(gp *g) bool
505
506// sighandler is invoked when a signal occurs. The global g will be
507// set to a gsignal goroutine and we will be running on the alternate
508// signal stack. The parameter g will be the value of the global g
509// when the signal occurred. The sig, info, and ctxt parameters are
510// from the system signal handler: they are the parameters passed when
511// the SA is passed to the sigaction system call.
512//
513// The garbage collector may have stopped the world, so write barriers
514// are not allowed.
515//
516//go:nowritebarrierrec
517func sighandler(sig uint32, info *siginfo, ctxt unsafe.Pointer, gp *g) {
518	_g_ := getg()
519	c := &sigctxt{info, ctxt}
520
521	if sig == _SIGPROF {
522		sigprof(c.sigpc(), c.sigsp(), c.siglr(), gp, _g_.m)
523		return
524	}
525
526	if sig == _SIGTRAP && testSigtrap != nil && testSigtrap(info, (*sigctxt)(noescape(unsafe.Pointer(c))), gp) {
527		return
528	}
529
530	if sig == _SIGUSR1 && testSigusr1 != nil && testSigusr1(gp) {
531		return
532	}
533
534	if sig == sigPreempt {
535		// Might be a preemption signal.
536		doSigPreempt(gp, c)
537		// Even if this was definitely a preemption signal, it
538		// may have been coalesced with another signal, so we
539		// still let it through to the application.
540	}
541
542	flags := int32(_SigThrow)
543	if sig < uint32(len(sigtable)) {
544		flags = sigtable[sig].flags
545	}
546	if flags&_SigPanic != 0 && gp.throwsplit {
547		// We can't safely sigpanic because it may grow the
548		// stack. Abort in the signal handler instead.
549		flags = (flags &^ _SigPanic) | _SigThrow
550	}
551	if isAbortPC(c.sigpc()) {
552		// On many architectures, the abort function just
553		// causes a memory fault. Don't turn that into a panic.
554		flags = _SigThrow
555	}
556	if c.sigcode() != _SI_USER && flags&_SigPanic != 0 {
557		// The signal is going to cause a panic.
558		// Arrange the stack so that it looks like the point
559		// where the signal occurred made a call to the
560		// function sigpanic. Then set the PC to sigpanic.
561
562		// Have to pass arguments out of band since
563		// augmenting the stack frame would break
564		// the unwinding code.
565		gp.sig = sig
566		gp.sigcode0 = uintptr(c.sigcode())
567		gp.sigcode1 = uintptr(c.fault())
568		gp.sigpc = c.sigpc()
569
570		c.preparePanic(sig, gp)
571		return
572	}
573
574	if c.sigcode() == _SI_USER || flags&_SigNotify != 0 {
575		if sigsend(sig) {
576			return
577		}
578	}
579
580	if c.sigcode() == _SI_USER && signal_ignored(sig) {
581		return
582	}
583
584	if flags&_SigKill != 0 {
585		dieFromSignal(sig)
586	}
587
588	if flags&_SigThrow == 0 {
589		return
590	}
591
592	_g_.m.throwing = 1
593	_g_.m.caughtsig.set(gp)
594
595	if crashing == 0 {
596		startpanic_m()
597	}
598
599	if sig < uint32(len(sigtable)) {
600		print(sigtable[sig].name, "\n")
601	} else {
602		print("Signal ", sig, "\n")
603	}
604
605	print("PC=", hex(c.sigpc()), " m=", _g_.m.id, " sigcode=", c.sigcode(), "\n")
606	if _g_.m.lockedg != 0 && _g_.m.ncgo > 0 && gp == _g_.m.g0 {
607		print("signal arrived during cgo execution\n")
608		gp = _g_.m.lockedg.ptr()
609	}
610	print("\n")
611
612	level, _, docrash := gotraceback()
613	if level > 0 {
614		goroutineheader(gp)
615		tracebacktrap(c.sigpc(), c.sigsp(), c.siglr(), gp)
616		if crashing > 0 && gp != _g_.m.curg && _g_.m.curg != nil && readgstatus(_g_.m.curg)&^_Gscan == _Grunning {
617			// tracebackothers on original m skipped this one; trace it now.
618			goroutineheader(_g_.m.curg)
619			traceback(^uintptr(0), ^uintptr(0), 0, _g_.m.curg)
620		} else if crashing == 0 {
621			tracebackothers(gp)
622			print("\n")
623		}
624		dumpregs(c)
625	}
626
627	if docrash {
628		crashing++
629		if crashing < mcount()-int32(extraMCount) {
630			// There are other m's that need to dump their stacks.
631			// Relay SIGQUIT to the next m by sending it to the current process.
632			// All m's that have already received SIGQUIT have signal masks blocking
633			// receipt of any signals, so the SIGQUIT will go to an m that hasn't seen it yet.
634			// When the last m receives the SIGQUIT, it will fall through to the call to
635			// crash below. Just in case the relaying gets botched, each m involved in
636			// the relay sleeps for 5 seconds and then does the crash/exit itself.
637			// In expected operation, the last m has received the SIGQUIT and run
638			// crash/exit and the process is gone, all long before any of the
639			// 5-second sleeps have finished.
640			print("\n-----\n\n")
641			raiseproc(_SIGQUIT)
642			usleep(5 * 1000 * 1000)
643		}
644		crash()
645	}
646
647	printDebugLog()
648
649	exit(2)
650}
651
652// sigpanic turns a synchronous signal into a run-time panic.
653// If the signal handler sees a synchronous panic, it arranges the
654// stack to look like the function where the signal occurred called
655// sigpanic, sets the signal's PC value to sigpanic, and returns from
656// the signal handler. The effect is that the program will act as
657// though the function that got the signal simply called sigpanic
658// instead.
659//
660// This must NOT be nosplit because the linker doesn't know where
661// sigpanic calls can be injected.
662//
663// The signal handler must not inject a call to sigpanic if
664// getg().throwsplit, since sigpanic may need to grow the stack.
665//
666// This is exported via linkname to assembly in runtime/cgo.
667//go:linkname sigpanic
668func sigpanic() {
669	g := getg()
670	if !canpanic(g) {
671		throw("unexpected signal during runtime execution")
672	}
673
674	switch g.sig {
675	case _SIGBUS:
676		if g.sigcode0 == _BUS_ADRERR && g.sigcode1 < 0x1000 {
677			panicmem()
678		}
679		// Support runtime/debug.SetPanicOnFault.
680		if g.paniconfault {
681			panicmem()
682		}
683		print("unexpected fault address ", hex(g.sigcode1), "\n")
684		throw("fault")
685	case _SIGSEGV:
686		if (g.sigcode0 == 0 || g.sigcode0 == _SEGV_MAPERR || g.sigcode0 == _SEGV_ACCERR) && g.sigcode1 < 0x1000 {
687			panicmem()
688		}
689		// Support runtime/debug.SetPanicOnFault.
690		if g.paniconfault {
691			panicmem()
692		}
693		print("unexpected fault address ", hex(g.sigcode1), "\n")
694		throw("fault")
695	case _SIGFPE:
696		switch g.sigcode0 {
697		case _FPE_INTDIV:
698			panicdivide()
699		case _FPE_INTOVF:
700			panicoverflow()
701		}
702		panicfloat()
703	}
704
705	if g.sig >= uint32(len(sigtable)) {
706		// can't happen: we looked up g.sig in sigtable to decide to call sigpanic
707		throw("unexpected signal value")
708	}
709	panic(errorString(sigtable[g.sig].name))
710}
711
712// dieFromSignal kills the program with a signal.
713// This provides the expected exit status for the shell.
714// This is only called with fatal signals expected to kill the process.
715//go:nosplit
716//go:nowritebarrierrec
717func dieFromSignal(sig uint32) {
718	unblocksig(sig)
719	// Mark the signal as unhandled to ensure it is forwarded.
720	atomic.Store(&handlingSig[sig], 0)
721	raise(sig)
722
723	// That should have killed us. On some systems, though, raise
724	// sends the signal to the whole process rather than to just
725	// the current thread, which means that the signal may not yet
726	// have been delivered. Give other threads a chance to run and
727	// pick up the signal.
728	osyield()
729	osyield()
730	osyield()
731
732	// If that didn't work, try _SIG_DFL.
733	setsig(sig, _SIG_DFL)
734	raise(sig)
735
736	osyield()
737	osyield()
738	osyield()
739
740	// If we are still somehow running, just exit with the wrong status.
741	exit(2)
742}
743
744// raisebadsignal is called when a signal is received on a non-Go
745// thread, and the Go program does not want to handle it (that is, the
746// program has not called os/signal.Notify for the signal).
747func raisebadsignal(sig uint32, c *sigctxt) {
748	if sig == _SIGPROF {
749		// Ignore profiling signals that arrive on non-Go threads.
750		return
751	}
752
753	var handler uintptr
754	if sig >= _NSIG {
755		handler = _SIG_DFL
756	} else {
757		handler = atomic.Loaduintptr(&fwdSig[sig])
758	}
759
760	// Reset the signal handler and raise the signal.
761	// We are currently running inside a signal handler, so the
762	// signal is blocked. We need to unblock it before raising the
763	// signal, or the signal we raise will be ignored until we return
764	// from the signal handler. We know that the signal was unblocked
765	// before entering the handler, or else we would not have received
766	// it. That means that we don't have to worry about blocking it
767	// again.
768	unblocksig(sig)
769	setsig(sig, handler)
770
771	// If we're linked into a non-Go program we want to try to
772	// avoid modifying the original context in which the signal
773	// was raised. If the handler is the default, we know it
774	// is non-recoverable, so we don't have to worry about
775	// re-installing sighandler. At this point we can just
776	// return and the signal will be re-raised and caught by
777	// the default handler with the correct context.
778	//
779	// On FreeBSD, the libthr sigaction code prevents
780	// this from working so we fall through to raise.
781	if GOOS != "freebsd" && (isarchive || islibrary) && handler == _SIG_DFL && c.sigcode() != _SI_USER {
782		return
783	}
784
785	raise(sig)
786
787	// Give the signal a chance to be delivered.
788	// In almost all real cases the program is about to crash,
789	// so sleeping here is not a waste of time.
790	usleep(1000)
791
792	// If the signal didn't cause the program to exit, restore the
793	// Go signal handler and carry on.
794	//
795	// We may receive another instance of the signal before we
796	// restore the Go handler, but that is not so bad: we know
797	// that the Go program has been ignoring the signal.
798	setsig(sig, funcPC(sighandler))
799}
800
801//go:nosplit
802func crash() {
803	// OS X core dumps are linear dumps of the mapped memory,
804	// from the first virtual byte to the last, with zeros in the gaps.
805	// Because of the way we arrange the address space on 64-bit systems,
806	// this means the OS X core file will be >128 GB and even on a zippy
807	// workstation can take OS X well over an hour to write (uninterruptible).
808	// Save users from making that mistake.
809	if GOOS == "darwin" && GOARCH == "amd64" {
810		return
811	}
812
813	dieFromSignal(_SIGABRT)
814}
815
816// ensureSigM starts one global, sleeping thread to make sure at least one thread
817// is available to catch signals enabled for os/signal.
818func ensureSigM() {
819	if maskUpdatedChan != nil {
820		return
821	}
822	maskUpdatedChan = make(chan struct{})
823	disableSigChan = make(chan uint32)
824	enableSigChan = make(chan uint32)
825	go func() {
826		// Signal masks are per-thread, so make sure this goroutine stays on one
827		// thread.
828		LockOSThread()
829		defer UnlockOSThread()
830		// The sigBlocked mask contains the signals not active for os/signal,
831		// initially all signals except the essential. When signal.Notify()/Stop is called,
832		// sigenable/sigdisable in turn notify this thread to update its signal
833		// mask accordingly.
834		sigBlocked := sigset_all
835		for i := range sigtable {
836			if !blockableSig(uint32(i)) {
837				sigdelset(&sigBlocked, i)
838			}
839		}
840		sigprocmask(_SIG_SETMASK, &sigBlocked, nil)
841		for {
842			select {
843			case sig := <-enableSigChan:
844				if sig > 0 {
845					sigdelset(&sigBlocked, int(sig))
846				}
847			case sig := <-disableSigChan:
848				if sig > 0 && blockableSig(sig) {
849					sigaddset(&sigBlocked, int(sig))
850				}
851			}
852			sigprocmask(_SIG_SETMASK, &sigBlocked, nil)
853			maskUpdatedChan <- struct{}{}
854		}
855	}()
856}
857
858// This is called when we receive a signal when there is no signal stack.
859// This can only happen if non-Go code calls sigaltstack to disable the
860// signal stack.
861func noSignalStack(sig uint32) {
862	println("signal", sig, "received on thread with no signal stack")
863	throw("non-Go code disabled sigaltstack")
864}
865
866// This is called if we receive a signal when there is a signal stack
867// but we are not on it. This can only happen if non-Go code called
868// sigaction without setting the SS_ONSTACK flag.
869func sigNotOnStack(sig uint32) {
870	println("signal", sig, "received but handler not on signal stack")
871	throw("non-Go code set up signal handler without SA_ONSTACK flag")
872}
873
874// signalDuringFork is called if we receive a signal while doing a fork.
875// We do not want signals at that time, as a signal sent to the process
876// group may be delivered to the child process, causing confusion.
877// This should never be called, because we block signals across the fork;
878// this function is just a safety check. See issue 18600 for background.
879func signalDuringFork(sig uint32) {
880	println("signal", sig, "received during fork")
881	throw("signal received during fork")
882}
883
884var badginsignalMsg = "fatal: bad g in signal handler\n"
885
886// This runs on a foreign stack, without an m or a g. No stack split.
887//go:nosplit
888//go:norace
889//go:nowritebarrierrec
890func badsignal(sig uintptr, c *sigctxt) {
891	if !iscgo && !cgoHasExtraM {
892		// There is no extra M. needm will not be able to grab
893		// an M. Instead of hanging, just crash.
894		// Cannot call split-stack function as there is no G.
895		s := stringStructOf(&badginsignalMsg)
896		write(2, s.str, int32(s.len))
897		exit(2)
898		*(*uintptr)(unsafe.Pointer(uintptr(123))) = 2
899	}
900	needm(0)
901	if !sigsend(uint32(sig)) {
902		// A foreign thread received the signal sig, and the
903		// Go code does not want to handle it.
904		raisebadsignal(uint32(sig), c)
905	}
906	dropm()
907}
908
909//go:noescape
910func sigfwd(fn uintptr, sig uint32, info *siginfo, ctx unsafe.Pointer)
911
912// Determines if the signal should be handled by Go and if not, forwards the
913// signal to the handler that was installed before Go's. Returns whether the
914// signal was forwarded.
915// This is called by the signal handler, and the world may be stopped.
916//go:nosplit
917//go:nowritebarrierrec
918func sigfwdgo(sig uint32, info *siginfo, ctx unsafe.Pointer) bool {
919	if sig >= uint32(len(sigtable)) {
920		return false
921	}
922	fwdFn := atomic.Loaduintptr(&fwdSig[sig])
923	flags := sigtable[sig].flags
924
925	// If we aren't handling the signal, forward it.
926	if atomic.Load(&handlingSig[sig]) == 0 || !signalsOK {
927		// If the signal is ignored, doing nothing is the same as forwarding.
928		if fwdFn == _SIG_IGN || (fwdFn == _SIG_DFL && flags&_SigIgn != 0) {
929			return true
930		}
931		// We are not handling the signal and there is no other handler to forward to.
932		// Crash with the default behavior.
933		if fwdFn == _SIG_DFL {
934			setsig(sig, _SIG_DFL)
935			dieFromSignal(sig)
936			return false
937		}
938
939		sigfwd(fwdFn, sig, info, ctx)
940		return true
941	}
942
943	// This function and its caller sigtrampgo assumes SIGPIPE is delivered on the
944	// originating thread. This property does not hold on macOS (golang.org/issue/33384),
945	// so we have no choice but to ignore SIGPIPE.
946	if GOOS == "darwin" && sig == _SIGPIPE {
947		return true
948	}
949
950	// If there is no handler to forward to, no need to forward.
951	if fwdFn == _SIG_DFL {
952		return false
953	}
954
955	c := &sigctxt{info, ctx}
956	// Only forward synchronous signals and SIGPIPE.
957	// Unfortunately, user generated SIGPIPEs will also be forwarded, because si_code
958	// is set to _SI_USER even for a SIGPIPE raised from a write to a closed socket
959	// or pipe.
960	if (c.sigcode() == _SI_USER || flags&_SigPanic == 0) && sig != _SIGPIPE {
961		return false
962	}
963	// Determine if the signal occurred inside Go code. We test that:
964	//   (1) we weren't in VDSO page,
965	//   (2) we were in a goroutine (i.e., m.curg != nil), and
966	//   (3) we weren't in CGO.
967	g := sigFetchG(c)
968	if g != nil && g.m != nil && g.m.curg != nil && !g.m.incgo {
969		return false
970	}
971
972	// Signal not handled by Go, forward it.
973	if fwdFn != _SIG_IGN {
974		sigfwd(fwdFn, sig, info, ctx)
975	}
976
977	return true
978}
979
980// msigsave saves the current thread's signal mask into mp.sigmask.
981// This is used to preserve the non-Go signal mask when a non-Go
982// thread calls a Go function.
983// This is nosplit and nowritebarrierrec because it is called by needm
984// which may be called on a non-Go thread with no g available.
985//go:nosplit
986//go:nowritebarrierrec
987func msigsave(mp *m) {
988	sigprocmask(_SIG_SETMASK, nil, &mp.sigmask)
989}
990
991// msigrestore sets the current thread's signal mask to sigmask.
992// This is used to restore the non-Go signal mask when a non-Go thread
993// calls a Go function.
994// This is nosplit and nowritebarrierrec because it is called by dropm
995// after g has been cleared.
996//go:nosplit
997//go:nowritebarrierrec
998func msigrestore(sigmask sigset) {
999	sigprocmask(_SIG_SETMASK, &sigmask, nil)
1000}
1001
1002// sigblock blocks all signals in the current thread's signal mask.
1003// This is used to block signals while setting up and tearing down g
1004// when a non-Go thread calls a Go function.
1005// The OS-specific code is expected to define sigset_all.
1006// This is nosplit and nowritebarrierrec because it is called by needm
1007// which may be called on a non-Go thread with no g available.
1008//go:nosplit
1009//go:nowritebarrierrec
1010func sigblock() {
1011	sigprocmask(_SIG_SETMASK, &sigset_all, nil)
1012}
1013
1014// unblocksig removes sig from the current thread's signal mask.
1015// This is nosplit and nowritebarrierrec because it is called from
1016// dieFromSignal, which can be called by sigfwdgo while running in the
1017// signal handler, on the signal stack, with no g available.
1018//go:nosplit
1019//go:nowritebarrierrec
1020func unblocksig(sig uint32) {
1021	var set sigset
1022	sigaddset(&set, int(sig))
1023	sigprocmask(_SIG_UNBLOCK, &set, nil)
1024}
1025
1026// minitSignals is called when initializing a new m to set the
1027// thread's alternate signal stack and signal mask.
1028func minitSignals() {
1029	minitSignalStack()
1030	minitSignalMask()
1031}
1032
1033// minitSignalStack is called when initializing a new m to set the
1034// alternate signal stack. If the alternate signal stack is not set
1035// for the thread (the normal case) then set the alternate signal
1036// stack to the gsignal stack. If the alternate signal stack is set
1037// for the thread (the case when a non-Go thread sets the alternate
1038// signal stack and then calls a Go function) then set the gsignal
1039// stack to the alternate signal stack. We also set the alternate
1040// signal stack to the gsignal stack if cgo is not used (regardless
1041// of whether it is already set). Record which choice was made in
1042// newSigstack, so that it can be undone in unminit.
1043func minitSignalStack() {
1044	_g_ := getg()
1045	var st stackt
1046	sigaltstack(nil, &st)
1047	if st.ss_flags&_SS_DISABLE != 0 || !iscgo {
1048		signalstack(&_g_.m.gsignal.stack)
1049		_g_.m.newSigstack = true
1050	} else {
1051		setGsignalStack(&st, &_g_.m.goSigStack)
1052		_g_.m.newSigstack = false
1053	}
1054}
1055
1056// minitSignalMask is called when initializing a new m to set the
1057// thread's signal mask. When this is called all signals have been
1058// blocked for the thread.  This starts with m.sigmask, which was set
1059// either from initSigmask for a newly created thread or by calling
1060// msigsave if this is a non-Go thread calling a Go function. It
1061// removes all essential signals from the mask, thus causing those
1062// signals to not be blocked. Then it sets the thread's signal mask.
1063// After this is called the thread can receive signals.
1064func minitSignalMask() {
1065	nmask := getg().m.sigmask
1066	for i := range sigtable {
1067		if !blockableSig(uint32(i)) {
1068			sigdelset(&nmask, i)
1069		}
1070	}
1071	sigprocmask(_SIG_SETMASK, &nmask, nil)
1072}
1073
1074// unminitSignals is called from dropm, via unminit, to undo the
1075// effect of calling minit on a non-Go thread.
1076//go:nosplit
1077func unminitSignals() {
1078	if getg().m.newSigstack {
1079		st := stackt{ss_flags: _SS_DISABLE}
1080		sigaltstack(&st, nil)
1081	} else {
1082		// We got the signal stack from someone else. Restore
1083		// the Go-allocated stack in case this M gets reused
1084		// for another thread (e.g., it's an extram). Also, on
1085		// Android, libc allocates a signal stack for all
1086		// threads, so it's important to restore the Go stack
1087		// even on Go-created threads so we can free it.
1088		restoreGsignalStack(&getg().m.goSigStack)
1089	}
1090}
1091
1092// blockableSig reports whether sig may be blocked by the signal mask.
1093// We never want to block the signals marked _SigUnblock;
1094// these are the synchronous signals that turn into a Go panic.
1095// In a Go program--not a c-archive/c-shared--we never want to block
1096// the signals marked _SigKill or _SigThrow, as otherwise it's possible
1097// for all running threads to block them and delay their delivery until
1098// we start a new thread. When linked into a C program we let the C code
1099// decide on the disposition of those signals.
1100func blockableSig(sig uint32) bool {
1101	flags := sigtable[sig].flags
1102	if flags&_SigUnblock != 0 {
1103		return false
1104	}
1105	if isarchive || islibrary {
1106		return true
1107	}
1108	return flags&(_SigKill|_SigThrow) == 0
1109}
1110
1111// gsignalStack saves the fields of the gsignal stack changed by
1112// setGsignalStack.
1113type gsignalStack struct {
1114	stack       stack
1115	stackguard0 uintptr
1116	stackguard1 uintptr
1117	stktopsp    uintptr
1118}
1119
1120// setGsignalStack sets the gsignal stack of the current m to an
1121// alternate signal stack returned from the sigaltstack system call.
1122// It saves the old values in *old for use by restoreGsignalStack.
1123// This is used when handling a signal if non-Go code has set the
1124// alternate signal stack.
1125//go:nosplit
1126//go:nowritebarrierrec
1127func setGsignalStack(st *stackt, old *gsignalStack) {
1128	g := getg()
1129	if old != nil {
1130		old.stack = g.m.gsignal.stack
1131		old.stackguard0 = g.m.gsignal.stackguard0
1132		old.stackguard1 = g.m.gsignal.stackguard1
1133		old.stktopsp = g.m.gsignal.stktopsp
1134	}
1135	stsp := uintptr(unsafe.Pointer(st.ss_sp))
1136	g.m.gsignal.stack.lo = stsp
1137	g.m.gsignal.stack.hi = stsp + st.ss_size
1138	g.m.gsignal.stackguard0 = stsp + _StackGuard
1139	g.m.gsignal.stackguard1 = stsp + _StackGuard
1140}
1141
1142// restoreGsignalStack restores the gsignal stack to the value it had
1143// before entering the signal handler.
1144//go:nosplit
1145//go:nowritebarrierrec
1146func restoreGsignalStack(st *gsignalStack) {
1147	gp := getg().m.gsignal
1148	gp.stack = st.stack
1149	gp.stackguard0 = st.stackguard0
1150	gp.stackguard1 = st.stackguard1
1151	gp.stktopsp = st.stktopsp
1152}
1153
1154// signalstack sets the current thread's alternate signal stack to s.
1155//go:nosplit
1156func signalstack(s *stack) {
1157	st := stackt{ss_size: s.hi - s.lo}
1158	setSignalstackSP(&st, s.lo)
1159	sigaltstack(&st, nil)
1160}
1161
1162// setsigsegv is used on darwin/arm{,64} to fake a segmentation fault.
1163//
1164// This is exported via linkname to assembly in runtime/cgo.
1165//
1166//go:nosplit
1167//go:linkname setsigsegv
1168func setsigsegv(pc uintptr) {
1169	g := getg()
1170	g.sig = _SIGSEGV
1171	g.sigpc = pc
1172	g.sigcode0 = _SEGV_MAPERR
1173	g.sigcode1 = 0 // TODO: emulate si_addr
1174}
1175