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