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