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