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.
9 "runtime/internal/atomic"
10 "runtime/internal/sys"
14 // The code in this file implements stack trace walking for all architectures.
15 // The most important fact about a given architecture is whether it uses a link register.
16 // On systems with link registers, the prologue for a non-leaf function stores the
17 // incoming value of LR at the bottom of the newly allocated stack frame.
18 // On systems without link registers (x86), the architecture pushes a return PC during
19 // the call instruction, so the return PC ends up above the stack frame.
20 // In this file, the return PC is always called LR, no matter how it was found.
22 const usesLR = sys.MinFrameSize > 0
24 // Generic traceback. Handles runtime stack prints (pcbuf == nil),
25 // the runtime.Callers function (pcbuf != nil), as well as the garbage
26 // collector (callback != nil). A little clunky to merge these, but avoids
27 // duplicating the code and all its subtlety.
29 // The skip argument is only valid with pcbuf != nil and counts the number
30 // of logical frames to skip rather than physical frames (with inlining, a
31 // PC in pcbuf can represent multiple calls).
32 func gentraceback(pc0, sp0, lr0 uintptr, gp *g, skip int, pcbuf *uintptr, max int, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer, flags uint) int {
33 if skip > 0 && callback != nil {
34 throw("gentraceback callback cannot be used with non-zero skip")
37 // Don't call this "g"; it's too easy get "g" and "gp" confused.
38 if ourg := getg(); ourg == gp && ourg == ourg.m.curg {
39 // The starting sp has been passed in as a uintptr, and the caller may
40 // have other uintptr-typed stack references as well.
41 // If during one of the calls that got us here or during one of the
42 // callbacks below the stack must be grown, all these uintptr references
43 // to the stack will not be updated, and gentraceback will continue
44 // to inspect the old stack memory, which may no longer be valid.
45 // Even if all the variables were updated correctly, it is not clear that
46 // we want to expose a traceback that begins on one stack and ends
47 // on another stack. That could confuse callers quite a bit.
48 // Instead, we require that gentraceback and any other function that
49 // accepts an sp for the current goroutine (typically obtained by
50 // calling getcallersp) must not run on that goroutine's stack but
51 // instead on the g0 stack.
52 throw("gentraceback cannot trace user goroutine on its own stack")
54 level, _, _ := gotraceback()
56 var ctxt *funcval // Context pointer for unstarted goroutines. See issue #25897.
58 if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
59 if gp.syscallsp != 0 {
71 ctxt = (*funcval)(gp.sched.ctxt)
84 printing := pcbuf == nil && callback == nil
86 // If the PC is zero, it's likely a nil function call.
87 // Start in the caller's frame.
90 frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
93 frame.pc = uintptr(*(*uintptr)(unsafe.Pointer(frame.sp)))
94 frame.sp += sys.PtrSize
98 f := findfunc(frame.pc)
100 if callback != nil || printing {
101 print("runtime: unknown pc ", hex(frame.pc), "\n")
102 tracebackHexdump(gp.stack, &frame, 0)
111 var cache pcvalueCache
113 lastFuncID := funcID_normal
117 // pc is the PC of the running function.
118 // sp is the stack pointer at that program counter.
119 // fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
120 // stk is the stack containing sp.
121 // The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
124 // No frame information, must be external function, like race support.
125 // See golang.org/issue/13568.
129 // Compute function info flags.
131 if f.funcID == funcID_cgocallback {
132 // cgocallback does write SP to switch from the g0 to the curg stack,
133 // but it carefully arranges that during the transition BOTH stacks
134 // have cgocallback frame valid for unwinding through.
135 // So we don't need to exclude it with the other SP-writing functions.
136 flag &^= funcFlag_SPWRITE
138 if frame.pc == pc0 && frame.sp == sp0 && pc0 == gp.syscallpc && sp0 == gp.syscallsp {
139 // Some Syscall functions write to SP, but they do so only after
140 // saving the entry PC/SP using entersyscall.
141 // Since we are using the entry PC/SP, the later SP write doesn't matter.
142 flag &^= funcFlag_SPWRITE
145 // Found an actual function.
146 // Derive frame pointer and link register.
148 // Jump over system stack transitions. If we're on g0 and there's a user
149 // goroutine, try to jump. Otherwise this is a regular call.
150 if flags&_TraceJumpStack != 0 && gp == gp.m.g0 && gp.m.curg != nil {
152 case funcID_morestack:
153 // morestack does not return normally -- newstack()
154 // gogo's to curg.sched. Match that.
155 // This keeps morestack() from showing up in the backtrace,
156 // but that makes some sense since it'll never be returned
158 frame.pc = gp.m.curg.sched.pc
159 frame.fn = findfunc(frame.pc)
162 frame.sp = gp.m.curg.sched.sp
163 cgoCtxt = gp.m.curg.cgoCtxt
164 case funcID_systemstack:
165 // systemstack returns normally, so just follow the
167 frame.sp = gp.m.curg.sched.sp
168 cgoCtxt = gp.m.curg.cgoCtxt
169 flag &^= funcFlag_SPWRITE
172 frame.fp = frame.sp + uintptr(funcspdelta(f, frame.pc, &cache))
174 // On x86, call instruction pushes return PC before entering new function.
175 frame.fp += sys.PtrSize
179 if flag&funcFlag_TOPFRAME != 0 {
180 // This function marks the top of the stack. Stop the traceback.
183 } else if flag&funcFlag_SPWRITE != 0 && (callback == nil || n > 0) {
184 // The function we are in does a write to SP that we don't know
185 // how to encode in the spdelta table. Examples include context
186 // switch routines like runtime.gogo but also any code that switches
187 // to the g0 stack to run host C code. Since we can't reliably unwind
188 // the SP (we might not even be on the stack we think we are),
189 // we stop the traceback here.
190 // This only applies for profiling signals (callback == nil).
192 // For a GC stack traversal (callback != nil), we should only see
193 // a function when it has voluntarily preempted itself on entry
194 // during the stack growth check. In that case, the function has
195 // not yet had a chance to do any writes to SP and is safe to unwind.
196 // isAsyncSafePoint does not allow assembly functions to be async preempted,
197 // and preemptPark double-checks that SPWRITE functions are not async preempted.
198 // So for GC stack traversal we leave things alone (this if body does not execute for n == 0)
199 // at the bottom frame of the stack. But farther up the stack we'd better not
202 println("traceback: unexpected SPWRITE function", funcname(f))
210 if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
212 frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
216 lrPtr = frame.fp - sys.PtrSize
217 frame.lr = uintptr(*(*uintptr)(unsafe.Pointer(lrPtr)))
220 flr = findfunc(frame.lr)
222 // This happens if you get a profiling interrupt at just the wrong time.
223 // In that context it is okay to stop early.
224 // But if callback is set, we're doing a garbage collection and must
225 // get everything, so crash loudly.
227 if doPrint && gp.m.incgo && f.funcID == funcID_sigpanic {
228 // We can inject sigpanic
229 // calls directly into C code,
230 // in which case we'll see a C
231 // return PC. Don't complain.
234 if callback != nil || doPrint {
235 print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
236 tracebackHexdump(gp.stack, &frame, lrPtr)
239 throw("unknown caller pc")
244 frame.varp = frame.fp
246 // On x86, call instruction pushes return PC before entering new function.
247 frame.varp -= sys.PtrSize
250 // For architectures with frame pointers, if there's
251 // a frame, then there's a saved frame pointer here.
253 // NOTE: This code is not as general as it looks.
254 // On x86, the ABI is to save the frame pointer word at the
255 // top of the stack frame, so we have to back down over it.
256 // On arm64, the frame pointer should be at the bottom of
257 // the stack (with R29 (aka FP) = RSP), in which case we would
258 // not want to do the subtraction here. But we started out without
259 // any frame pointer, and when we wanted to add it, we didn't
260 // want to break all the assembly doing direct writes to 8(RSP)
261 // to set the first parameter to a called function.
262 // So we decided to write the FP link *below* the stack pointer
263 // (with R29 = RSP - 8 in Go functions).
264 // This is technically ABI-compatible but not standard.
265 // And it happens to end up mimicking the x86 layout.
266 // Other architectures may make different decisions.
267 if frame.varp > frame.sp && framepointer_enabled {
268 frame.varp -= sys.PtrSize
271 // Derive size of arguments.
272 // Most functions have a fixed-size argument block,
273 // so we can use metadata about the function f.
274 // Not all, though: there are some variadic functions
275 // in package runtime and reflect, and for those we use call-specific
276 // metadata recorded by f's caller.
277 if callback != nil || printing {
278 frame.argp = frame.fp + sys.MinFrameSize
280 frame.arglen, frame.argmap, ok = getArgInfoFast(f, callback != nil)
282 frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil, ctxt)
285 ctxt = nil // ctxt is only needed to get arg maps for the topmost frame
287 // Determine frame's 'continuation PC', where it can continue.
288 // Normally this is the return address on the stack, but if sigpanic
289 // is immediately below this function on the stack, then the frame
290 // stopped executing due to a trap, and frame.pc is probably not
291 // a safe point for looking up liveness information. In this panicking case,
292 // the function either doesn't return at all (if it has no defers or if the
293 // defers do not recover) or it returns from one of the calls to
294 // deferproc a second time (if the corresponding deferred func recovers).
295 // In the latter case, use a deferreturn call site as the continuation pc.
296 frame.continpc = frame.pc
298 if frame.fn.deferreturn != 0 {
299 frame.continpc = frame.fn.entry + uintptr(frame.fn.deferreturn) + 1
300 // Note: this may perhaps keep return variables alive longer than
301 // strictly necessary, as we are using "function has a defer statement"
302 // as a proxy for "function actually deferred something". It seems
303 // to be a minor drawback. (We used to actually look through the
304 // gp._defer for a defer corresponding to this function, but that
305 // is hard to do with defer records on the stack during a stack copy.)
306 // Note: the +1 is to offset the -1 that
307 // stack.go:getStackMap does to back up a return
308 // address make sure the pc is in the CALL instruction.
315 if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
322 // backup to CALL instruction to read inlining info (same logic as below)
324 // Normally, pc is a return address. In that case, we want to look up
325 // file/line information using pc-1, because that is the pc of the
326 // call instruction (more precisely, the last byte of the call instruction).
327 // Callers expect the pc buffer to contain return addresses and do the
328 // same -1 themselves, so we keep pc unchanged.
329 // When the pc is from a signal (e.g. profiler or segv) then we want
330 // to look up file/line information using pc, and we store pc+1 in the
331 // pc buffer so callers can unconditionally subtract 1 before looking up.
333 // The pc can be at function entry when the frame is initialized without
334 // actually running code, like runtime.mstart.
335 if (n == 0 && flags&_TraceTrap != 0) || waspanic || pc == f.entry {
341 // If there is inlining info, record the inner frames.
342 if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
343 inltree := (*[1 << 20]inlinedCall)(inldata)
345 ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, &cache)
349 if inltree[ix].funcID == funcID_wrapper && elideWrapperCalling(lastFuncID) {
354 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
357 lastFuncID = inltree[ix].funcID
358 // Back up to an instruction in the "caller".
359 tracepc = frame.fn.entry + uintptr(inltree[ix].parentPc)
363 // Record the main frame.
364 if f.funcID == funcID_wrapper && elideWrapperCalling(lastFuncID) {
365 // Ignore wrapper functions (except when they trigger panics).
369 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
372 lastFuncID = f.funcID
373 n-- // offset n++ below
377 // assume skip=0 for printing.
379 // Never elide wrappers if we haven't printed
380 // any frames. And don't elide wrappers that
381 // called panic rather than the wrapped
382 // function. Otherwise, leave them out.
384 // backup to CALL instruction to read inlining info (same logic as below)
386 if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
389 // If there is inlining info, print the inner frames.
390 if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
391 inltree := (*[1 << 20]inlinedCall)(inldata)
393 inlFuncInfo := funcInfo{&inlFunc, f.datap}
395 ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil)
400 // Create a fake _func for the
402 inlFunc.nameoff = inltree[ix].func_
403 inlFunc.funcID = inltree[ix].funcID
405 if (flags&_TraceRuntimeFrames) != 0 || showframe(inlFuncInfo, gp, nprint == 0, inlFuncInfo.funcID, lastFuncID) {
406 name := funcname(inlFuncInfo)
407 file, line := funcline(f, tracepc)
408 print(name, "(...)\n")
409 print("\t", file, ":", line, "\n")
412 lastFuncID = inltree[ix].funcID
413 // Back up to an instruction in the "caller".
414 tracepc = frame.fn.entry + uintptr(inltree[ix].parentPc)
417 if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, f.funcID, lastFuncID) {
418 // Print during crash.
419 // main(0x1, 0x2, 0x3)
420 // /home/rsc/go/src/runtime/x.go:23 +0xf
423 file, line := funcline(f, tracepc)
424 if name == "runtime.gopanic" {
428 argp := unsafe.Pointer(frame.argp)
431 print("\t", file, ":", line)
432 if frame.pc > f.entry {
433 print(" +", hex(frame.pc-f.entry))
435 if gp.m != nil && gp.m.throwing > 0 && gp == gp.m.curg || level >= 2 {
436 print(" fp=", hex(frame.fp), " sp=", hex(frame.sp), " pc=", hex(frame.pc))
441 lastFuncID = f.funcID
445 if f.funcID == funcID_cgocallback && len(cgoCtxt) > 0 {
446 ctxt := cgoCtxt[len(cgoCtxt)-1]
447 cgoCtxt = cgoCtxt[:len(cgoCtxt)-1]
449 // skip only applies to Go frames.
450 // callback != nil only used when we only care
452 if skip == 0 && callback == nil {
453 n = tracebackCgoContext(pcbuf, printing, ctxt, n, max)
457 waspanic = f.funcID == funcID_sigpanic
458 injectedCall := waspanic || f.funcID == funcID_asyncPreempt
460 // Do not unwind past the bottom of the stack.
465 // Unwind to next frame.
473 // On link register architectures, sighandler saves the LR on stack
474 // before faking a call.
475 if usesLR && injectedCall {
476 x := *(*uintptr)(unsafe.Pointer(frame.sp))
477 frame.sp += alignUp(sys.MinFrameSize, sys.StackAlign)
478 f = findfunc(frame.pc)
482 } else if funcspdelta(f, frame.pc, &cache) == 0 {
492 // Note that panic != nil is okay here: there can be leftover panics,
493 // because the defers on the panic stack do not nest in frame order as
494 // they do on the defer stack. If you have:
500 // frame 4's panic starts running defers
501 // frame 5, running d3, defers d4
503 // frame 5's panic starts running defers
504 // frame 6, running d4, garbage collects
505 // frame 6, running d2, garbage collects
507 // During the execution of d4, the panic stack is d4 -> d3, which
508 // is nested properly, and we'll treat frame 3 as resumable, because we
509 // can find d3. (And in fact frame 3 is resumable. If d4 recovers
510 // and frame 5 continues running, d3, d3 can recover and we'll
511 // resume execution in (returning from) frame 3.)
513 // During the execution of d2, however, the panic stack is d2 -> d3,
514 // which is inverted. The scan will match d2 to frame 2 but having
515 // d2 on the stack until then means it will not match d3 to frame 3.
516 // This is okay: if we're running d2, then all the defers after d2 have
517 // completed and their corresponding frames are dead. Not finding d3
518 // for frame 3 means we'll set frame 3's continpc == 0, which is correct
519 // (frame 3 is dead). At the end of the walk the panic stack can thus
520 // contain defers (d3 in this case) for dead frames. The inversion here
521 // always indicates a dead frame, and the effect of the inversion on the
522 // scan is to hide those dead frames, so the scan is still okay:
523 // what's left on the panic stack are exactly (and only) the dead frames.
525 // We require callback != nil here because only when callback != nil
526 // do we know that gentraceback is being called in a "must be correct"
527 // context as opposed to a "best effort" context. The tracebacks with
528 // callbacks only happen when everything is stopped nicely.
529 // At other times, such as when gathering a stack for a profiling signal
530 // or when printing a traceback during a crash, everything may not be
531 // stopped nicely, and the stack walk may not be able to complete.
532 if callback != nil && n < max && frame.sp != gp.stktopsp {
533 print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n")
534 print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n")
535 throw("traceback did not unwind completely")
541 // printArgs prints function arguments in traceback.
542 func printArgs(f funcInfo, argp unsafe.Pointer) {
543 // The "instruction" of argument printing is encoded in _FUNCDATA_ArgInfo.
544 // See cmd/compile/internal/ssagen.emitArgInfo for the description of the
546 // These constants need to be in sync with the compiler.
552 _offsetTooLarge = 0xfb
556 limit = 10 // print no more than 10 args/components
557 maxDepth = 5 // no more than 5 layers of nesting
558 maxLen = (maxDepth*3+2)*limit + 1 // max length of _FUNCDATA_ArgInfo (see the compiler side for reasoning)
561 p := (*[maxLen]uint8)(funcdata(f, _FUNCDATA_ArgInfo))
566 print1 := func(off, sz uint8) {
567 x := readUnaligned64(add(argp, uintptr(off)))
568 // mask out irrelavant bits
574 x = x << shift >> shift
581 printcomma := func() {
604 case _offsetTooLarge:
617 // reflectMethodValue is a partial duplicate of reflect.makeFuncImpl
618 // and reflect.methodValue.
619 type reflectMethodValue struct {
621 stack *bitvector // ptrmap for both args and results
622 argLen uintptr // just args
625 // getArgInfoFast returns the argument frame information for a call to f.
626 // It is short and inlineable. However, it does not handle all functions.
627 // If ok reports false, you must call getArgInfo instead.
628 // TODO(josharian): once we do mid-stack inlining,
629 // call getArgInfo directly from getArgInfoFast and stop returning an ok bool.
630 func getArgInfoFast(f funcInfo, needArgMap bool) (arglen uintptr, argmap *bitvector, ok bool) {
631 return uintptr(f.args), nil, !(needArgMap && f.args == _ArgsSizeUnknown)
634 // getArgInfo returns the argument frame information for a call to f
635 // with call frame frame.
637 // This is used for both actual calls with active stack frames and for
638 // deferred calls or goroutines that are not yet executing. If this is an actual
639 // call, ctxt must be nil (getArgInfo will retrieve what it needs from
640 // the active stack frame). If this is a deferred call or unstarted goroutine,
641 // ctxt must be the function object that was deferred or go'd.
642 func getArgInfo(frame *stkframe, f funcInfo, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) {
643 arglen = uintptr(f.args)
644 if needArgMap && f.args == _ArgsSizeUnknown {
645 // Extract argument bitmaps for reflect stubs from the calls they made to reflect.
647 case "reflect.makeFuncStub", "reflect.methodValueCall":
648 // These take a *reflect.methodValue as their
650 var mv *reflectMethodValue
653 // This is not an actual call, but a
654 // deferred call or an unstarted goroutine.
655 // The function value is itself the *reflect.methodValue.
656 mv = (*reflectMethodValue)(unsafe.Pointer(ctxt))
658 // This is a real call that took the
659 // *reflect.methodValue as its context
660 // register and immediately saved it
661 // to 0(SP). Get the methodValue from
663 arg0 := frame.sp + sys.MinFrameSize
664 mv = *(**reflectMethodValue)(unsafe.Pointer(arg0))
665 // Figure out whether the return values are valid.
666 // Reflect will update this value after it copies
667 // in the return values.
668 retValid = *(*bool)(unsafe.Pointer(arg0 + 4*sys.PtrSize))
670 if mv.fn != f.entry {
671 print("runtime: confused by ", funcname(f), "\n")
672 throw("reflect mismatch")
675 arglen = uintptr(bv.n * sys.PtrSize)
677 arglen = uintptr(mv.argLen) &^ (sys.PtrSize - 1)
685 // tracebackCgoContext handles tracing back a cgo context value, from
686 // the context argument to setCgoTraceback, for the gentraceback
687 // function. It returns the new value of n.
688 func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int {
689 var cgoPCs [32]uintptr
690 cgoContextPCs(ctxt, cgoPCs[:])
691 var arg cgoSymbolizerArg
692 anySymbolized := false
693 for _, pc := range cgoPCs {
694 if pc == 0 || n >= max {
698 (*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
701 if cgoSymbolizer == nil {
702 print("non-Go function at pc=", hex(pc), "\n")
704 c := printOneCgoTraceback(pc, max-n, &arg)
705 n += c - 1 // +1 a few lines down
713 callCgoSymbolizer(&arg)
718 func printcreatedby(gp *g) {
719 // Show what created goroutine, except main goroutine (goid 1).
722 if f.valid() && showframe(f, gp, false, funcID_normal, funcID_normal) && gp.goid != 1 {
723 printcreatedby1(f, pc)
727 func printcreatedby1(f funcInfo, pc uintptr) {
728 print("created by ", funcname(f), "\n")
729 tracepc := pc // back up to CALL instruction for funcline.
731 tracepc -= sys.PCQuantum
733 file, line := funcline(f, tracepc)
734 print("\t", file, ":", line)
736 print(" +", hex(pc-f.entry))
741 func traceback(pc, sp, lr uintptr, gp *g) {
742 traceback1(pc, sp, lr, gp, 0)
745 // tracebacktrap is like traceback but expects that the PC and SP were obtained
746 // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
747 // Because they are from a trap instead of from a saved pair,
748 // the initial PC must not be rewound to the previous instruction.
749 // (All the saved pairs record a PC that is a return address, so we
750 // rewind it into the CALL instruction.)
751 // If gp.m.libcall{g,pc,sp} information is available, it uses that information in preference to
752 // the pc/sp/lr passed in.
753 func tracebacktrap(pc, sp, lr uintptr, gp *g) {
754 if gp.m.libcallsp != 0 {
755 // We're in C code somewhere, traceback from the saved position.
756 traceback1(gp.m.libcallpc, gp.m.libcallsp, 0, gp.m.libcallg.ptr(), 0)
759 traceback1(pc, sp, lr, gp, _TraceTrap)
762 func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
763 // If the goroutine is in cgo, and we have a cgo traceback, print that.
764 if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
765 // Lock cgoCallers so that a signal handler won't
766 // change it, copy the array, reset it, unlock it.
767 // We are locked to the thread and are not running
768 // concurrently with a signal handler.
769 // We just have to stop a signal handler from interrupting
770 // in the middle of our copy.
771 atomic.Store(&gp.m.cgoCallersUse, 1)
772 cgoCallers := *gp.m.cgoCallers
773 gp.m.cgoCallers[0] = 0
774 atomic.Store(&gp.m.cgoCallersUse, 0)
776 printCgoTraceback(&cgoCallers)
780 if readgstatus(gp)&^_Gscan == _Gsyscall {
781 // Override registers if blocked in system call.
786 // Print traceback. By default, omits runtime frames.
787 // If that means we print nothing at all, repeat forcing all frames printed.
788 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
789 if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
790 n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
792 if n == _TracebackMaxFrames {
793 print("...additional frames elided...\n")
797 if gp.ancestors == nil {
800 for _, ancestor := range *gp.ancestors {
801 printAncestorTraceback(ancestor)
805 // printAncestorTraceback prints the traceback of the given ancestor.
806 // TODO: Unify this with gentraceback and CallersFrames.
807 func printAncestorTraceback(ancestor ancestorInfo) {
808 print("[originating from goroutine ", ancestor.goid, "]:\n")
809 for fidx, pc := range ancestor.pcs {
810 f := findfunc(pc) // f previously validated
811 if showfuncinfo(f, fidx == 0, funcID_normal, funcID_normal) {
812 printAncestorTracebackFuncInfo(f, pc)
815 if len(ancestor.pcs) == _TracebackMaxFrames {
816 print("...additional frames elided...\n")
818 // Show what created goroutine, except main goroutine (goid 1).
819 f := findfunc(ancestor.gopc)
820 if f.valid() && showfuncinfo(f, false, funcID_normal, funcID_normal) && ancestor.goid != 1 {
821 printcreatedby1(f, ancestor.gopc)
825 // printAncestorTraceback prints the given function info at a given pc
826 // within an ancestor traceback. The precision of this info is reduced
827 // due to only have access to the pcs at the time of the caller
828 // goroutine being created.
829 func printAncestorTracebackFuncInfo(f funcInfo, pc uintptr) {
831 if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
832 inltree := (*[1 << 20]inlinedCall)(inldata)
833 ix := pcdatavalue(f, _PCDATA_InlTreeIndex, pc, nil)
835 name = funcnameFromNameoff(f, inltree[ix].func_)
838 file, line := funcline(f, pc)
839 if name == "runtime.gopanic" {
842 print(name, "(...)\n")
843 print("\t", file, ":", line)
845 print(" +", hex(pc-f.entry))
850 func callers(skip int, pcbuf []uintptr) int {
856 n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
861 func gcallers(gp *g, skip int, pcbuf []uintptr) int {
862 return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
865 // showframe reports whether the frame with the given characteristics should
866 // be printed during a traceback.
867 func showframe(f funcInfo, gp *g, firstFrame bool, funcID, childID funcID) bool {
869 if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
872 return showfuncinfo(f, firstFrame, funcID, childID)
875 // showfuncinfo reports whether a function with the given characteristics should
876 // be printed during a traceback.
877 func showfuncinfo(f funcInfo, firstFrame bool, funcID, childID funcID) bool {
878 // Note that f may be a synthesized funcInfo for an inlined
879 // function, in which case only nameoff and funcID are set.
881 level, _, _ := gotraceback()
891 if funcID == funcID_wrapper && elideWrapperCalling(childID) {
897 // Special case: always show runtime.gopanic frame
898 // in the middle of a stack trace, so that we can
899 // see the boundary between ordinary code and
900 // panic-induced deferred code.
901 // See golang.org/issue/5832.
902 if name == "runtime.gopanic" && !firstFrame {
906 return bytealg.IndexByteString(name, '.') >= 0 && (!hasPrefix(name, "runtime.") || isExportedRuntime(name))
909 // isExportedRuntime reports whether name is an exported runtime function.
910 // It is only for runtime functions, so ASCII A-Z is fine.
911 func isExportedRuntime(name string) bool {
912 const n = len("runtime.")
913 return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
916 // elideWrapperCalling reports whether a wrapper function that called
917 // function id should be elided from stack traces.
918 func elideWrapperCalling(id funcID) bool {
919 // If the wrapper called a panic function instead of the
920 // wrapped function, we want to include it in stacks.
921 return !(id == funcID_gopanic || id == funcID_sigpanic || id == funcID_panicwrap)
924 var gStatusStrings = [...]string{
926 _Grunnable: "runnable",
927 _Grunning: "running",
928 _Gsyscall: "syscall",
929 _Gwaiting: "waiting",
931 _Gcopystack: "copystack",
932 _Gpreempted: "preempted",
935 func goroutineheader(gp *g) {
936 gpstatus := readgstatus(gp)
938 isScan := gpstatus&_Gscan != 0
939 gpstatus &^= _Gscan // drop the scan bit
941 // Basic string status
943 if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
944 status = gStatusStrings[gpstatus]
950 if gpstatus == _Gwaiting && gp.waitreason != waitReasonZero {
951 status = gp.waitreason.String()
954 // approx time the G is blocked, in minutes
956 if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
957 waitfor = (nanotime() - gp.waitsince) / 60e9
959 print("goroutine ", gp.goid, " [", status)
964 print(", ", waitfor, " minutes")
967 print(", locked to thread")
972 func tracebackothers(me *g) {
973 level, _, _ := gotraceback()
975 // Show the current goroutine first, if we haven't already.
976 curgp := getg().m.curg
977 if curgp != nil && curgp != me {
979 goroutineheader(curgp)
980 traceback(^uintptr(0), ^uintptr(0), 0, curgp)
983 // We can't call locking forEachG here because this may be during fatal
984 // throw/panic, where locking could be out-of-order or a direct
987 // Instead, use forEachGRace, which requires no locking. We don't lock
988 // against concurrent creation of new Gs, but even with allglock we may
989 // miss Gs created after this loop.
990 forEachGRace(func(gp *g) {
991 if gp == me || gp == curgp || readgstatus(gp) == _Gdead || isSystemGoroutine(gp, false) && level < 2 {
996 // Note: gp.m == g.m occurs when tracebackothers is
997 // called from a signal handler initiated during a
998 // systemstack call. The original G is still in the
999 // running state, and we want to print its stack.
1000 if gp.m != getg().m && readgstatus(gp)&^_Gscan == _Grunning {
1001 print("\tgoroutine running on other thread; stack unavailable\n")
1004 traceback(^uintptr(0), ^uintptr(0), 0, gp)
1009 // tracebackHexdump hexdumps part of stk around frame.sp and frame.fp
1010 // for debugging purposes. If the address bad is included in the
1011 // hexdumped range, it will mark it as well.
1012 func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) {
1013 const expand = 32 * sys.PtrSize
1014 const maxExpand = 256 * sys.PtrSize
1015 // Start around frame.sp.
1016 lo, hi := frame.sp, frame.sp
1017 // Expand to include frame.fp.
1018 if frame.fp != 0 && frame.fp < lo {
1021 if frame.fp != 0 && frame.fp > hi {
1024 // Expand a bit more.
1025 lo, hi = lo-expand, hi+expand
1026 // But don't go too far from frame.sp.
1027 if lo < frame.sp-maxExpand {
1028 lo = frame.sp - maxExpand
1030 if hi > frame.sp+maxExpand {
1031 hi = frame.sp + maxExpand
1033 // And don't go outside the stack bounds.
1041 // Print the hex dump.
1042 print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n")
1043 hexdumpWords(lo, hi, func(p uintptr) byte {
1056 // isSystemGoroutine reports whether the goroutine g must be omitted
1057 // in stack dumps and deadlock detector. This is any goroutine that
1058 // starts at a runtime.* entry point, except for runtime.main,
1059 // runtime.handleAsyncEvent (wasm only) and sometimes runtime.runfinq.
1061 // If fixed is true, any goroutine that can vary between user and
1062 // system (that is, the finalizer goroutine) is considered a user
1064 func isSystemGoroutine(gp *g, fixed bool) bool {
1065 // Keep this in sync with cmd/trace/trace.go:isSystemGoroutine.
1066 f := findfunc(gp.startpc)
1070 if f.funcID == funcID_runtime_main || f.funcID == funcID_handleAsyncEvent {
1073 if f.funcID == funcID_runfinq {
1074 // We include the finalizer goroutine if it's calling
1075 // back into user code.
1077 // This goroutine can vary. In fixed mode,
1078 // always consider it a user goroutine.
1083 return hasPrefix(funcname(f), "runtime.")
1086 // SetCgoTraceback records three C functions to use to gather
1087 // traceback information from C code and to convert that traceback
1088 // information into symbolic information. These are used when printing
1089 // stack traces for a program that uses cgo.
1091 // The traceback and context functions may be called from a signal
1092 // handler, and must therefore use only async-signal safe functions.
1093 // The symbolizer function may be called while the program is
1094 // crashing, and so must be cautious about using memory. None of the
1095 // functions may call back into Go.
1097 // The context function will be called with a single argument, a
1098 // pointer to a struct:
1104 // In C syntax, this struct will be
1107 // uintptr_t Context;
1110 // If the Context field is 0, the context function is being called to
1111 // record the current traceback context. It should record in the
1112 // Context field whatever information is needed about the current
1113 // point of execution to later produce a stack trace, probably the
1114 // stack pointer and PC. In this case the context function will be
1115 // called from C code.
1117 // If the Context field is not 0, then it is a value returned by a
1118 // previous call to the context function. This case is called when the
1119 // context is no longer needed; that is, when the Go code is returning
1120 // to its C code caller. This permits the context function to release
1121 // any associated resources.
1123 // While it would be correct for the context function to record a
1124 // complete a stack trace whenever it is called, and simply copy that
1125 // out in the traceback function, in a typical program the context
1126 // function will be called many times without ever recording a
1127 // traceback for that context. Recording a complete stack trace in a
1128 // call to the context function is likely to be inefficient.
1130 // The traceback function will be called with a single argument, a
1131 // pointer to a struct:
1135 // SigContext uintptr
1140 // In C syntax, this struct will be
1143 // uintptr_t Context;
1144 // uintptr_t SigContext;
1149 // The Context field will be zero to gather a traceback from the
1150 // current program execution point. In this case, the traceback
1151 // function will be called from C code.
1153 // Otherwise Context will be a value previously returned by a call to
1154 // the context function. The traceback function should gather a stack
1155 // trace from that saved point in the program execution. The traceback
1156 // function may be called from an execution thread other than the one
1157 // that recorded the context, but only when the context is known to be
1158 // valid and unchanging. The traceback function may also be called
1159 // deeper in the call stack on the same thread that recorded the
1160 // context. The traceback function may be called multiple times with
1161 // the same Context value; it will usually be appropriate to cache the
1162 // result, if possible, the first time this is called for a specific
1165 // If the traceback function is called from a signal handler on a Unix
1166 // system, SigContext will be the signal context argument passed to
1167 // the signal handler (a C ucontext_t* cast to uintptr_t). This may be
1168 // used to start tracing at the point where the signal occurred. If
1169 // the traceback function is not called from a signal handler,
1170 // SigContext will be zero.
1172 // Buf is where the traceback information should be stored. It should
1173 // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
1174 // the PC of that function's caller, and so on. Max is the maximum
1175 // number of entries to store. The function should store a zero to
1176 // indicate the top of the stack, or that the caller is on a different
1177 // stack, presumably a Go stack.
1179 // Unlike runtime.Callers, the PC values returned should, when passed
1180 // to the symbolizer function, return the file/line of the call
1181 // instruction. No additional subtraction is required or appropriate.
1183 // On all platforms, the traceback function is invoked when a call from
1184 // Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le,
1185 // and freebsd/amd64, the traceback function is also invoked when a
1186 // signal is received by a thread that is executing a cgo call. The
1187 // traceback function should not make assumptions about when it is
1188 // called, as future versions of Go may make additional calls.
1190 // The symbolizer function will be called with a single argument, a
1191 // pointer to a struct:
1194 // PC uintptr // program counter to fetch information for
1195 // File *byte // file name (NUL terminated)
1196 // Lineno uintptr // line number
1197 // Func *byte // function name (NUL terminated)
1198 // Entry uintptr // function entry point
1199 // More uintptr // set non-zero if more info for this PC
1200 // Data uintptr // unused by runtime, available for function
1203 // In C syntax, this struct will be
1208 // uintptr_t Lineno;
1215 // The PC field will be a value returned by a call to the traceback
1218 // The first time the function is called for a particular traceback,
1219 // all the fields except PC will be 0. The function should fill in the
1220 // other fields if possible, setting them to 0/nil if the information
1221 // is not available. The Data field may be used to store any useful
1222 // information across calls. The More field should be set to non-zero
1223 // if there is more information for this PC, zero otherwise. If More
1224 // is set non-zero, the function will be called again with the same
1225 // PC, and may return different information (this is intended for use
1226 // with inlined functions). If More is zero, the function will be
1227 // called with the next PC value in the traceback. When the traceback
1228 // is complete, the function will be called once more with PC set to
1229 // zero; this may be used to free any information. Each call will
1230 // leave the fields of the struct set to the same values they had upon
1231 // return, except for the PC field when the More field is zero. The
1232 // function must not keep a copy of the struct pointer between calls.
1234 // When calling SetCgoTraceback, the version argument is the version
1235 // number of the structs that the functions expect to receive.
1236 // Currently this must be zero.
1238 // The symbolizer function may be nil, in which case the results of
1239 // the traceback function will be displayed as numbers. If the
1240 // traceback function is nil, the symbolizer function will never be
1241 // called. The context function may be nil, in which case the
1242 // traceback function will only be called with the context field set
1243 // to zero. If the context function is nil, then calls from Go to C
1244 // to Go will not show a traceback for the C portion of the call stack.
1246 // SetCgoTraceback should be called only once, ideally from an init function.
1247 func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
1249 panic("unsupported version")
1252 if cgoTraceback != nil && cgoTraceback != traceback ||
1253 cgoContext != nil && cgoContext != context ||
1254 cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
1255 panic("call SetCgoTraceback only once")
1258 cgoTraceback = traceback
1259 cgoContext = context
1260 cgoSymbolizer = symbolizer
1262 // The context function is called when a C function calls a Go
1263 // function. As such it is only called by C code in runtime/cgo.
1264 if _cgo_set_context_function != nil {
1265 cgocall(_cgo_set_context_function, context)
1269 var cgoTraceback unsafe.Pointer
1270 var cgoContext unsafe.Pointer
1271 var cgoSymbolizer unsafe.Pointer
1273 // cgoTracebackArg is the type passed to cgoTraceback.
1274 type cgoTracebackArg struct {
1281 // cgoContextArg is the type passed to the context function.
1282 type cgoContextArg struct {
1286 // cgoSymbolizerArg is the type passed to cgoSymbolizer.
1287 type cgoSymbolizerArg struct {
1297 // cgoTraceback prints a traceback of callers.
1298 func printCgoTraceback(callers *cgoCallers) {
1299 if cgoSymbolizer == nil {
1300 for _, c := range callers {
1304 print("non-Go function at pc=", hex(c), "\n")
1309 var arg cgoSymbolizerArg
1310 for _, c := range callers {
1314 printOneCgoTraceback(c, 0x7fffffff, &arg)
1317 callCgoSymbolizer(&arg)
1320 // printOneCgoTraceback prints the traceback of a single cgo caller.
1321 // This can print more than one line because of inlining.
1322 // Returns the number of frames printed.
1323 func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
1327 callCgoSymbolizer(arg)
1328 if arg.funcName != nil {
1329 // Note that we don't print any argument
1330 // information here, not even parentheses.
1331 // The symbolizer must add that if appropriate.
1332 println(gostringnocopy(arg.funcName))
1334 println("non-Go function")
1337 if arg.file != nil {
1338 print(gostringnocopy(arg.file), ":", arg.lineno, " ")
1340 print("pc=", hex(pc), "\n")
1349 // callCgoSymbolizer calls the cgoSymbolizer function.
1350 func callCgoSymbolizer(arg *cgoSymbolizerArg) {
1352 if panicking > 0 || getg().m.curg != getg() {
1353 // We do not want to call into the scheduler when panicking
1354 // or when on the system stack.
1358 msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
1360 call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
1363 // cgoContextPCs gets the PC values from a cgo traceback.
1364 func cgoContextPCs(ctxt uintptr, buf []uintptr) {
1365 if cgoTraceback == nil {
1369 if panicking > 0 || getg().m.curg != getg() {
1370 // We do not want to call into the scheduler when panicking
1371 // or when on the system stack.
1374 arg := cgoTracebackArg{
1376 buf: (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
1377 max: uintptr(len(buf)),
1380 msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
1382 call(cgoTraceback, noescape(unsafe.Pointer(&arg)))