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