Source file src/runtime/traceback.go

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

View as plain text