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