github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/runtime/traceback.go (about) 1 // Copyright 2009 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 package runtime 6 7 import ( 8 "internal/abi" 9 "internal/bytealg" 10 "internal/goarch" 11 "runtime/internal/sys" 12 "unsafe" 13 ) 14 15 // The code in this file implements stack trace walking for all architectures. 16 // The most important fact about a given architecture is whether it uses a link register. 17 // On systems with link registers, the prologue for a non-leaf function stores the 18 // incoming value of LR at the bottom of the newly allocated stack frame. 19 // On systems without link registers (x86), the architecture pushes a return PC during 20 // the call instruction, so the return PC ends up above the stack frame. 21 // In this file, the return PC is always called LR, no matter how it was found. 22 23 const usesLR = sys.MinFrameSize > 0 24 25 const ( 26 // tracebackInnerFrames is the number of innermost frames to print in a 27 // stack trace. The total maximum frames is tracebackInnerFrames + 28 // tracebackOuterFrames. 29 tracebackInnerFrames = 50 30 31 // tracebackOuterFrames is the number of outermost frames to print in a 32 // stack trace. 33 tracebackOuterFrames = 50 34 ) 35 36 // unwindFlags control the behavior of various unwinders. 37 type unwindFlags uint8 38 39 const ( 40 // unwindPrintErrors indicates that if unwinding encounters an error, it 41 // should print a message and stop without throwing. This is used for things 42 // like stack printing, where it's better to get incomplete information than 43 // to crash. This is also used in situations where everything may not be 44 // stopped nicely and the stack walk may not be able to complete, such as 45 // during profiling signals or during a crash. 46 // 47 // If neither unwindPrintErrors or unwindSilentErrors are set, unwinding 48 // performs extra consistency checks and throws on any error. 49 // 50 // Note that there are a small number of fatal situations that will throw 51 // regardless of unwindPrintErrors or unwindSilentErrors. 52 unwindPrintErrors unwindFlags = 1 << iota 53 54 // unwindSilentErrors silently ignores errors during unwinding. 55 unwindSilentErrors 56 57 // unwindTrap indicates that the initial PC and SP are from a trap, not a 58 // return PC from a call. 59 // 60 // The unwindTrap flag is updated during unwinding. If set, frame.pc is the 61 // address of a faulting instruction instead of the return address of a 62 // call. It also means the liveness at pc may not be known. 63 // 64 // TODO: Distinguish frame.continpc, which is really the stack map PC, from 65 // the actual continuation PC, which is computed differently depending on 66 // this flag and a few other things. 67 unwindTrap 68 69 // unwindJumpStack indicates that, if the traceback is on a system stack, it 70 // should resume tracing at the user stack when the system stack is 71 // exhausted. 72 unwindJumpStack 73 ) 74 75 // An unwinder iterates the physical stack frames of a Go sack. 76 // 77 // Typical use of an unwinder looks like: 78 // 79 // var u unwinder 80 // for u.init(gp, 0); u.valid(); u.next() { 81 // // ... use frame info in u ... 82 // } 83 // 84 // Implementation note: This is carefully structured to be pointer-free because 85 // tracebacks happen in places that disallow write barriers (e.g., signals). 86 // Even if this is stack-allocated, its pointer-receiver methods don't know that 87 // their receiver is on the stack, so they still emit write barriers. Here we 88 // address that by carefully avoiding any pointers in this type. Another 89 // approach would be to split this into a mutable part that's passed by pointer 90 // but contains no pointers itself and an immutable part that's passed and 91 // returned by value and can contain pointers. We could potentially hide that 92 // we're doing that in trivial methods that are inlined into the caller that has 93 // the stack allocation, but that's fragile. 94 type unwinder struct { 95 // frame is the current physical stack frame, or all 0s if 96 // there is no frame. 97 frame stkframe 98 99 // g is the G who's stack is being unwound. If the 100 // unwindJumpStack flag is set and the unwinder jumps stacks, 101 // this will be different from the initial G. 102 g guintptr 103 104 // cgoCtxt is the index into g.cgoCtxt of the next frame on the cgo stack. 105 // The cgo stack is unwound in tandem with the Go stack as we find marker frames. 106 cgoCtxt int 107 108 // calleeFuncID is the function ID of the caller of the current 109 // frame. 110 calleeFuncID abi.FuncID 111 112 // flags are the flags to this unwind. Some of these are updated as we 113 // unwind (see the flags documentation). 114 flags unwindFlags 115 116 // cache is used to cache pcvalue lookups. 117 cache pcvalueCache 118 } 119 120 // init initializes u to start unwinding gp's stack and positions the 121 // iterator on gp's innermost frame. gp must not be the current G. 122 // 123 // A single unwinder can be reused for multiple unwinds. 124 func (u *unwinder) init(gp *g, flags unwindFlags) { 125 // Implementation note: This starts the iterator on the first frame and we 126 // provide a "valid" method. Alternatively, this could start in a "before 127 // the first frame" state and "next" could return whether it was able to 128 // move to the next frame, but that's both more awkward to use in a "for" 129 // loop and is harder to implement because we have to do things differently 130 // for the first frame. 131 u.initAt(^uintptr(0), ^uintptr(0), ^uintptr(0), gp, flags) 132 } 133 134 func (u *unwinder) initAt(pc0, sp0, lr0 uintptr, gp *g, flags unwindFlags) { 135 // Don't call this "g"; it's too easy get "g" and "gp" confused. 136 if ourg := getg(); ourg == gp && ourg == ourg.m.curg { 137 // The starting sp has been passed in as a uintptr, and the caller may 138 // have other uintptr-typed stack references as well. 139 // If during one of the calls that got us here or during one of the 140 // callbacks below the stack must be grown, all these uintptr references 141 // to the stack will not be updated, and traceback will continue 142 // to inspect the old stack memory, which may no longer be valid. 143 // Even if all the variables were updated correctly, it is not clear that 144 // we want to expose a traceback that begins on one stack and ends 145 // on another stack. That could confuse callers quite a bit. 146 // Instead, we require that initAt and any other function that 147 // accepts an sp for the current goroutine (typically obtained by 148 // calling getcallersp) must not run on that goroutine's stack but 149 // instead on the g0 stack. 150 throw("cannot trace user goroutine on its own stack") 151 } 152 153 if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp. 154 if gp.syscallsp != 0 { 155 pc0 = gp.syscallpc 156 sp0 = gp.syscallsp 157 if usesLR { 158 lr0 = 0 159 } 160 } else { 161 pc0 = gp.sched.pc 162 sp0 = gp.sched.sp 163 if usesLR { 164 lr0 = gp.sched.lr 165 } 166 } 167 } 168 169 var frame stkframe 170 frame.pc = pc0 171 frame.sp = sp0 172 if usesLR { 173 frame.lr = lr0 174 } 175 176 // If the PC is zero, it's likely a nil function call. 177 // Start in the caller's frame. 178 if frame.pc == 0 { 179 if usesLR { 180 frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp)) 181 frame.lr = 0 182 } else { 183 frame.pc = uintptr(*(*uintptr)(unsafe.Pointer(frame.sp))) 184 frame.sp += goarch.PtrSize 185 } 186 } 187 188 // runtime/internal/atomic functions call into kernel helpers on 189 // arm < 7. See runtime/internal/atomic/sys_linux_arm.s. 190 // 191 // Start in the caller's frame. 192 if GOARCH == "arm" && goarm < 7 && GOOS == "linux" && frame.pc&0xffff0000 == 0xffff0000 { 193 // Note that the calls are simple BL without pushing the return 194 // address, so we use LR directly. 195 // 196 // The kernel helpers are frameless leaf functions, so SP and 197 // LR are not touched. 198 frame.pc = frame.lr 199 frame.lr = 0 200 } 201 202 f := findfunc(frame.pc) 203 if !f.valid() { 204 if flags&unwindSilentErrors == 0 { 205 print("runtime: g ", gp.goid, ": unknown pc ", hex(frame.pc), "\n") 206 tracebackHexdump(gp.stack, &frame, 0) 207 } 208 if flags&(unwindPrintErrors|unwindSilentErrors) == 0 { 209 throw("unknown pc") 210 } 211 *u = unwinder{} 212 return 213 } 214 frame.fn = f 215 216 // Populate the unwinder. 217 *u = unwinder{ 218 frame: frame, 219 g: gp.guintptr(), 220 cgoCtxt: len(gp.cgoCtxt) - 1, 221 calleeFuncID: abi.FuncIDNormal, 222 flags: flags, 223 } 224 225 isSyscall := frame.pc == pc0 && frame.sp == sp0 && pc0 == gp.syscallpc && sp0 == gp.syscallsp 226 u.resolveInternal(true, isSyscall) 227 } 228 229 func (u *unwinder) valid() bool { 230 return u.frame.pc != 0 231 } 232 233 // resolveInternal fills in u.frame based on u.frame.fn, pc, and sp. 234 // 235 // innermost indicates that this is the first resolve on this stack. If 236 // innermost is set, isSyscall indicates that the PC/SP was retrieved from 237 // gp.syscall*; this is otherwise ignored. 238 // 239 // On entry, u.frame contains: 240 // - fn is the running function. 241 // - pc is the PC in the running function. 242 // - sp is the stack pointer at that program counter. 243 // - For the innermost frame on LR machines, lr is the program counter that called fn. 244 // 245 // On return, u.frame contains: 246 // - fp is the stack pointer of the caller. 247 // - lr is the program counter that called fn. 248 // - varp, argp, and continpc are populated for the current frame. 249 // 250 // If fn is a stack-jumping function, resolveInternal can change the entire 251 // frame state to follow that stack jump. 252 // 253 // This is internal to unwinder. 254 func (u *unwinder) resolveInternal(innermost, isSyscall bool) { 255 frame := &u.frame 256 gp := u.g.ptr() 257 258 f := frame.fn 259 if f.pcsp == 0 { 260 // No frame information, must be external function, like race support. 261 // See golang.org/issue/13568. 262 u.finishInternal() 263 return 264 } 265 266 // Compute function info flags. 267 flag := f.flag 268 if f.funcID == abi.FuncID_cgocallback { 269 // cgocallback does write SP to switch from the g0 to the curg stack, 270 // but it carefully arranges that during the transition BOTH stacks 271 // have cgocallback frame valid for unwinding through. 272 // So we don't need to exclude it with the other SP-writing functions. 273 flag &^= abi.FuncFlagSPWrite 274 } 275 if isSyscall { 276 // Some Syscall functions write to SP, but they do so only after 277 // saving the entry PC/SP using entersyscall. 278 // Since we are using the entry PC/SP, the later SP write doesn't matter. 279 flag &^= abi.FuncFlagSPWrite 280 } 281 282 // Found an actual function. 283 // Derive frame pointer. 284 if frame.fp == 0 { 285 // Jump over system stack transitions. If we're on g0 and there's a user 286 // goroutine, try to jump. Otherwise this is a regular call. 287 // We also defensively check that this won't switch M's on us, 288 // which could happen at critical points in the scheduler. 289 // This ensures gp.m doesn't change from a stack jump. 290 if u.flags&unwindJumpStack != 0 && gp == gp.m.g0 && gp.m.curg != nil && gp.m.curg.m == gp.m { 291 switch f.funcID { 292 case abi.FuncID_morestack: 293 // morestack does not return normally -- newstack() 294 // gogo's to curg.sched. Match that. 295 // This keeps morestack() from showing up in the backtrace, 296 // but that makes some sense since it'll never be returned 297 // to. 298 gp = gp.m.curg 299 u.g.set(gp) 300 frame.pc = gp.sched.pc 301 frame.fn = findfunc(frame.pc) 302 f = frame.fn 303 flag = f.flag 304 frame.lr = gp.sched.lr 305 frame.sp = gp.sched.sp 306 u.cgoCtxt = len(gp.cgoCtxt) - 1 307 case abi.FuncID_systemstack: 308 // systemstack returns normally, so just follow the 309 // stack transition. 310 if usesLR && funcspdelta(f, frame.pc, &u.cache) == 0 { 311 // We're at the function prologue and the stack 312 // switch hasn't happened, or epilogue where we're 313 // about to return. Just unwind normally. 314 // Do this only on LR machines because on x86 315 // systemstack doesn't have an SP delta (the CALL 316 // instruction opens the frame), therefore no way 317 // to check. 318 flag &^= abi.FuncFlagSPWrite 319 break 320 } 321 gp = gp.m.curg 322 u.g.set(gp) 323 frame.sp = gp.sched.sp 324 u.cgoCtxt = len(gp.cgoCtxt) - 1 325 flag &^= abi.FuncFlagSPWrite 326 } 327 } 328 frame.fp = frame.sp + uintptr(funcspdelta(f, frame.pc, &u.cache)) 329 if !usesLR { 330 // On x86, call instruction pushes return PC before entering new function. 331 frame.fp += goarch.PtrSize 332 } 333 } 334 335 // Derive link register. 336 if flag&abi.FuncFlagTopFrame != 0 { 337 // This function marks the top of the stack. Stop the traceback. 338 frame.lr = 0 339 } else if flag&abi.FuncFlagSPWrite != 0 { 340 // The function we are in does a write to SP that we don't know 341 // how to encode in the spdelta table. Examples include context 342 // switch routines like runtime.gogo but also any code that switches 343 // to the g0 stack to run host C code. 344 if u.flags&(unwindPrintErrors|unwindSilentErrors) != 0 { 345 // We can't reliably unwind the SP (we might 346 // not even be on the stack we think we are), 347 // so stop the traceback here. 348 frame.lr = 0 349 } else { 350 // For a GC stack traversal, we should only see 351 // an SPWRITE function when it has voluntarily preempted itself on entry 352 // during the stack growth check. In that case, the function has 353 // not yet had a chance to do any writes to SP and is safe to unwind. 354 // isAsyncSafePoint does not allow assembly functions to be async preempted, 355 // and preemptPark double-checks that SPWRITE functions are not async preempted. 356 // So for GC stack traversal, we can safely ignore SPWRITE for the innermost frame, 357 // but farther up the stack we'd better not find any. 358 if !innermost { 359 println("traceback: unexpected SPWRITE function", funcname(f)) 360 throw("traceback") 361 } 362 } 363 } else { 364 var lrPtr uintptr 365 if usesLR { 366 if innermost && frame.sp < frame.fp || frame.lr == 0 { 367 lrPtr = frame.sp 368 frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr)) 369 } 370 } else { 371 if frame.lr == 0 { 372 lrPtr = frame.fp - goarch.PtrSize 373 frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr)) 374 } 375 } 376 } 377 378 frame.varp = frame.fp 379 if !usesLR { 380 // On x86, call instruction pushes return PC before entering new function. 381 frame.varp -= goarch.PtrSize 382 } 383 384 // For architectures with frame pointers, if there's 385 // a frame, then there's a saved frame pointer here. 386 // 387 // NOTE: This code is not as general as it looks. 388 // On x86, the ABI is to save the frame pointer word at the 389 // top of the stack frame, so we have to back down over it. 390 // On arm64, the frame pointer should be at the bottom of 391 // the stack (with R29 (aka FP) = RSP), in which case we would 392 // not want to do the subtraction here. But we started out without 393 // any frame pointer, and when we wanted to add it, we didn't 394 // want to break all the assembly doing direct writes to 8(RSP) 395 // to set the first parameter to a called function. 396 // So we decided to write the FP link *below* the stack pointer 397 // (with R29 = RSP - 8 in Go functions). 398 // This is technically ABI-compatible but not standard. 399 // And it happens to end up mimicking the x86 layout. 400 // Other architectures may make different decisions. 401 if frame.varp > frame.sp && framepointer_enabled { 402 frame.varp -= goarch.PtrSize 403 } 404 405 frame.argp = frame.fp + sys.MinFrameSize 406 407 // Determine frame's 'continuation PC', where it can continue. 408 // Normally this is the return address on the stack, but if sigpanic 409 // is immediately below this function on the stack, then the frame 410 // stopped executing due to a trap, and frame.pc is probably not 411 // a safe point for looking up liveness information. In this panicking case, 412 // the function either doesn't return at all (if it has no defers or if the 413 // defers do not recover) or it returns from one of the calls to 414 // deferproc a second time (if the corresponding deferred func recovers). 415 // In the latter case, use a deferreturn call site as the continuation pc. 416 frame.continpc = frame.pc 417 if u.calleeFuncID == abi.FuncID_sigpanic { 418 if frame.fn.deferreturn != 0 { 419 frame.continpc = frame.fn.entry() + uintptr(frame.fn.deferreturn) + 1 420 // Note: this may perhaps keep return variables alive longer than 421 // strictly necessary, as we are using "function has a defer statement" 422 // as a proxy for "function actually deferred something". It seems 423 // to be a minor drawback. (We used to actually look through the 424 // gp._defer for a defer corresponding to this function, but that 425 // is hard to do with defer records on the stack during a stack copy.) 426 // Note: the +1 is to offset the -1 that 427 // stack.go:getStackMap does to back up a return 428 // address make sure the pc is in the CALL instruction. 429 } else { 430 frame.continpc = 0 431 } 432 } 433 } 434 435 func (u *unwinder) next() { 436 frame := &u.frame 437 f := frame.fn 438 gp := u.g.ptr() 439 440 // Do not unwind past the bottom of the stack. 441 if frame.lr == 0 { 442 u.finishInternal() 443 return 444 } 445 flr := findfunc(frame.lr) 446 if !flr.valid() { 447 // This happens if you get a profiling interrupt at just the wrong time. 448 // In that context it is okay to stop early. 449 // But if no error flags are set, we're doing a garbage collection and must 450 // get everything, so crash loudly. 451 fail := u.flags&(unwindPrintErrors|unwindSilentErrors) == 0 452 doPrint := u.flags&unwindSilentErrors == 0 453 if doPrint && gp.m.incgo && f.funcID == abi.FuncID_sigpanic { 454 // We can inject sigpanic 455 // calls directly into C code, 456 // in which case we'll see a C 457 // return PC. Don't complain. 458 doPrint = false 459 } 460 if fail || doPrint { 461 print("runtime: g ", gp.goid, ": unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n") 462 tracebackHexdump(gp.stack, frame, 0) 463 } 464 if fail { 465 throw("unknown caller pc") 466 } 467 frame.lr = 0 468 u.finishInternal() 469 return 470 } 471 472 if frame.pc == frame.lr && frame.sp == frame.fp { 473 // If the next frame is identical to the current frame, we cannot make progress. 474 print("runtime: traceback stuck. pc=", hex(frame.pc), " sp=", hex(frame.sp), "\n") 475 tracebackHexdump(gp.stack, frame, frame.sp) 476 throw("traceback stuck") 477 } 478 479 injectedCall := f.funcID == abi.FuncID_sigpanic || f.funcID == abi.FuncID_asyncPreempt || f.funcID == abi.FuncID_debugCallV2 480 if injectedCall { 481 u.flags |= unwindTrap 482 } else { 483 u.flags &^= unwindTrap 484 } 485 486 // Unwind to next frame. 487 u.calleeFuncID = f.funcID 488 frame.fn = flr 489 frame.pc = frame.lr 490 frame.lr = 0 491 frame.sp = frame.fp 492 frame.fp = 0 493 494 // On link register architectures, sighandler saves the LR on stack 495 // before faking a call. 496 if usesLR && injectedCall { 497 x := *(*uintptr)(unsafe.Pointer(frame.sp)) 498 frame.sp += alignUp(sys.MinFrameSize, sys.StackAlign) 499 f = findfunc(frame.pc) 500 frame.fn = f 501 if !f.valid() { 502 frame.pc = x 503 } else if funcspdelta(f, frame.pc, &u.cache) == 0 { 504 frame.lr = x 505 } 506 } 507 508 u.resolveInternal(false, false) 509 } 510 511 // finishInternal is an unwinder-internal helper called after the stack has been 512 // exhausted. It sets the unwinder to an invalid state and checks that it 513 // successfully unwound the entire stack. 514 func (u *unwinder) finishInternal() { 515 u.frame.pc = 0 516 517 // Note that panic != nil is okay here: there can be leftover panics, 518 // because the defers on the panic stack do not nest in frame order as 519 // they do on the defer stack. If you have: 520 // 521 // frame 1 defers d1 522 // frame 2 defers d2 523 // frame 3 defers d3 524 // frame 4 panics 525 // frame 4's panic starts running defers 526 // frame 5, running d3, defers d4 527 // frame 5 panics 528 // frame 5's panic starts running defers 529 // frame 6, running d4, garbage collects 530 // frame 6, running d2, garbage collects 531 // 532 // During the execution of d4, the panic stack is d4 -> d3, which 533 // is nested properly, and we'll treat frame 3 as resumable, because we 534 // can find d3. (And in fact frame 3 is resumable. If d4 recovers 535 // and frame 5 continues running, d3, d3 can recover and we'll 536 // resume execution in (returning from) frame 3.) 537 // 538 // During the execution of d2, however, the panic stack is d2 -> d3, 539 // which is inverted. The scan will match d2 to frame 2 but having 540 // d2 on the stack until then means it will not match d3 to frame 3. 541 // This is okay: if we're running d2, then all the defers after d2 have 542 // completed and their corresponding frames are dead. Not finding d3 543 // for frame 3 means we'll set frame 3's continpc == 0, which is correct 544 // (frame 3 is dead). At the end of the walk the panic stack can thus 545 // contain defers (d3 in this case) for dead frames. The inversion here 546 // always indicates a dead frame, and the effect of the inversion on the 547 // scan is to hide those dead frames, so the scan is still okay: 548 // what's left on the panic stack are exactly (and only) the dead frames. 549 // 550 // We require callback != nil here because only when callback != nil 551 // do we know that gentraceback is being called in a "must be correct" 552 // context as opposed to a "best effort" context. The tracebacks with 553 // callbacks only happen when everything is stopped nicely. 554 // At other times, such as when gathering a stack for a profiling signal 555 // or when printing a traceback during a crash, everything may not be 556 // stopped nicely, and the stack walk may not be able to complete. 557 gp := u.g.ptr() 558 if u.flags&(unwindPrintErrors|unwindSilentErrors) == 0 && u.frame.sp != gp.stktopsp { 559 print("runtime: g", gp.goid, ": frame.sp=", hex(u.frame.sp), " top=", hex(gp.stktopsp), "\n") 560 print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "\n") 561 throw("traceback did not unwind completely") 562 } 563 } 564 565 // symPC returns the PC that should be used for symbolizing the current frame. 566 // Specifically, this is the PC of the last instruction executed in this frame. 567 // 568 // If this frame did a normal call, then frame.pc is a return PC, so this will 569 // return frame.pc-1, which points into the CALL instruction. If the frame was 570 // interrupted by a signal (e.g., profiler, segv, etc) then frame.pc is for the 571 // trapped instruction, so this returns frame.pc. See issue #34123. Finally, 572 // frame.pc can be at function entry when the frame is initialized without 573 // actually running code, like in runtime.mstart, in which case this returns 574 // frame.pc because that's the best we can do. 575 func (u *unwinder) symPC() uintptr { 576 if u.flags&unwindTrap == 0 && u.frame.pc > u.frame.fn.entry() { 577 // Regular call. 578 return u.frame.pc - 1 579 } 580 // Trapping instruction or we're at the function entry point. 581 return u.frame.pc 582 } 583 584 // cgoCallers populates pcBuf with the cgo callers of the current frame using 585 // the registered cgo unwinder. It returns the number of PCs written to pcBuf. 586 // If the current frame is not a cgo frame or if there's no registered cgo 587 // unwinder, it returns 0. 588 func (u *unwinder) cgoCallers(pcBuf []uintptr) int { 589 if cgoTraceback == nil || u.frame.fn.funcID != abi.FuncID_cgocallback || u.cgoCtxt < 0 { 590 // We don't have a cgo unwinder (typical case), or we do but we're not 591 // in a cgo frame or we're out of cgo context. 592 return 0 593 } 594 595 ctxt := u.g.ptr().cgoCtxt[u.cgoCtxt] 596 u.cgoCtxt-- 597 cgoContextPCs(ctxt, pcBuf) 598 for i, pc := range pcBuf { 599 if pc == 0 { 600 return i 601 } 602 } 603 return len(pcBuf) 604 } 605 606 // tracebackPCs populates pcBuf with the return addresses for each frame from u 607 // and returns the number of PCs written to pcBuf. The returned PCs correspond 608 // to "logical frames" rather than "physical frames"; that is if A is inlined 609 // into B, this will still return a PCs for both A and B. This also includes PCs 610 // generated by the cgo unwinder, if one is registered. 611 // 612 // If skip != 0, this skips this many logical frames. 613 // 614 // Callers should set the unwindSilentErrors flag on u. 615 func tracebackPCs(u *unwinder, skip int, pcBuf []uintptr) int { 616 var cgoBuf [32]uintptr 617 n := 0 618 for ; n < len(pcBuf) && u.valid(); u.next() { 619 f := u.frame.fn 620 cgoN := u.cgoCallers(cgoBuf[:]) 621 622 // TODO: Why does &u.cache cause u to escape? (Same in traceback2) 623 for iu, uf := newInlineUnwinder(f, u.symPC(), noEscapePtr(&u.cache)); n < len(pcBuf) && uf.valid(); uf = iu.next(uf) { 624 sf := iu.srcFunc(uf) 625 if sf.funcID == abi.FuncIDWrapper && elideWrapperCalling(u.calleeFuncID) { 626 // ignore wrappers 627 } else if skip > 0 { 628 skip-- 629 } else { 630 // Callers expect the pc buffer to contain return addresses 631 // and do the -1 themselves, so we add 1 to the call PC to 632 // create a return PC. 633 pcBuf[n] = uf.pc + 1 634 n++ 635 } 636 u.calleeFuncID = sf.funcID 637 } 638 // Add cgo frames (if we're done skipping over the requested number of 639 // Go frames). 640 if skip == 0 { 641 n += copy(pcBuf[n:], cgoBuf[:cgoN]) 642 } 643 } 644 return n 645 } 646 647 // printArgs prints function arguments in traceback. 648 func printArgs(f funcInfo, argp unsafe.Pointer, pc uintptr) { 649 // The "instruction" of argument printing is encoded in _FUNCDATA_ArgInfo. 650 // See cmd/compile/internal/ssagen.emitArgInfo for the description of the 651 // encoding. 652 // These constants need to be in sync with the compiler. 653 const ( 654 _endSeq = 0xff 655 _startAgg = 0xfe 656 _endAgg = 0xfd 657 _dotdotdot = 0xfc 658 _offsetTooLarge = 0xfb 659 ) 660 661 const ( 662 limit = 10 // print no more than 10 args/components 663 maxDepth = 5 // no more than 5 layers of nesting 664 maxLen = (maxDepth*3+2)*limit + 1 // max length of _FUNCDATA_ArgInfo (see the compiler side for reasoning) 665 ) 666 667 p := (*[maxLen]uint8)(funcdata(f, abi.FUNCDATA_ArgInfo)) 668 if p == nil { 669 return 670 } 671 672 liveInfo := funcdata(f, abi.FUNCDATA_ArgLiveInfo) 673 liveIdx := pcdatavalue(f, abi.PCDATA_ArgLiveIndex, pc, nil) 674 startOffset := uint8(0xff) // smallest offset that needs liveness info (slots with a lower offset is always live) 675 if liveInfo != nil { 676 startOffset = *(*uint8)(liveInfo) 677 } 678 679 isLive := func(off, slotIdx uint8) bool { 680 if liveInfo == nil || liveIdx <= 0 { 681 return true // no liveness info, always live 682 } 683 if off < startOffset { 684 return true 685 } 686 bits := *(*uint8)(add(liveInfo, uintptr(liveIdx)+uintptr(slotIdx/8))) 687 return bits&(1<<(slotIdx%8)) != 0 688 } 689 690 print1 := func(off, sz, slotIdx uint8) { 691 x := readUnaligned64(add(argp, uintptr(off))) 692 // mask out irrelevant bits 693 if sz < 8 { 694 shift := 64 - sz*8 695 if goarch.BigEndian { 696 x = x >> shift 697 } else { 698 x = x << shift >> shift 699 } 700 } 701 print(hex(x)) 702 if !isLive(off, slotIdx) { 703 print("?") 704 } 705 } 706 707 start := true 708 printcomma := func() { 709 if !start { 710 print(", ") 711 } 712 } 713 pi := 0 714 slotIdx := uint8(0) // register arg spill slot index 715 printloop: 716 for { 717 o := p[pi] 718 pi++ 719 switch o { 720 case _endSeq: 721 break printloop 722 case _startAgg: 723 printcomma() 724 print("{") 725 start = true 726 continue 727 case _endAgg: 728 print("}") 729 case _dotdotdot: 730 printcomma() 731 print("...") 732 case _offsetTooLarge: 733 printcomma() 734 print("_") 735 default: 736 printcomma() 737 sz := p[pi] 738 pi++ 739 print1(o, sz, slotIdx) 740 if o >= startOffset { 741 slotIdx++ 742 } 743 } 744 start = false 745 } 746 } 747 748 // funcNamePiecesForPrint returns the function name for printing to the user. 749 // It returns three pieces so it doesn't need an allocation for string 750 // concatenation. 751 func funcNamePiecesForPrint(name string) (string, string, string) { 752 // Replace the shape name in generic function with "...". 753 i := bytealg.IndexByteString(name, '[') 754 if i < 0 { 755 return name, "", "" 756 } 757 j := len(name) - 1 758 for name[j] != ']' { 759 j-- 760 } 761 if j <= i { 762 return name, "", "" 763 } 764 return name[:i], "[...]", name[j+1:] 765 } 766 767 // funcNameForPrint returns the function name for printing to the user. 768 func funcNameForPrint(name string) string { 769 a, b, c := funcNamePiecesForPrint(name) 770 return a + b + c 771 } 772 773 // printFuncName prints a function name. name is the function name in 774 // the binary's func data table. 775 func printFuncName(name string) { 776 if name == "runtime.gopanic" { 777 print("panic") 778 return 779 } 780 a, b, c := funcNamePiecesForPrint(name) 781 print(a, b, c) 782 } 783 784 func printcreatedby(gp *g) { 785 // Show what created goroutine, except main goroutine (goid 1). 786 pc := gp.gopc 787 f := findfunc(pc) 788 if f.valid() && showframe(f.srcFunc(), gp, false, abi.FuncIDNormal) && gp.goid != 1 { 789 printcreatedby1(f, pc, gp.parentGoid) 790 } 791 } 792 793 func printcreatedby1(f funcInfo, pc uintptr, goid uint64) { 794 print("created by ") 795 printFuncName(funcname(f)) 796 if goid != 0 { 797 print(" in goroutine ", goid) 798 } 799 print("\n") 800 tracepc := pc // back up to CALL instruction for funcline. 801 if pc > f.entry() { 802 tracepc -= sys.PCQuantum 803 } 804 file, line := funcline(f, tracepc) 805 print("\t", file, ":", line) 806 if pc > f.entry() { 807 print(" +", hex(pc-f.entry())) 808 } 809 print("\n") 810 } 811 812 func traceback(pc, sp, lr uintptr, gp *g) { 813 traceback1(pc, sp, lr, gp, 0) 814 } 815 816 // tracebacktrap is like traceback but expects that the PC and SP were obtained 817 // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp. 818 // Because they are from a trap instead of from a saved pair, 819 // the initial PC must not be rewound to the previous instruction. 820 // (All the saved pairs record a PC that is a return address, so we 821 // rewind it into the CALL instruction.) 822 // If gp.m.libcall{g,pc,sp} information is available, it uses that information in preference to 823 // the pc/sp/lr passed in. 824 func tracebacktrap(pc, sp, lr uintptr, gp *g) { 825 if gp.m.libcallsp != 0 { 826 // We're in C code somewhere, traceback from the saved position. 827 traceback1(gp.m.libcallpc, gp.m.libcallsp, 0, gp.m.libcallg.ptr(), 0) 828 return 829 } 830 traceback1(pc, sp, lr, gp, unwindTrap) 831 } 832 833 func traceback1(pc, sp, lr uintptr, gp *g, flags unwindFlags) { 834 // If the goroutine is in cgo, and we have a cgo traceback, print that. 835 if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 { 836 // Lock cgoCallers so that a signal handler won't 837 // change it, copy the array, reset it, unlock it. 838 // We are locked to the thread and are not running 839 // concurrently with a signal handler. 840 // We just have to stop a signal handler from interrupting 841 // in the middle of our copy. 842 gp.m.cgoCallersUse.Store(1) 843 cgoCallers := *gp.m.cgoCallers 844 gp.m.cgoCallers[0] = 0 845 gp.m.cgoCallersUse.Store(0) 846 847 printCgoTraceback(&cgoCallers) 848 } 849 850 if readgstatus(gp)&^_Gscan == _Gsyscall { 851 // Override registers if blocked in system call. 852 pc = gp.syscallpc 853 sp = gp.syscallsp 854 flags &^= unwindTrap 855 } 856 if gp.m != nil && gp.m.vdsoSP != 0 { 857 // Override registers if running in VDSO. This comes after the 858 // _Gsyscall check to cover VDSO calls after entersyscall. 859 pc = gp.m.vdsoPC 860 sp = gp.m.vdsoSP 861 flags &^= unwindTrap 862 } 863 864 // Print traceback. 865 // 866 // We print the first tracebackInnerFrames frames, and the last 867 // tracebackOuterFrames frames. There are many possible approaches to this. 868 // There are various complications to this: 869 // 870 // - We'd prefer to walk the stack once because in really bad situations 871 // traceback may crash (and we want as much output as possible) or the stack 872 // may be changing. 873 // 874 // - Each physical frame can represent several logical frames, so we might 875 // have to pause in the middle of a physical frame and pick up in the middle 876 // of a physical frame. 877 // 878 // - The cgo symbolizer can expand a cgo PC to more than one logical frame, 879 // and involves juggling state on the C side that we don't manage. Since its 880 // expansion state is managed on the C side, we can't capture the expansion 881 // state part way through, and because the output strings are managed on the 882 // C side, we can't capture the output. Thus, our only choice is to replay a 883 // whole expansion, potentially discarding some of it. 884 // 885 // Rejected approaches: 886 // 887 // - Do two passes where the first pass just counts and the second pass does 888 // all the printing. This is undesirable if the stack is corrupted or changing 889 // because we won't see a partial stack if we panic. 890 // 891 // - Keep a ring buffer of the last N logical frames and use this to print 892 // the bottom frames once we reach the end of the stack. This works, but 893 // requires keeping a surprising amount of state on the stack, and we have 894 // to run the cgo symbolizer twice—once to count frames, and a second to 895 // print them—since we can't retain the strings it returns. 896 // 897 // Instead, we print the outer frames, and if we reach that limit, we clone 898 // the unwinder, count the remaining frames, and then skip forward and 899 // finish printing from the clone. This makes two passes over the outer part 900 // of the stack, but the single pass over the inner part ensures that's 901 // printed immediately and not revisited. It keeps minimal state on the 902 // stack. And through a combination of skip counts and limits, we can do all 903 // of the steps we need with a single traceback printer implementation. 904 // 905 // We could be more lax about exactly how many frames we print, for example 906 // always stopping and resuming on physical frame boundaries, or at least 907 // cgo expansion boundaries. It's not clear that's much simpler. 908 flags |= unwindPrintErrors 909 var u unwinder 910 tracebackWithRuntime := func(showRuntime bool) int { 911 const maxInt int = 0x7fffffff 912 u.initAt(pc, sp, lr, gp, flags) 913 n, lastN := traceback2(&u, showRuntime, 0, tracebackInnerFrames) 914 if n < tracebackInnerFrames { 915 // We printed the whole stack. 916 return n 917 } 918 // Clone the unwinder and figure out how many frames are left. This 919 // count will include any logical frames already printed for u's current 920 // physical frame. 921 u2 := u 922 remaining, _ := traceback2(&u, showRuntime, maxInt, 0) 923 elide := remaining - lastN - tracebackOuterFrames 924 if elide > 0 { 925 print("...", elide, " frames elided...\n") 926 traceback2(&u2, showRuntime, lastN+elide, tracebackOuterFrames) 927 } else if elide <= 0 { 928 // There are tracebackOuterFrames or fewer frames left to print. 929 // Just print the rest of the stack. 930 traceback2(&u2, showRuntime, lastN, tracebackOuterFrames) 931 } 932 return n 933 } 934 // By default, omits runtime frames. If that means we print nothing at all, 935 // repeat forcing all frames printed. 936 if tracebackWithRuntime(false) == 0 { 937 tracebackWithRuntime(true) 938 } 939 printcreatedby(gp) 940 941 if gp.ancestors == nil { 942 return 943 } 944 for _, ancestor := range *gp.ancestors { 945 printAncestorTraceback(ancestor) 946 } 947 } 948 949 // traceback2 prints a stack trace starting at u. It skips the first "skip" 950 // logical frames, after which it prints at most "max" logical frames. It 951 // returns n, which is the number of logical frames skipped and printed, and 952 // lastN, which is the number of logical frames skipped or printed just in the 953 // physical frame that u references. 954 func traceback2(u *unwinder, showRuntime bool, skip, max int) (n, lastN int) { 955 // commitFrame commits to a logical frame and returns whether this frame 956 // should be printed and whether iteration should stop. 957 commitFrame := func() (pr, stop bool) { 958 if skip == 0 && max == 0 { 959 // Stop 960 return false, true 961 } 962 n++ 963 lastN++ 964 if skip > 0 { 965 // Skip 966 skip-- 967 return false, false 968 } 969 // Print 970 max-- 971 return true, false 972 } 973 974 gp := u.g.ptr() 975 level, _, _ := gotraceback() 976 var cgoBuf [32]uintptr 977 for ; u.valid(); u.next() { 978 lastN = 0 979 f := u.frame.fn 980 for iu, uf := newInlineUnwinder(f, u.symPC(), noEscapePtr(&u.cache)); uf.valid(); uf = iu.next(uf) { 981 sf := iu.srcFunc(uf) 982 callee := u.calleeFuncID 983 u.calleeFuncID = sf.funcID 984 if !(showRuntime || showframe(sf, gp, n == 0, callee)) { 985 continue 986 } 987 988 if pr, stop := commitFrame(); stop { 989 return 990 } else if !pr { 991 continue 992 } 993 994 name := sf.name() 995 file, line := iu.fileLine(uf) 996 // Print during crash. 997 // main(0x1, 0x2, 0x3) 998 // /home/rsc/go/src/runtime/x.go:23 +0xf 999 // 1000 printFuncName(name) 1001 print("(") 1002 if iu.isInlined(uf) { 1003 print("...") 1004 } else { 1005 argp := unsafe.Pointer(u.frame.argp) 1006 printArgs(f, argp, u.symPC()) 1007 } 1008 print(")\n") 1009 print("\t", file, ":", line) 1010 if !iu.isInlined(uf) { 1011 if u.frame.pc > f.entry() { 1012 print(" +", hex(u.frame.pc-f.entry())) 1013 } 1014 if gp.m != nil && gp.m.throwing >= throwTypeRuntime && gp == gp.m.curg || level >= 2 { 1015 print(" fp=", hex(u.frame.fp), " sp=", hex(u.frame.sp), " pc=", hex(u.frame.pc)) 1016 } 1017 } 1018 print("\n") 1019 } 1020 1021 // Print cgo frames. 1022 if cgoN := u.cgoCallers(cgoBuf[:]); cgoN > 0 { 1023 var arg cgoSymbolizerArg 1024 anySymbolized := false 1025 stop := false 1026 for _, pc := range cgoBuf[:cgoN] { 1027 if cgoSymbolizer == nil { 1028 if pr, stop := commitFrame(); stop { 1029 break 1030 } else if pr { 1031 print("non-Go function at pc=", hex(pc), "\n") 1032 } 1033 } else { 1034 stop = printOneCgoTraceback(pc, commitFrame, &arg) 1035 anySymbolized = true 1036 if stop { 1037 break 1038 } 1039 } 1040 } 1041 if anySymbolized { 1042 // Free symbolization state. 1043 arg.pc = 0 1044 callCgoSymbolizer(&arg) 1045 } 1046 if stop { 1047 return 1048 } 1049 } 1050 } 1051 return n, 0 1052 } 1053 1054 // printAncestorTraceback prints the traceback of the given ancestor. 1055 // TODO: Unify this with gentraceback and CallersFrames. 1056 func printAncestorTraceback(ancestor ancestorInfo) { 1057 print("[originating from goroutine ", ancestor.goid, "]:\n") 1058 for fidx, pc := range ancestor.pcs { 1059 f := findfunc(pc) // f previously validated 1060 if showfuncinfo(f.srcFunc(), fidx == 0, abi.FuncIDNormal) { 1061 printAncestorTracebackFuncInfo(f, pc) 1062 } 1063 } 1064 if len(ancestor.pcs) == tracebackInnerFrames { 1065 print("...additional frames elided...\n") 1066 } 1067 // Show what created goroutine, except main goroutine (goid 1). 1068 f := findfunc(ancestor.gopc) 1069 if f.valid() && showfuncinfo(f.srcFunc(), false, abi.FuncIDNormal) && ancestor.goid != 1 { 1070 // In ancestor mode, we'll already print the goroutine ancestor. 1071 // Pass 0 for the goid parameter so we don't print it again. 1072 printcreatedby1(f, ancestor.gopc, 0) 1073 } 1074 } 1075 1076 // printAncestorTracebackFuncInfo prints the given function info at a given pc 1077 // within an ancestor traceback. The precision of this info is reduced 1078 // due to only have access to the pcs at the time of the caller 1079 // goroutine being created. 1080 func printAncestorTracebackFuncInfo(f funcInfo, pc uintptr) { 1081 u, uf := newInlineUnwinder(f, pc, nil) 1082 file, line := u.fileLine(uf) 1083 printFuncName(u.srcFunc(uf).name()) 1084 print("(...)\n") 1085 print("\t", file, ":", line) 1086 if pc > f.entry() { 1087 print(" +", hex(pc-f.entry())) 1088 } 1089 print("\n") 1090 } 1091 1092 func callers(skip int, pcbuf []uintptr) int { 1093 sp := getcallersp() 1094 pc := getcallerpc() 1095 gp := getg() 1096 var n int 1097 systemstack(func() { 1098 var u unwinder 1099 u.initAt(pc, sp, 0, gp, unwindSilentErrors) 1100 n = tracebackPCs(&u, skip, pcbuf) 1101 }) 1102 return n 1103 } 1104 1105 func gcallers(gp *g, skip int, pcbuf []uintptr) int { 1106 var u unwinder 1107 u.init(gp, unwindSilentErrors) 1108 return tracebackPCs(&u, skip, pcbuf) 1109 } 1110 1111 // showframe reports whether the frame with the given characteristics should 1112 // be printed during a traceback. 1113 func showframe(sf srcFunc, gp *g, firstFrame bool, calleeID abi.FuncID) bool { 1114 mp := getg().m 1115 if mp.throwing >= throwTypeRuntime && gp != nil && (gp == mp.curg || gp == mp.caughtsig.ptr()) { 1116 return true 1117 } 1118 return showfuncinfo(sf, firstFrame, calleeID) 1119 } 1120 1121 // showfuncinfo reports whether a function with the given characteristics should 1122 // be printed during a traceback. 1123 func showfuncinfo(sf srcFunc, firstFrame bool, calleeID abi.FuncID) bool { 1124 level, _, _ := gotraceback() 1125 if level > 1 { 1126 // Show all frames. 1127 return true 1128 } 1129 1130 if sf.funcID == abi.FuncIDWrapper && elideWrapperCalling(calleeID) { 1131 return false 1132 } 1133 1134 name := sf.name() 1135 1136 // Special case: always show runtime.gopanic frame 1137 // in the middle of a stack trace, so that we can 1138 // see the boundary between ordinary code and 1139 // panic-induced deferred code. 1140 // See golang.org/issue/5832. 1141 if name == "runtime.gopanic" && !firstFrame { 1142 return true 1143 } 1144 1145 return bytealg.IndexByteString(name, '.') >= 0 && (!hasPrefix(name, "runtime.") || isExportedRuntime(name)) 1146 } 1147 1148 // isExportedRuntime reports whether name is an exported runtime function. 1149 // It is only for runtime functions, so ASCII A-Z is fine. 1150 func isExportedRuntime(name string) bool { 1151 const n = len("runtime.") 1152 return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z' 1153 } 1154 1155 // elideWrapperCalling reports whether a wrapper function that called 1156 // function id should be elided from stack traces. 1157 func elideWrapperCalling(id abi.FuncID) bool { 1158 // If the wrapper called a panic function instead of the 1159 // wrapped function, we want to include it in stacks. 1160 return !(id == abi.FuncID_gopanic || id == abi.FuncID_sigpanic || id == abi.FuncID_panicwrap) 1161 } 1162 1163 var gStatusStrings = [...]string{ 1164 _Gidle: "idle", 1165 _Grunnable: "runnable", 1166 _Grunning: "running", 1167 _Gsyscall: "syscall", 1168 _Gwaiting: "waiting", 1169 _Gdead: "dead", 1170 _Gcopystack: "copystack", 1171 _Gpreempted: "preempted", 1172 } 1173 1174 func goroutineheader(gp *g) { 1175 gpstatus := readgstatus(gp) 1176 1177 isScan := gpstatus&_Gscan != 0 1178 gpstatus &^= _Gscan // drop the scan bit 1179 1180 // Basic string status 1181 var status string 1182 if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) { 1183 status = gStatusStrings[gpstatus] 1184 } else { 1185 status = "???" 1186 } 1187 1188 // Override. 1189 if gpstatus == _Gwaiting && gp.waitreason != waitReasonZero { 1190 status = gp.waitreason.String() 1191 } 1192 1193 // approx time the G is blocked, in minutes 1194 var waitfor int64 1195 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 { 1196 waitfor = (nanotime() - gp.waitsince) / 60e9 1197 } 1198 print("goroutine ", gp.goid, " [", status) 1199 if isScan { 1200 print(" (scan)") 1201 } 1202 if waitfor >= 1 { 1203 print(", ", waitfor, " minutes") 1204 } 1205 if gp.lockedm != 0 { 1206 print(", locked to thread") 1207 } 1208 print("]:\n") 1209 } 1210 1211 func tracebackothers(me *g) { 1212 level, _, _ := gotraceback() 1213 1214 // Show the current goroutine first, if we haven't already. 1215 curgp := getg().m.curg 1216 if curgp != nil && curgp != me { 1217 print("\n") 1218 goroutineheader(curgp) 1219 traceback(^uintptr(0), ^uintptr(0), 0, curgp) 1220 } 1221 1222 // We can't call locking forEachG here because this may be during fatal 1223 // throw/panic, where locking could be out-of-order or a direct 1224 // deadlock. 1225 // 1226 // Instead, use forEachGRace, which requires no locking. We don't lock 1227 // against concurrent creation of new Gs, but even with allglock we may 1228 // miss Gs created after this loop. 1229 forEachGRace(func(gp *g) { 1230 if gp == me || gp == curgp || readgstatus(gp) == _Gdead || isSystemGoroutine(gp, false) && level < 2 { 1231 return 1232 } 1233 print("\n") 1234 goroutineheader(gp) 1235 // Note: gp.m == getg().m occurs when tracebackothers is called 1236 // from a signal handler initiated during a systemstack call. 1237 // The original G is still in the running state, and we want to 1238 // print its stack. 1239 if gp.m != getg().m && readgstatus(gp)&^_Gscan == _Grunning { 1240 print("\tgoroutine running on other thread; stack unavailable\n") 1241 printcreatedby(gp) 1242 } else { 1243 traceback(^uintptr(0), ^uintptr(0), 0, gp) 1244 } 1245 }) 1246 } 1247 1248 // tracebackHexdump hexdumps part of stk around frame.sp and frame.fp 1249 // for debugging purposes. If the address bad is included in the 1250 // hexdumped range, it will mark it as well. 1251 func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) { 1252 const expand = 32 * goarch.PtrSize 1253 const maxExpand = 256 * goarch.PtrSize 1254 // Start around frame.sp. 1255 lo, hi := frame.sp, frame.sp 1256 // Expand to include frame.fp. 1257 if frame.fp != 0 && frame.fp < lo { 1258 lo = frame.fp 1259 } 1260 if frame.fp != 0 && frame.fp > hi { 1261 hi = frame.fp 1262 } 1263 // Expand a bit more. 1264 lo, hi = lo-expand, hi+expand 1265 // But don't go too far from frame.sp. 1266 if lo < frame.sp-maxExpand { 1267 lo = frame.sp - maxExpand 1268 } 1269 if hi > frame.sp+maxExpand { 1270 hi = frame.sp + maxExpand 1271 } 1272 // And don't go outside the stack bounds. 1273 if lo < stk.lo { 1274 lo = stk.lo 1275 } 1276 if hi > stk.hi { 1277 hi = stk.hi 1278 } 1279 1280 // Print the hex dump. 1281 print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n") 1282 hexdumpWords(lo, hi, func(p uintptr) byte { 1283 switch p { 1284 case frame.fp: 1285 return '>' 1286 case frame.sp: 1287 return '<' 1288 case bad: 1289 return '!' 1290 } 1291 return 0 1292 }) 1293 } 1294 1295 // isSystemGoroutine reports whether the goroutine g must be omitted 1296 // in stack dumps and deadlock detector. This is any goroutine that 1297 // starts at a runtime.* entry point, except for runtime.main, 1298 // runtime.handleAsyncEvent (wasm only) and sometimes runtime.runfinq. 1299 // 1300 // If fixed is true, any goroutine that can vary between user and 1301 // system (that is, the finalizer goroutine) is considered a user 1302 // goroutine. 1303 func isSystemGoroutine(gp *g, fixed bool) bool { 1304 // Keep this in sync with internal/trace.IsSystemGoroutine. 1305 f := findfunc(gp.startpc) 1306 if !f.valid() { 1307 return false 1308 } 1309 if f.funcID == abi.FuncID_runtime_main || f.funcID == abi.FuncID_handleAsyncEvent { 1310 return false 1311 } 1312 if f.funcID == abi.FuncID_runfinq { 1313 // We include the finalizer goroutine if it's calling 1314 // back into user code. 1315 if fixed { 1316 // This goroutine can vary. In fixed mode, 1317 // always consider it a user goroutine. 1318 return false 1319 } 1320 return fingStatus.Load()&fingRunningFinalizer == 0 1321 } 1322 return hasPrefix(funcname(f), "runtime.") 1323 } 1324 1325 // SetCgoTraceback records three C functions to use to gather 1326 // traceback information from C code and to convert that traceback 1327 // information into symbolic information. These are used when printing 1328 // stack traces for a program that uses cgo. 1329 // 1330 // The traceback and context functions may be called from a signal 1331 // handler, and must therefore use only async-signal safe functions. 1332 // The symbolizer function may be called while the program is 1333 // crashing, and so must be cautious about using memory. None of the 1334 // functions may call back into Go. 1335 // 1336 // The context function will be called with a single argument, a 1337 // pointer to a struct: 1338 // 1339 // struct { 1340 // Context uintptr 1341 // } 1342 // 1343 // In C syntax, this struct will be 1344 // 1345 // struct { 1346 // uintptr_t Context; 1347 // }; 1348 // 1349 // If the Context field is 0, the context function is being called to 1350 // record the current traceback context. It should record in the 1351 // Context field whatever information is needed about the current 1352 // point of execution to later produce a stack trace, probably the 1353 // stack pointer and PC. In this case the context function will be 1354 // called from C code. 1355 // 1356 // If the Context field is not 0, then it is a value returned by a 1357 // previous call to the context function. This case is called when the 1358 // context is no longer needed; that is, when the Go code is returning 1359 // to its C code caller. This permits the context function to release 1360 // any associated resources. 1361 // 1362 // While it would be correct for the context function to record a 1363 // complete a stack trace whenever it is called, and simply copy that 1364 // out in the traceback function, in a typical program the context 1365 // function will be called many times without ever recording a 1366 // traceback for that context. Recording a complete stack trace in a 1367 // call to the context function is likely to be inefficient. 1368 // 1369 // The traceback function will be called with a single argument, a 1370 // pointer to a struct: 1371 // 1372 // struct { 1373 // Context uintptr 1374 // SigContext uintptr 1375 // Buf *uintptr 1376 // Max uintptr 1377 // } 1378 // 1379 // In C syntax, this struct will be 1380 // 1381 // struct { 1382 // uintptr_t Context; 1383 // uintptr_t SigContext; 1384 // uintptr_t* Buf; 1385 // uintptr_t Max; 1386 // }; 1387 // 1388 // The Context field will be zero to gather a traceback from the 1389 // current program execution point. In this case, the traceback 1390 // function will be called from C code. 1391 // 1392 // Otherwise Context will be a value previously returned by a call to 1393 // the context function. The traceback function should gather a stack 1394 // trace from that saved point in the program execution. The traceback 1395 // function may be called from an execution thread other than the one 1396 // that recorded the context, but only when the context is known to be 1397 // valid and unchanging. The traceback function may also be called 1398 // deeper in the call stack on the same thread that recorded the 1399 // context. The traceback function may be called multiple times with 1400 // the same Context value; it will usually be appropriate to cache the 1401 // result, if possible, the first time this is called for a specific 1402 // context value. 1403 // 1404 // If the traceback function is called from a signal handler on a Unix 1405 // system, SigContext will be the signal context argument passed to 1406 // the signal handler (a C ucontext_t* cast to uintptr_t). This may be 1407 // used to start tracing at the point where the signal occurred. If 1408 // the traceback function is not called from a signal handler, 1409 // SigContext will be zero. 1410 // 1411 // Buf is where the traceback information should be stored. It should 1412 // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is 1413 // the PC of that function's caller, and so on. Max is the maximum 1414 // number of entries to store. The function should store a zero to 1415 // indicate the top of the stack, or that the caller is on a different 1416 // stack, presumably a Go stack. 1417 // 1418 // Unlike runtime.Callers, the PC values returned should, when passed 1419 // to the symbolizer function, return the file/line of the call 1420 // instruction. No additional subtraction is required or appropriate. 1421 // 1422 // On all platforms, the traceback function is invoked when a call from 1423 // Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le, 1424 // linux/arm64, and freebsd/amd64, the traceback function is also invoked 1425 // when a signal is received by a thread that is executing a cgo call. 1426 // The traceback function should not make assumptions about when it is 1427 // called, as future versions of Go may make additional calls. 1428 // 1429 // The symbolizer function will be called with a single argument, a 1430 // pointer to a struct: 1431 // 1432 // struct { 1433 // PC uintptr // program counter to fetch information for 1434 // File *byte // file name (NUL terminated) 1435 // Lineno uintptr // line number 1436 // Func *byte // function name (NUL terminated) 1437 // Entry uintptr // function entry point 1438 // More uintptr // set non-zero if more info for this PC 1439 // Data uintptr // unused by runtime, available for function 1440 // } 1441 // 1442 // In C syntax, this struct will be 1443 // 1444 // struct { 1445 // uintptr_t PC; 1446 // char* File; 1447 // uintptr_t Lineno; 1448 // char* Func; 1449 // uintptr_t Entry; 1450 // uintptr_t More; 1451 // uintptr_t Data; 1452 // }; 1453 // 1454 // The PC field will be a value returned by a call to the traceback 1455 // function. 1456 // 1457 // The first time the function is called for a particular traceback, 1458 // all the fields except PC will be 0. The function should fill in the 1459 // other fields if possible, setting them to 0/nil if the information 1460 // is not available. The Data field may be used to store any useful 1461 // information across calls. The More field should be set to non-zero 1462 // if there is more information for this PC, zero otherwise. If More 1463 // is set non-zero, the function will be called again with the same 1464 // PC, and may return different information (this is intended for use 1465 // with inlined functions). If More is zero, the function will be 1466 // called with the next PC value in the traceback. When the traceback 1467 // is complete, the function will be called once more with PC set to 1468 // zero; this may be used to free any information. Each call will 1469 // leave the fields of the struct set to the same values they had upon 1470 // return, except for the PC field when the More field is zero. The 1471 // function must not keep a copy of the struct pointer between calls. 1472 // 1473 // When calling SetCgoTraceback, the version argument is the version 1474 // number of the structs that the functions expect to receive. 1475 // Currently this must be zero. 1476 // 1477 // The symbolizer function may be nil, in which case the results of 1478 // the traceback function will be displayed as numbers. If the 1479 // traceback function is nil, the symbolizer function will never be 1480 // called. The context function may be nil, in which case the 1481 // traceback function will only be called with the context field set 1482 // to zero. If the context function is nil, then calls from Go to C 1483 // to Go will not show a traceback for the C portion of the call stack. 1484 // 1485 // SetCgoTraceback should be called only once, ideally from an init function. 1486 func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) { 1487 if version != 0 { 1488 panic("unsupported version") 1489 } 1490 1491 if cgoTraceback != nil && cgoTraceback != traceback || 1492 cgoContext != nil && cgoContext != context || 1493 cgoSymbolizer != nil && cgoSymbolizer != symbolizer { 1494 panic("call SetCgoTraceback only once") 1495 } 1496 1497 cgoTraceback = traceback 1498 cgoContext = context 1499 cgoSymbolizer = symbolizer 1500 1501 // The context function is called when a C function calls a Go 1502 // function. As such it is only called by C code in runtime/cgo. 1503 if _cgo_set_context_function != nil { 1504 cgocall(_cgo_set_context_function, context) 1505 } 1506 } 1507 1508 var cgoTraceback unsafe.Pointer 1509 var cgoContext unsafe.Pointer 1510 var cgoSymbolizer unsafe.Pointer 1511 1512 // cgoTracebackArg is the type passed to cgoTraceback. 1513 type cgoTracebackArg struct { 1514 context uintptr 1515 sigContext uintptr 1516 buf *uintptr 1517 max uintptr 1518 } 1519 1520 // cgoContextArg is the type passed to the context function. 1521 type cgoContextArg struct { 1522 context uintptr 1523 } 1524 1525 // cgoSymbolizerArg is the type passed to cgoSymbolizer. 1526 type cgoSymbolizerArg struct { 1527 pc uintptr 1528 file *byte 1529 lineno uintptr 1530 funcName *byte 1531 entry uintptr 1532 more uintptr 1533 data uintptr 1534 } 1535 1536 // printCgoTraceback prints a traceback of callers. 1537 func printCgoTraceback(callers *cgoCallers) { 1538 if cgoSymbolizer == nil { 1539 for _, c := range callers { 1540 if c == 0 { 1541 break 1542 } 1543 print("non-Go function at pc=", hex(c), "\n") 1544 } 1545 return 1546 } 1547 1548 commitFrame := func() (pr, stop bool) { return true, false } 1549 var arg cgoSymbolizerArg 1550 for _, c := range callers { 1551 if c == 0 { 1552 break 1553 } 1554 printOneCgoTraceback(c, commitFrame, &arg) 1555 } 1556 arg.pc = 0 1557 callCgoSymbolizer(&arg) 1558 } 1559 1560 // printOneCgoTraceback prints the traceback of a single cgo caller. 1561 // This can print more than one line because of inlining. 1562 // It returns the "stop" result of commitFrame. 1563 func printOneCgoTraceback(pc uintptr, commitFrame func() (pr, stop bool), arg *cgoSymbolizerArg) bool { 1564 arg.pc = pc 1565 for { 1566 if pr, stop := commitFrame(); stop { 1567 return true 1568 } else if !pr { 1569 continue 1570 } 1571 1572 callCgoSymbolizer(arg) 1573 if arg.funcName != nil { 1574 // Note that we don't print any argument 1575 // information here, not even parentheses. 1576 // The symbolizer must add that if appropriate. 1577 println(gostringnocopy(arg.funcName)) 1578 } else { 1579 println("non-Go function") 1580 } 1581 print("\t") 1582 if arg.file != nil { 1583 print(gostringnocopy(arg.file), ":", arg.lineno, " ") 1584 } 1585 print("pc=", hex(pc), "\n") 1586 if arg.more == 0 { 1587 return false 1588 } 1589 } 1590 } 1591 1592 // callCgoSymbolizer calls the cgoSymbolizer function. 1593 func callCgoSymbolizer(arg *cgoSymbolizerArg) { 1594 call := cgocall 1595 if panicking.Load() > 0 || getg().m.curg != getg() { 1596 // We do not want to call into the scheduler when panicking 1597 // or when on the system stack. 1598 call = asmcgocall 1599 } 1600 if msanenabled { 1601 msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{})) 1602 } 1603 if asanenabled { 1604 asanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{})) 1605 } 1606 call(cgoSymbolizer, noescape(unsafe.Pointer(arg))) 1607 } 1608 1609 // cgoContextPCs gets the PC values from a cgo traceback. 1610 func cgoContextPCs(ctxt uintptr, buf []uintptr) { 1611 if cgoTraceback == nil { 1612 return 1613 } 1614 call := cgocall 1615 if panicking.Load() > 0 || getg().m.curg != getg() { 1616 // We do not want to call into the scheduler when panicking 1617 // or when on the system stack. 1618 call = asmcgocall 1619 } 1620 arg := cgoTracebackArg{ 1621 context: ctxt, 1622 buf: (*uintptr)(noescape(unsafe.Pointer(&buf[0]))), 1623 max: uintptr(len(buf)), 1624 } 1625 if msanenabled { 1626 msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg)) 1627 } 1628 if asanenabled { 1629 asanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg)) 1630 } 1631 call(cgoTraceback, noescape(unsafe.Pointer(&arg))) 1632 }