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/bytealg"
     9  	"internal/goarch"
    10  	"runtime/internal/sys"
    11  	"unsafe"
    12  )
    13  
    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.
    21  
    22  const usesLR = sys.MinFrameSize > 0
    23  
    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.
    28  //
    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")
    35  	}
    36  
    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")
    53  	}
    54  	level, _, _ := gotraceback()
    55  
    56  	if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
    57  		if gp.syscallsp != 0 {
    58  			pc0 = gp.syscallpc
    59  			sp0 = gp.syscallsp
    60  			if usesLR {
    61  				lr0 = 0
    62  			}
    63  		} else {
    64  			pc0 = gp.sched.pc
    65  			sp0 = gp.sched.sp
    66  			if usesLR {
    67  				lr0 = gp.sched.lr
    68  			}
    69  		}
    70  	}
    71  
    72  	nprint := 0
    73  	var frame stkframe
    74  	frame.pc = pc0
    75  	frame.sp = sp0
    76  	if usesLR {
    77  		frame.lr = lr0
    78  	}
    79  	waspanic := false
    80  	cgoCtxt := gp.cgoCtxt
    81  	stack := gp.stack
    82  	printing := pcbuf == nil && callback == nil
    83  
    84  	// If the PC is zero, it's likely a nil function call.
    85  	// Start in the caller's frame.
    86  	if frame.pc == 0 {
    87  		if usesLR {
    88  			frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
    89  			frame.lr = 0
    90  		} else {
    91  			frame.pc = uintptr(*(*uintptr)(unsafe.Pointer(frame.sp)))
    92  			frame.sp += goarch.PtrSize
    93  		}
    94  	}
    95  
    96  	// runtime/internal/atomic functions call into kernel helpers on
    97  	// arm < 7. See runtime/internal/atomic/sys_linux_arm.s.
    98  	//
    99  	// Start in the caller's frame.
   100  	if GOARCH == "arm" && goarm < 7 && GOOS == "linux" && frame.pc&0xffff0000 == 0xffff0000 {
   101  		// Note that the calls are simple BL without pushing the return
   102  		// address, so we use LR directly.
   103  		//
   104  		// The kernel helpers are frameless leaf functions, so SP and
   105  		// LR are not touched.
   106  		frame.pc = frame.lr
   107  		frame.lr = 0
   108  	}
   109  
   110  	f := findfunc(frame.pc)
   111  	if !f.valid() {
   112  		if callback != nil || printing {
   113  			print("runtime: g ", gp.goid, ": unknown pc ", hex(frame.pc), "\n")
   114  			tracebackHexdump(stack, &frame, 0)
   115  		}
   116  		if callback != nil {
   117  			throw("unknown pc")
   118  		}
   119  		return 0
   120  	}
   121  	frame.fn = f
   122  
   123  	var cache pcvalueCache
   124  
   125  	lastFuncID := funcID_normal
   126  	n := 0
   127  	for n < max {
   128  		// Typically:
   129  		//	pc is the PC of the running function.
   130  		//	sp is the stack pointer at that program counter.
   131  		//	fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
   132  		//	stk is the stack containing sp.
   133  		//	The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
   134  		f = frame.fn
   135  		if f.pcsp == 0 {
   136  			// No frame information, must be external function, like race support.
   137  			// See golang.org/issue/13568.
   138  			break
   139  		}
   140  
   141  		// Compute function info flags.
   142  		flag := f.flag
   143  		if f.funcID == funcID_cgocallback {
   144  			// cgocallback does write SP to switch from the g0 to the curg stack,
   145  			// but it carefully arranges that during the transition BOTH stacks
   146  			// have cgocallback frame valid for unwinding through.
   147  			// So we don't need to exclude it with the other SP-writing functions.
   148  			flag &^= funcFlag_SPWRITE
   149  		}
   150  		if frame.pc == pc0 && frame.sp == sp0 && pc0 == gp.syscallpc && sp0 == gp.syscallsp {
   151  			// Some Syscall functions write to SP, but they do so only after
   152  			// saving the entry PC/SP using entersyscall.
   153  			// Since we are using the entry PC/SP, the later SP write doesn't matter.
   154  			flag &^= funcFlag_SPWRITE
   155  		}
   156  
   157  		// Found an actual function.
   158  		// Derive frame pointer and link register.
   159  		if frame.fp == 0 {
   160  			// Jump over system stack transitions. If we're on g0 and there's a user
   161  			// goroutine, try to jump. Otherwise this is a regular call.
   162  			// We also defensively check that this won't switch M's on us,
   163  			// which could happen at critical points in the scheduler.
   164  			// This ensures gp.m doesn't change from a stack jump.
   165  			if flags&_TraceJumpStack != 0 && gp == gp.m.g0 && gp.m.curg != nil && gp.m.curg.m == gp.m {
   166  				switch f.funcID {
   167  				case funcID_morestack:
   168  					// morestack does not return normally -- newstack()
   169  					// gogo's to curg.sched. Match that.
   170  					// This keeps morestack() from showing up in the backtrace,
   171  					// but that makes some sense since it'll never be returned
   172  					// to.
   173  					gp = gp.m.curg
   174  					frame.pc = gp.sched.pc
   175  					frame.fn = findfunc(frame.pc)
   176  					f = frame.fn
   177  					flag = f.flag
   178  					frame.lr = gp.sched.lr
   179  					frame.sp = gp.sched.sp
   180  					stack = gp.stack
   181  					cgoCtxt = gp.cgoCtxt
   182  				case funcID_systemstack:
   183  					// systemstack returns normally, so just follow the
   184  					// stack transition.
   185  					if usesLR && funcspdelta(f, frame.pc, &cache) == 0 {
   186  						// We're at the function prologue and the stack
   187  						// switch hasn't happened, or epilogue where we're
   188  						// about to return. Just unwind normally.
   189  						// Do this only on LR machines because on x86
   190  						// systemstack doesn't have an SP delta (the CALL
   191  						// instruction opens the frame), therefore no way
   192  						// to check.
   193  						flag &^= funcFlag_SPWRITE
   194  						break
   195  					}
   196  					gp = gp.m.curg
   197  					frame.sp = gp.sched.sp
   198  					stack = gp.stack
   199  					cgoCtxt = gp.cgoCtxt
   200  					flag &^= funcFlag_SPWRITE
   201  				}
   202  			}
   203  			frame.fp = frame.sp + uintptr(funcspdelta(f, frame.pc, &cache))
   204  			if !usesLR {
   205  				// On x86, call instruction pushes return PC before entering new function.
   206  				frame.fp += goarch.PtrSize
   207  			}
   208  		}
   209  		var flr funcInfo
   210  		if flag&funcFlag_TOPFRAME != 0 {
   211  			// This function marks the top of the stack. Stop the traceback.
   212  			frame.lr = 0
   213  			flr = funcInfo{}
   214  		} else if flag&funcFlag_SPWRITE != 0 && (callback == nil || n > 0) {
   215  			// The function we are in does a write to SP that we don't know
   216  			// how to encode in the spdelta table. Examples include context
   217  			// switch routines like runtime.gogo but also any code that switches
   218  			// to the g0 stack to run host C code. Since we can't reliably unwind
   219  			// the SP (we might not even be on the stack we think we are),
   220  			// we stop the traceback here.
   221  			// This only applies for profiling signals (callback == nil).
   222  			//
   223  			// For a GC stack traversal (callback != nil), we should only see
   224  			// a function when it has voluntarily preempted itself on entry
   225  			// during the stack growth check. In that case, the function has
   226  			// not yet had a chance to do any writes to SP and is safe to unwind.
   227  			// isAsyncSafePoint does not allow assembly functions to be async preempted,
   228  			// and preemptPark double-checks that SPWRITE functions are not async preempted.
   229  			// So for GC stack traversal we leave things alone (this if body does not execute for n == 0)
   230  			// at the bottom frame of the stack. But farther up the stack we'd better not
   231  			// find any.
   232  			if callback != nil {
   233  				println("traceback: unexpected SPWRITE function", funcname(f))
   234  				throw("traceback")
   235  			}
   236  			frame.lr = 0
   237  			flr = funcInfo{}
   238  		} else {
   239  			var lrPtr uintptr
   240  			if usesLR {
   241  				if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
   242  					lrPtr = frame.sp
   243  					frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
   244  				}
   245  			} else {
   246  				if frame.lr == 0 {
   247  					lrPtr = frame.fp - goarch.PtrSize
   248  					frame.lr = uintptr(*(*uintptr)(unsafe.Pointer(lrPtr)))
   249  				}
   250  			}
   251  			flr = findfunc(frame.lr)
   252  			if !flr.valid() {
   253  				// This happens if you get a profiling interrupt at just the wrong time.
   254  				// In that context it is okay to stop early.
   255  				// But if callback is set, we're doing a garbage collection and must
   256  				// get everything, so crash loudly.
   257  				doPrint := printing
   258  				if doPrint && gp.m.incgo && f.funcID == funcID_sigpanic {
   259  					// We can inject sigpanic
   260  					// calls directly into C code,
   261  					// in which case we'll see a C
   262  					// return PC. Don't complain.
   263  					doPrint = false
   264  				}
   265  				if callback != nil || doPrint {
   266  					print("runtime: g ", gp.goid, ": unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
   267  					tracebackHexdump(stack, &frame, lrPtr)
   268  				}
   269  				if callback != nil {
   270  					throw("unknown caller pc")
   271  				}
   272  			}
   273  		}
   274  
   275  		frame.varp = frame.fp
   276  		if !usesLR {
   277  			// On x86, call instruction pushes return PC before entering new function.
   278  			frame.varp -= goarch.PtrSize
   279  		}
   280  
   281  		// For architectures with frame pointers, if there's
   282  		// a frame, then there's a saved frame pointer here.
   283  		//
   284  		// NOTE: This code is not as general as it looks.
   285  		// On x86, the ABI is to save the frame pointer word at the
   286  		// top of the stack frame, so we have to back down over it.
   287  		// On arm64, the frame pointer should be at the bottom of
   288  		// the stack (with R29 (aka FP) = RSP), in which case we would
   289  		// not want to do the subtraction here. But we started out without
   290  		// any frame pointer, and when we wanted to add it, we didn't
   291  		// want to break all the assembly doing direct writes to 8(RSP)
   292  		// to set the first parameter to a called function.
   293  		// So we decided to write the FP link *below* the stack pointer
   294  		// (with R29 = RSP - 8 in Go functions).
   295  		// This is technically ABI-compatible but not standard.
   296  		// And it happens to end up mimicking the x86 layout.
   297  		// Other architectures may make different decisions.
   298  		if frame.varp > frame.sp && framepointer_enabled {
   299  			frame.varp -= goarch.PtrSize
   300  		}
   301  
   302  		frame.argp = frame.fp + sys.MinFrameSize
   303  
   304  		// Determine frame's 'continuation PC', where it can continue.
   305  		// Normally this is the return address on the stack, but if sigpanic
   306  		// is immediately below this function on the stack, then the frame
   307  		// stopped executing due to a trap, and frame.pc is probably not
   308  		// a safe point for looking up liveness information. In this panicking case,
   309  		// the function either doesn't return at all (if it has no defers or if the
   310  		// defers do not recover) or it returns from one of the calls to
   311  		// deferproc a second time (if the corresponding deferred func recovers).
   312  		// In the latter case, use a deferreturn call site as the continuation pc.
   313  		frame.continpc = frame.pc
   314  		if waspanic {
   315  			if frame.fn.deferreturn != 0 {
   316  				frame.continpc = frame.fn.entry() + uintptr(frame.fn.deferreturn) + 1
   317  				// Note: this may perhaps keep return variables alive longer than
   318  				// strictly necessary, as we are using "function has a defer statement"
   319  				// as a proxy for "function actually deferred something". It seems
   320  				// to be a minor drawback. (We used to actually look through the
   321  				// gp._defer for a defer corresponding to this function, but that
   322  				// is hard to do with defer records on the stack during a stack copy.)
   323  				// Note: the +1 is to offset the -1 that
   324  				// stack.go:getStackMap does to back up a return
   325  				// address make sure the pc is in the CALL instruction.
   326  			} else {
   327  				frame.continpc = 0
   328  			}
   329  		}
   330  
   331  		if callback != nil {
   332  			if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
   333  				return n
   334  			}
   335  		}
   336  
   337  		if pcbuf != nil {
   338  			pc := frame.pc
   339  			// backup to CALL instruction to read inlining info (same logic as below)
   340  			tracepc := pc
   341  			// Normally, pc is a return address. In that case, we want to look up
   342  			// file/line information using pc-1, because that is the pc of the
   343  			// call instruction (more precisely, the last byte of the call instruction).
   344  			// Callers expect the pc buffer to contain return addresses and do the
   345  			// same -1 themselves, so we keep pc unchanged.
   346  			// When the pc is from a signal (e.g. profiler or segv) then we want
   347  			// to look up file/line information using pc, and we store pc+1 in the
   348  			// pc buffer so callers can unconditionally subtract 1 before looking up.
   349  			// See issue 34123.
   350  			// The pc can be at function entry when the frame is initialized without
   351  			// actually running code, like runtime.mstart.
   352  			if (n == 0 && flags&_TraceTrap != 0) || waspanic || pc == f.entry() {
   353  				pc++
   354  			} else {
   355  				tracepc--
   356  			}
   357  
   358  			// If there is inlining info, record the inner frames.
   359  			if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
   360  				inltree := (*[1 << 20]inlinedCall)(inldata)
   361  				for {
   362  					ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, &cache)
   363  					if ix < 0 {
   364  						break
   365  					}
   366  					if inltree[ix].funcID == funcID_wrapper && elideWrapperCalling(lastFuncID) {
   367  						// ignore wrappers
   368  					} else if skip > 0 {
   369  						skip--
   370  					} else if n < max {
   371  						(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   372  						n++
   373  					}
   374  					lastFuncID = inltree[ix].funcID
   375  					// Back up to an instruction in the "caller".
   376  					tracepc = frame.fn.entry() + uintptr(inltree[ix].parentPc)
   377  					pc = tracepc + 1
   378  				}
   379  			}
   380  			// Record the main frame.
   381  			if f.funcID == funcID_wrapper && elideWrapperCalling(lastFuncID) {
   382  				// Ignore wrapper functions (except when they trigger panics).
   383  			} else if skip > 0 {
   384  				skip--
   385  			} else if n < max {
   386  				(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   387  				n++
   388  			}
   389  			lastFuncID = f.funcID
   390  			n-- // offset n++ below
   391  		}
   392  
   393  		if printing {
   394  			// assume skip=0 for printing.
   395  			//
   396  			// Never elide wrappers if we haven't printed
   397  			// any frames. And don't elide wrappers that
   398  			// called panic rather than the wrapped
   399  			// function. Otherwise, leave them out.
   400  
   401  			// backup to CALL instruction to read inlining info (same logic as below)
   402  			tracepc := frame.pc
   403  			if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry() && !waspanic {
   404  				tracepc--
   405  			}
   406  			// If there is inlining info, print the inner frames.
   407  			if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
   408  				inltree := (*[1 << 20]inlinedCall)(inldata)
   409  				var inlFunc _func
   410  				inlFuncInfo := funcInfo{&inlFunc, f.datap}
   411  				for {
   412  					ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil)
   413  					if ix < 0 {
   414  						break
   415  					}
   416  
   417  					// Create a fake _func for the
   418  					// inlined function.
   419  					inlFunc.nameOff = inltree[ix].nameOff
   420  					inlFunc.funcID = inltree[ix].funcID
   421  					inlFunc.startLine = inltree[ix].startLine
   422  
   423  					if (flags&_TraceRuntimeFrames) != 0 || showframe(inlFuncInfo, gp, nprint == 0, inlFuncInfo.funcID, lastFuncID) {
   424  						name := funcname(inlFuncInfo)
   425  						file, line := funcline(f, tracepc)
   426  						print(name, "(...)\n")
   427  						print("\t", file, ":", line, "\n")
   428  						nprint++
   429  					}
   430  					lastFuncID = inltree[ix].funcID
   431  					// Back up to an instruction in the "caller".
   432  					tracepc = frame.fn.entry() + uintptr(inltree[ix].parentPc)
   433  				}
   434  			}
   435  			if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, f.funcID, lastFuncID) {
   436  				// Print during crash.
   437  				//	main(0x1, 0x2, 0x3)
   438  				//		/home/rsc/go/src/runtime/x.go:23 +0xf
   439  				//
   440  				name := funcname(f)
   441  				file, line := funcline(f, tracepc)
   442  				if name == "runtime.gopanic" {
   443  					name = "panic"
   444  				}
   445  				print(name, "(")
   446  				argp := unsafe.Pointer(frame.argp)
   447  				printArgs(f, argp, tracepc)
   448  				print(")\n")
   449  				print("\t", file, ":", line)
   450  				if frame.pc > f.entry() {
   451  					print(" +", hex(frame.pc-f.entry()))
   452  				}
   453  				if gp.m != nil && gp.m.throwing >= throwTypeRuntime && gp == gp.m.curg || level >= 2 {
   454  					print(" fp=", hex(frame.fp), " sp=", hex(frame.sp), " pc=", hex(frame.pc))
   455  				}
   456  				print("\n")
   457  				nprint++
   458  			}
   459  			lastFuncID = f.funcID
   460  		}
   461  		n++
   462  
   463  		if f.funcID == funcID_cgocallback && len(cgoCtxt) > 0 {
   464  			ctxt := cgoCtxt[len(cgoCtxt)-1]
   465  			cgoCtxt = cgoCtxt[:len(cgoCtxt)-1]
   466  
   467  			// skip only applies to Go frames.
   468  			// callback != nil only used when we only care
   469  			// about Go frames.
   470  			if skip == 0 && callback == nil {
   471  				n = tracebackCgoContext(pcbuf, printing, ctxt, n, max)
   472  			}
   473  		}
   474  
   475  		waspanic = f.funcID == funcID_sigpanic
   476  		injectedCall := waspanic || f.funcID == funcID_asyncPreempt || f.funcID == funcID_debugCallV2
   477  
   478  		// Do not unwind past the bottom of the stack.
   479  		if !flr.valid() {
   480  			break
   481  		}
   482  
   483  		if frame.pc == frame.lr && frame.sp == frame.fp {
   484  			// If the next frame is identical to the current frame, we cannot make progress.
   485  			print("runtime: traceback stuck. pc=", hex(frame.pc), " sp=", hex(frame.sp), "\n")
   486  			tracebackHexdump(stack, &frame, frame.sp)
   487  			throw("traceback stuck")
   488  		}
   489  
   490  		// Unwind to next frame.
   491  		frame.fn = flr
   492  		frame.pc = frame.lr
   493  		frame.lr = 0
   494  		frame.sp = frame.fp
   495  		frame.fp = 0
   496  
   497  		// On link register architectures, sighandler saves the LR on stack
   498  		// before faking a call.
   499  		if usesLR && injectedCall {
   500  			x := *(*uintptr)(unsafe.Pointer(frame.sp))
   501  			frame.sp += alignUp(sys.MinFrameSize, sys.StackAlign)
   502  			f = findfunc(frame.pc)
   503  			frame.fn = f
   504  			if !f.valid() {
   505  				frame.pc = x
   506  			} else if funcspdelta(f, frame.pc, &cache) == 0 {
   507  				frame.lr = x
   508  			}
   509  		}
   510  	}
   511  
   512  	if printing {
   513  		n = nprint
   514  	}
   515  
   516  	// Note that panic != nil is okay here: there can be leftover panics,
   517  	// because the defers on the panic stack do not nest in frame order as
   518  	// they do on the defer stack. If you have:
   519  	//
   520  	//	frame 1 defers d1
   521  	//	frame 2 defers d2
   522  	//	frame 3 defers d3
   523  	//	frame 4 panics
   524  	//	frame 4's panic starts running defers
   525  	//	frame 5, running d3, defers d4
   526  	//	frame 5 panics
   527  	//	frame 5's panic starts running defers
   528  	//	frame 6, running d4, garbage collects
   529  	//	frame 6, running d2, garbage collects
   530  	//
   531  	// During the execution of d4, the panic stack is d4 -> d3, which
   532  	// is nested properly, and we'll treat frame 3 as resumable, because we
   533  	// can find d3. (And in fact frame 3 is resumable. If d4 recovers
   534  	// and frame 5 continues running, d3, d3 can recover and we'll
   535  	// resume execution in (returning from) frame 3.)
   536  	//
   537  	// During the execution of d2, however, the panic stack is d2 -> d3,
   538  	// which is inverted. The scan will match d2 to frame 2 but having
   539  	// d2 on the stack until then means it will not match d3 to frame 3.
   540  	// This is okay: if we're running d2, then all the defers after d2 have
   541  	// completed and their corresponding frames are dead. Not finding d3
   542  	// for frame 3 means we'll set frame 3's continpc == 0, which is correct
   543  	// (frame 3 is dead). At the end of the walk the panic stack can thus
   544  	// contain defers (d3 in this case) for dead frames. The inversion here
   545  	// always indicates a dead frame, and the effect of the inversion on the
   546  	// scan is to hide those dead frames, so the scan is still okay:
   547  	// what's left on the panic stack are exactly (and only) the dead frames.
   548  	//
   549  	// We require callback != nil here because only when callback != nil
   550  	// do we know that gentraceback is being called in a "must be correct"
   551  	// context as opposed to a "best effort" context. The tracebacks with
   552  	// callbacks only happen when everything is stopped nicely.
   553  	// At other times, such as when gathering a stack for a profiling signal
   554  	// or when printing a traceback during a crash, everything may not be
   555  	// stopped nicely, and the stack walk may not be able to complete.
   556  	if callback != nil && n < max && frame.sp != gp.stktopsp {
   557  		print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n")
   558  		print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n")
   559  		throw("traceback did not unwind completely")
   560  	}
   561  
   562  	return n
   563  }
   564  
   565  // printArgs prints function arguments in traceback.
   566  func printArgs(f funcInfo, argp unsafe.Pointer, pc uintptr) {
   567  	// The "instruction" of argument printing is encoded in _FUNCDATA_ArgInfo.
   568  	// See cmd/compile/internal/ssagen.emitArgInfo for the description of the
   569  	// encoding.
   570  	// These constants need to be in sync with the compiler.
   571  	const (
   572  		_endSeq         = 0xff
   573  		_startAgg       = 0xfe
   574  		_endAgg         = 0xfd
   575  		_dotdotdot      = 0xfc
   576  		_offsetTooLarge = 0xfb
   577  	)
   578  
   579  	const (
   580  		limit    = 10                       // print no more than 10 args/components
   581  		maxDepth = 5                        // no more than 5 layers of nesting
   582  		maxLen   = (maxDepth*3+2)*limit + 1 // max length of _FUNCDATA_ArgInfo (see the compiler side for reasoning)
   583  	)
   584  
   585  	p := (*[maxLen]uint8)(funcdata(f, _FUNCDATA_ArgInfo))
   586  	if p == nil {
   587  		return
   588  	}
   589  
   590  	liveInfo := funcdata(f, _FUNCDATA_ArgLiveInfo)
   591  	liveIdx := pcdatavalue(f, _PCDATA_ArgLiveIndex, pc, nil)
   592  	startOffset := uint8(0xff) // smallest offset that needs liveness info (slots with a lower offset is always live)
   593  	if liveInfo != nil {
   594  		startOffset = *(*uint8)(liveInfo)
   595  	}
   596  
   597  	isLive := func(off, slotIdx uint8) bool {
   598  		if liveInfo == nil || liveIdx <= 0 {
   599  			return true // no liveness info, always live
   600  		}
   601  		if off < startOffset {
   602  			return true
   603  		}
   604  		bits := *(*uint8)(add(liveInfo, uintptr(liveIdx)+uintptr(slotIdx/8)))
   605  		return bits&(1<<(slotIdx%8)) != 0
   606  	}
   607  
   608  	print1 := func(off, sz, slotIdx uint8) {
   609  		x := readUnaligned64(add(argp, uintptr(off)))
   610  		// mask out irrelevant bits
   611  		if sz < 8 {
   612  			shift := 64 - sz*8
   613  			if goarch.BigEndian {
   614  				x = x >> shift
   615  			} else {
   616  				x = x << shift >> shift
   617  			}
   618  		}
   619  		print(hex(x))
   620  		if !isLive(off, slotIdx) {
   621  			print("?")
   622  		}
   623  	}
   624  
   625  	start := true
   626  	printcomma := func() {
   627  		if !start {
   628  			print(", ")
   629  		}
   630  	}
   631  	pi := 0
   632  	slotIdx := uint8(0) // register arg spill slot index
   633  printloop:
   634  	for {
   635  		o := p[pi]
   636  		pi++
   637  		switch o {
   638  		case _endSeq:
   639  			break printloop
   640  		case _startAgg:
   641  			printcomma()
   642  			print("{")
   643  			start = true
   644  			continue
   645  		case _endAgg:
   646  			print("}")
   647  		case _dotdotdot:
   648  			printcomma()
   649  			print("...")
   650  		case _offsetTooLarge:
   651  			printcomma()
   652  			print("_")
   653  		default:
   654  			printcomma()
   655  			sz := p[pi]
   656  			pi++
   657  			print1(o, sz, slotIdx)
   658  			if o >= startOffset {
   659  				slotIdx++
   660  			}
   661  		}
   662  		start = false
   663  	}
   664  }
   665  
   666  // tracebackCgoContext handles tracing back a cgo context value, from
   667  // the context argument to setCgoTraceback, for the gentraceback
   668  // function. It returns the new value of n.
   669  func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int {
   670  	var cgoPCs [32]uintptr
   671  	cgoContextPCs(ctxt, cgoPCs[:])
   672  	var arg cgoSymbolizerArg
   673  	anySymbolized := false
   674  	for _, pc := range cgoPCs {
   675  		if pc == 0 || n >= max {
   676  			break
   677  		}
   678  		if pcbuf != nil {
   679  			(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   680  		}
   681  		if printing {
   682  			if cgoSymbolizer == nil {
   683  				print("non-Go function at pc=", hex(pc), "\n")
   684  			} else {
   685  				c := printOneCgoTraceback(pc, max-n, &arg)
   686  				n += c - 1 // +1 a few lines down
   687  				anySymbolized = true
   688  			}
   689  		}
   690  		n++
   691  	}
   692  	if anySymbolized {
   693  		arg.pc = 0
   694  		callCgoSymbolizer(&arg)
   695  	}
   696  	return n
   697  }
   698  
   699  func printcreatedby(gp *g) {
   700  	// Show what created goroutine, except main goroutine (goid 1).
   701  	pc := gp.gopc
   702  	f := findfunc(pc)
   703  	if f.valid() && showframe(f, gp, false, funcID_normal, funcID_normal) && gp.goid != 1 {
   704  		printcreatedby1(f, pc)
   705  	}
   706  }
   707  
   708  func printcreatedby1(f funcInfo, pc uintptr) {
   709  	print("created by ", funcname(f), "\n")
   710  	tracepc := pc // back up to CALL instruction for funcline.
   711  	if pc > f.entry() {
   712  		tracepc -= sys.PCQuantum
   713  	}
   714  	file, line := funcline(f, tracepc)
   715  	print("\t", file, ":", line)
   716  	if pc > f.entry() {
   717  		print(" +", hex(pc-f.entry()))
   718  	}
   719  	print("\n")
   720  }
   721  
   722  func traceback(pc, sp, lr uintptr, gp *g) {
   723  	traceback1(pc, sp, lr, gp, 0)
   724  }
   725  
   726  // tracebacktrap is like traceback but expects that the PC and SP were obtained
   727  // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
   728  // Because they are from a trap instead of from a saved pair,
   729  // the initial PC must not be rewound to the previous instruction.
   730  // (All the saved pairs record a PC that is a return address, so we
   731  // rewind it into the CALL instruction.)
   732  // If gp.m.libcall{g,pc,sp} information is available, it uses that information in preference to
   733  // the pc/sp/lr passed in.
   734  func tracebacktrap(pc, sp, lr uintptr, gp *g) {
   735  	if gp.m.libcallsp != 0 {
   736  		// We're in C code somewhere, traceback from the saved position.
   737  		traceback1(gp.m.libcallpc, gp.m.libcallsp, 0, gp.m.libcallg.ptr(), 0)
   738  		return
   739  	}
   740  	traceback1(pc, sp, lr, gp, _TraceTrap)
   741  }
   742  
   743  func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
   744  	// If the goroutine is in cgo, and we have a cgo traceback, print that.
   745  	if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
   746  		// Lock cgoCallers so that a signal handler won't
   747  		// change it, copy the array, reset it, unlock it.
   748  		// We are locked to the thread and are not running
   749  		// concurrently with a signal handler.
   750  		// We just have to stop a signal handler from interrupting
   751  		// in the middle of our copy.
   752  		gp.m.cgoCallersUse.Store(1)
   753  		cgoCallers := *gp.m.cgoCallers
   754  		gp.m.cgoCallers[0] = 0
   755  		gp.m.cgoCallersUse.Store(0)
   756  
   757  		printCgoTraceback(&cgoCallers)
   758  	}
   759  
   760  	if readgstatus(gp)&^_Gscan == _Gsyscall {
   761  		// Override registers if blocked in system call.
   762  		pc = gp.syscallpc
   763  		sp = gp.syscallsp
   764  		flags &^= _TraceTrap
   765  	}
   766  	if gp.m != nil && gp.m.vdsoSP != 0 {
   767  		// Override registers if running in VDSO. This comes after the
   768  		// _Gsyscall check to cover VDSO calls after entersyscall.
   769  		pc = gp.m.vdsoPC
   770  		sp = gp.m.vdsoSP
   771  		flags &^= _TraceTrap
   772  	}
   773  
   774  	// Print traceback. By default, omits runtime frames.
   775  	// If that means we print nothing at all, repeat forcing all frames printed.
   776  	n := gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
   777  	if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
   778  		n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
   779  	}
   780  	if n == _TracebackMaxFrames {
   781  		print("...additional frames elided...\n")
   782  	}
   783  	printcreatedby(gp)
   784  
   785  	if gp.ancestors == nil {
   786  		return
   787  	}
   788  	for _, ancestor := range *gp.ancestors {
   789  		printAncestorTraceback(ancestor)
   790  	}
   791  }
   792  
   793  // printAncestorTraceback prints the traceback of the given ancestor.
   794  // TODO: Unify this with gentraceback and CallersFrames.
   795  func printAncestorTraceback(ancestor ancestorInfo) {
   796  	print("[originating from goroutine ", ancestor.goid, "]:\n")
   797  	for fidx, pc := range ancestor.pcs {
   798  		f := findfunc(pc) // f previously validated
   799  		if showfuncinfo(f, fidx == 0, funcID_normal, funcID_normal) {
   800  			printAncestorTracebackFuncInfo(f, pc)
   801  		}
   802  	}
   803  	if len(ancestor.pcs) == _TracebackMaxFrames {
   804  		print("...additional frames elided...\n")
   805  	}
   806  	// Show what created goroutine, except main goroutine (goid 1).
   807  	f := findfunc(ancestor.gopc)
   808  	if f.valid() && showfuncinfo(f, false, funcID_normal, funcID_normal) && ancestor.goid != 1 {
   809  		printcreatedby1(f, ancestor.gopc)
   810  	}
   811  }
   812  
   813  // printAncestorTracebackFuncInfo prints the given function info at a given pc
   814  // within an ancestor traceback. The precision of this info is reduced
   815  // due to only have access to the pcs at the time of the caller
   816  // goroutine being created.
   817  func printAncestorTracebackFuncInfo(f funcInfo, pc uintptr) {
   818  	name := funcname(f)
   819  	if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
   820  		inltree := (*[1 << 20]inlinedCall)(inldata)
   821  		ix := pcdatavalue(f, _PCDATA_InlTreeIndex, pc, nil)
   822  		if ix >= 0 {
   823  			name = funcnameFromNameOff(f, inltree[ix].nameOff)
   824  		}
   825  	}
   826  	file, line := funcline(f, pc)
   827  	if name == "runtime.gopanic" {
   828  		name = "panic"
   829  	}
   830  	print(name, "(...)\n")
   831  	print("\t", file, ":", line)
   832  	if pc > f.entry() {
   833  		print(" +", hex(pc-f.entry()))
   834  	}
   835  	print("\n")
   836  }
   837  
   838  func callers(skip int, pcbuf []uintptr) int {
   839  	sp := getcallersp()
   840  	pc := getcallerpc()
   841  	gp := getg()
   842  	var n int
   843  	systemstack(func() {
   844  		n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   845  	})
   846  	return n
   847  }
   848  
   849  func gcallers(gp *g, skip int, pcbuf []uintptr) int {
   850  	return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   851  }
   852  
   853  // showframe reports whether the frame with the given characteristics should
   854  // be printed during a traceback.
   855  func showframe(f funcInfo, gp *g, firstFrame bool, funcID, childID funcID) bool {
   856  	mp := getg().m
   857  	if mp.throwing >= throwTypeRuntime && gp != nil && (gp == mp.curg || gp == mp.caughtsig.ptr()) {
   858  		return true
   859  	}
   860  	return showfuncinfo(f, firstFrame, funcID, childID)
   861  }
   862  
   863  // showfuncinfo reports whether a function with the given characteristics should
   864  // be printed during a traceback.
   865  func showfuncinfo(f funcInfo, firstFrame bool, funcID, childID funcID) bool {
   866  	// Note that f may be a synthesized funcInfo for an inlined
   867  	// function, in which case only nameOff and funcID are set.
   868  
   869  	level, _, _ := gotraceback()
   870  	if level > 1 {
   871  		// Show all frames.
   872  		return true
   873  	}
   874  
   875  	if !f.valid() {
   876  		return false
   877  	}
   878  
   879  	if funcID == funcID_wrapper && elideWrapperCalling(childID) {
   880  		return false
   881  	}
   882  
   883  	name := funcname(f)
   884  
   885  	// Special case: always show runtime.gopanic frame
   886  	// in the middle of a stack trace, so that we can
   887  	// see the boundary between ordinary code and
   888  	// panic-induced deferred code.
   889  	// See golang.org/issue/5832.
   890  	if name == "runtime.gopanic" && !firstFrame {
   891  		return true
   892  	}
   893  
   894  	return bytealg.IndexByteString(name, '.') >= 0 && (!hasPrefix(name, "runtime.") || isExportedRuntime(name))
   895  }
   896  
   897  // isExportedRuntime reports whether name is an exported runtime function.
   898  // It is only for runtime functions, so ASCII A-Z is fine.
   899  func isExportedRuntime(name string) bool {
   900  	const n = len("runtime.")
   901  	return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
   902  }
   903  
   904  // elideWrapperCalling reports whether a wrapper function that called
   905  // function id should be elided from stack traces.
   906  func elideWrapperCalling(id funcID) bool {
   907  	// If the wrapper called a panic function instead of the
   908  	// wrapped function, we want to include it in stacks.
   909  	return !(id == funcID_gopanic || id == funcID_sigpanic || id == funcID_panicwrap)
   910  }
   911  
   912  var gStatusStrings = [...]string{
   913  	_Gidle:      "idle",
   914  	_Grunnable:  "runnable",
   915  	_Grunning:   "running",
   916  	_Gsyscall:   "syscall",
   917  	_Gwaiting:   "waiting",
   918  	_Gdead:      "dead",
   919  	_Gcopystack: "copystack",
   920  	_Gpreempted: "preempted",
   921  }
   922  
   923  func goroutineheader(gp *g) {
   924  	gpstatus := readgstatus(gp)
   925  
   926  	isScan := gpstatus&_Gscan != 0
   927  	gpstatus &^= _Gscan // drop the scan bit
   928  
   929  	// Basic string status
   930  	var status string
   931  	if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
   932  		status = gStatusStrings[gpstatus]
   933  	} else {
   934  		status = "???"
   935  	}
   936  
   937  	// Override.
   938  	if gpstatus == _Gwaiting && gp.waitreason != waitReasonZero {
   939  		status = gp.waitreason.String()
   940  	}
   941  
   942  	// approx time the G is blocked, in minutes
   943  	var waitfor int64
   944  	if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
   945  		waitfor = (nanotime() - gp.waitsince) / 60e9
   946  	}
   947  	print("goroutine ", gp.goid, " [", status)
   948  	if isScan {
   949  		print(" (scan)")
   950  	}
   951  	if waitfor >= 1 {
   952  		print(", ", waitfor, " minutes")
   953  	}
   954  	if gp.lockedm != 0 {
   955  		print(", locked to thread")
   956  	}
   957  	print("]:\n")
   958  }
   959  
   960  func tracebackothers(me *g) {
   961  	level, _, _ := gotraceback()
   962  
   963  	// Show the current goroutine first, if we haven't already.
   964  	curgp := getg().m.curg
   965  	if curgp != nil && curgp != me {
   966  		print("\n")
   967  		goroutineheader(curgp)
   968  		traceback(^uintptr(0), ^uintptr(0), 0, curgp)
   969  	}
   970  
   971  	// We can't call locking forEachG here because this may be during fatal
   972  	// throw/panic, where locking could be out-of-order or a direct
   973  	// deadlock.
   974  	//
   975  	// Instead, use forEachGRace, which requires no locking. We don't lock
   976  	// against concurrent creation of new Gs, but even with allglock we may
   977  	// miss Gs created after this loop.
   978  	forEachGRace(func(gp *g) {
   979  		if gp == me || gp == curgp || readgstatus(gp) == _Gdead || isSystemGoroutine(gp, false) && level < 2 {
   980  			return
   981  		}
   982  		print("\n")
   983  		goroutineheader(gp)
   984  		// Note: gp.m == getg().m occurs when tracebackothers is called
   985  		// from a signal handler initiated during a systemstack call.
   986  		// The original G is still in the running state, and we want to
   987  		// print its stack.
   988  		if gp.m != getg().m && readgstatus(gp)&^_Gscan == _Grunning {
   989  			print("\tgoroutine running on other thread; stack unavailable\n")
   990  			printcreatedby(gp)
   991  		} else {
   992  			traceback(^uintptr(0), ^uintptr(0), 0, gp)
   993  		}
   994  	})
   995  }
   996  
   997  // tracebackHexdump hexdumps part of stk around frame.sp and frame.fp
   998  // for debugging purposes. If the address bad is included in the
   999  // hexdumped range, it will mark it as well.
  1000  func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) {
  1001  	const expand = 32 * goarch.PtrSize
  1002  	const maxExpand = 256 * goarch.PtrSize
  1003  	// Start around frame.sp.
  1004  	lo, hi := frame.sp, frame.sp
  1005  	// Expand to include frame.fp.
  1006  	if frame.fp != 0 && frame.fp < lo {
  1007  		lo = frame.fp
  1008  	}
  1009  	if frame.fp != 0 && frame.fp > hi {
  1010  		hi = frame.fp
  1011  	}
  1012  	// Expand a bit more.
  1013  	lo, hi = lo-expand, hi+expand
  1014  	// But don't go too far from frame.sp.
  1015  	if lo < frame.sp-maxExpand {
  1016  		lo = frame.sp - maxExpand
  1017  	}
  1018  	if hi > frame.sp+maxExpand {
  1019  		hi = frame.sp + maxExpand
  1020  	}
  1021  	// And don't go outside the stack bounds.
  1022  	if lo < stk.lo {
  1023  		lo = stk.lo
  1024  	}
  1025  	if hi > stk.hi {
  1026  		hi = stk.hi
  1027  	}
  1028  
  1029  	// Print the hex dump.
  1030  	print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n")
  1031  	hexdumpWords(lo, hi, func(p uintptr) byte {
  1032  		switch p {
  1033  		case frame.fp:
  1034  			return '>'
  1035  		case frame.sp:
  1036  			return '<'
  1037  		case bad:
  1038  			return '!'
  1039  		}
  1040  		return 0
  1041  	})
  1042  }
  1043  
  1044  // isSystemGoroutine reports whether the goroutine g must be omitted
  1045  // in stack dumps and deadlock detector. This is any goroutine that
  1046  // starts at a runtime.* entry point, except for runtime.main,
  1047  // runtime.handleAsyncEvent (wasm only) and sometimes runtime.runfinq.
  1048  //
  1049  // If fixed is true, any goroutine that can vary between user and
  1050  // system (that is, the finalizer goroutine) is considered a user
  1051  // goroutine.
  1052  func isSystemGoroutine(gp *g, fixed bool) bool {
  1053  	// Keep this in sync with internal/trace.IsSystemGoroutine.
  1054  	f := findfunc(gp.startpc)
  1055  	if !f.valid() {
  1056  		return false
  1057  	}
  1058  	if f.funcID == funcID_runtime_main || f.funcID == funcID_handleAsyncEvent {
  1059  		return false
  1060  	}
  1061  	if f.funcID == funcID_runfinq {
  1062  		// We include the finalizer goroutine if it's calling
  1063  		// back into user code.
  1064  		if fixed {
  1065  			// This goroutine can vary. In fixed mode,
  1066  			// always consider it a user goroutine.
  1067  			return false
  1068  		}
  1069  		return fingStatus.Load()&fingRunningFinalizer == 0
  1070  	}
  1071  	return hasPrefix(funcname(f), "runtime.")
  1072  }
  1073  
  1074  // SetCgoTraceback records three C functions to use to gather
  1075  // traceback information from C code and to convert that traceback
  1076  // information into symbolic information. These are used when printing
  1077  // stack traces for a program that uses cgo.
  1078  //
  1079  // The traceback and context functions may be called from a signal
  1080  // handler, and must therefore use only async-signal safe functions.
  1081  // The symbolizer function may be called while the program is
  1082  // crashing, and so must be cautious about using memory.  None of the
  1083  // functions may call back into Go.
  1084  //
  1085  // The context function will be called with a single argument, a
  1086  // pointer to a struct:
  1087  //
  1088  //	struct {
  1089  //		Context uintptr
  1090  //	}
  1091  //
  1092  // In C syntax, this struct will be
  1093  //
  1094  //	struct {
  1095  //		uintptr_t Context;
  1096  //	};
  1097  //
  1098  // If the Context field is 0, the context function is being called to
  1099  // record the current traceback context. It should record in the
  1100  // Context field whatever information is needed about the current
  1101  // point of execution to later produce a stack trace, probably the
  1102  // stack pointer and PC. In this case the context function will be
  1103  // called from C code.
  1104  //
  1105  // If the Context field is not 0, then it is a value returned by a
  1106  // previous call to the context function. This case is called when the
  1107  // context is no longer needed; that is, when the Go code is returning
  1108  // to its C code caller. This permits the context function to release
  1109  // any associated resources.
  1110  //
  1111  // While it would be correct for the context function to record a
  1112  // complete a stack trace whenever it is called, and simply copy that
  1113  // out in the traceback function, in a typical program the context
  1114  // function will be called many times without ever recording a
  1115  // traceback for that context. Recording a complete stack trace in a
  1116  // call to the context function is likely to be inefficient.
  1117  //
  1118  // The traceback function will be called with a single argument, a
  1119  // pointer to a struct:
  1120  //
  1121  //	struct {
  1122  //		Context    uintptr
  1123  //		SigContext uintptr
  1124  //		Buf        *uintptr
  1125  //		Max        uintptr
  1126  //	}
  1127  //
  1128  // In C syntax, this struct will be
  1129  //
  1130  //	struct {
  1131  //		uintptr_t  Context;
  1132  //		uintptr_t  SigContext;
  1133  //		uintptr_t* Buf;
  1134  //		uintptr_t  Max;
  1135  //	};
  1136  //
  1137  // The Context field will be zero to gather a traceback from the
  1138  // current program execution point. In this case, the traceback
  1139  // function will be called from C code.
  1140  //
  1141  // Otherwise Context will be a value previously returned by a call to
  1142  // the context function. The traceback function should gather a stack
  1143  // trace from that saved point in the program execution. The traceback
  1144  // function may be called from an execution thread other than the one
  1145  // that recorded the context, but only when the context is known to be
  1146  // valid and unchanging. The traceback function may also be called
  1147  // deeper in the call stack on the same thread that recorded the
  1148  // context. The traceback function may be called multiple times with
  1149  // the same Context value; it will usually be appropriate to cache the
  1150  // result, if possible, the first time this is called for a specific
  1151  // context value.
  1152  //
  1153  // If the traceback function is called from a signal handler on a Unix
  1154  // system, SigContext will be the signal context argument passed to
  1155  // the signal handler (a C ucontext_t* cast to uintptr_t). This may be
  1156  // used to start tracing at the point where the signal occurred. If
  1157  // the traceback function is not called from a signal handler,
  1158  // SigContext will be zero.
  1159  //
  1160  // Buf is where the traceback information should be stored. It should
  1161  // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
  1162  // the PC of that function's caller, and so on.  Max is the maximum
  1163  // number of entries to store.  The function should store a zero to
  1164  // indicate the top of the stack, or that the caller is on a different
  1165  // stack, presumably a Go stack.
  1166  //
  1167  // Unlike runtime.Callers, the PC values returned should, when passed
  1168  // to the symbolizer function, return the file/line of the call
  1169  // instruction.  No additional subtraction is required or appropriate.
  1170  //
  1171  // On all platforms, the traceback function is invoked when a call from
  1172  // Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le,
  1173  // linux/arm64, and freebsd/amd64, the traceback function is also invoked
  1174  // when a signal is received by a thread that is executing a cgo call.
  1175  // The traceback function should not make assumptions about when it is
  1176  // called, as future versions of Go may make additional calls.
  1177  //
  1178  // The symbolizer function will be called with a single argument, a
  1179  // pointer to a struct:
  1180  //
  1181  //	struct {
  1182  //		PC      uintptr // program counter to fetch information for
  1183  //		File    *byte   // file name (NUL terminated)
  1184  //		Lineno  uintptr // line number
  1185  //		Func    *byte   // function name (NUL terminated)
  1186  //		Entry   uintptr // function entry point
  1187  //		More    uintptr // set non-zero if more info for this PC
  1188  //		Data    uintptr // unused by runtime, available for function
  1189  //	}
  1190  //
  1191  // In C syntax, this struct will be
  1192  //
  1193  //	struct {
  1194  //		uintptr_t PC;
  1195  //		char*     File;
  1196  //		uintptr_t Lineno;
  1197  //		char*     Func;
  1198  //		uintptr_t Entry;
  1199  //		uintptr_t More;
  1200  //		uintptr_t Data;
  1201  //	};
  1202  //
  1203  // The PC field will be a value returned by a call to the traceback
  1204  // function.
  1205  //
  1206  // The first time the function is called for a particular traceback,
  1207  // all the fields except PC will be 0. The function should fill in the
  1208  // other fields if possible, setting them to 0/nil if the information
  1209  // is not available. The Data field may be used to store any useful
  1210  // information across calls. The More field should be set to non-zero
  1211  // if there is more information for this PC, zero otherwise. If More
  1212  // is set non-zero, the function will be called again with the same
  1213  // PC, and may return different information (this is intended for use
  1214  // with inlined functions). If More is zero, the function will be
  1215  // called with the next PC value in the traceback. When the traceback
  1216  // is complete, the function will be called once more with PC set to
  1217  // zero; this may be used to free any information. Each call will
  1218  // leave the fields of the struct set to the same values they had upon
  1219  // return, except for the PC field when the More field is zero. The
  1220  // function must not keep a copy of the struct pointer between calls.
  1221  //
  1222  // When calling SetCgoTraceback, the version argument is the version
  1223  // number of the structs that the functions expect to receive.
  1224  // Currently this must be zero.
  1225  //
  1226  // The symbolizer function may be nil, in which case the results of
  1227  // the traceback function will be displayed as numbers. If the
  1228  // traceback function is nil, the symbolizer function will never be
  1229  // called. The context function may be nil, in which case the
  1230  // traceback function will only be called with the context field set
  1231  // to zero.  If the context function is nil, then calls from Go to C
  1232  // to Go will not show a traceback for the C portion of the call stack.
  1233  //
  1234  // SetCgoTraceback should be called only once, ideally from an init function.
  1235  func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
  1236  	if version != 0 {
  1237  		panic("unsupported version")
  1238  	}
  1239  
  1240  	if cgoTraceback != nil && cgoTraceback != traceback ||
  1241  		cgoContext != nil && cgoContext != context ||
  1242  		cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
  1243  		panic("call SetCgoTraceback only once")
  1244  	}
  1245  
  1246  	cgoTraceback = traceback
  1247  	cgoContext = context
  1248  	cgoSymbolizer = symbolizer
  1249  
  1250  	// The context function is called when a C function calls a Go
  1251  	// function. As such it is only called by C code in runtime/cgo.
  1252  	if _cgo_set_context_function != nil {
  1253  		cgocall(_cgo_set_context_function, context)
  1254  	}
  1255  }
  1256  
  1257  var cgoTraceback unsafe.Pointer
  1258  var cgoContext unsafe.Pointer
  1259  var cgoSymbolizer unsafe.Pointer
  1260  
  1261  // cgoTracebackArg is the type passed to cgoTraceback.
  1262  type cgoTracebackArg struct {
  1263  	context    uintptr
  1264  	sigContext uintptr
  1265  	buf        *uintptr
  1266  	max        uintptr
  1267  }
  1268  
  1269  // cgoContextArg is the type passed to the context function.
  1270  type cgoContextArg struct {
  1271  	context uintptr
  1272  }
  1273  
  1274  // cgoSymbolizerArg is the type passed to cgoSymbolizer.
  1275  type cgoSymbolizerArg struct {
  1276  	pc       uintptr
  1277  	file     *byte
  1278  	lineno   uintptr
  1279  	funcName *byte
  1280  	entry    uintptr
  1281  	more     uintptr
  1282  	data     uintptr
  1283  }
  1284  
  1285  // printCgoTraceback prints a traceback of callers.
  1286  func printCgoTraceback(callers *cgoCallers) {
  1287  	if cgoSymbolizer == nil {
  1288  		for _, c := range callers {
  1289  			if c == 0 {
  1290  				break
  1291  			}
  1292  			print("non-Go function at pc=", hex(c), "\n")
  1293  		}
  1294  		return
  1295  	}
  1296  
  1297  	var arg cgoSymbolizerArg
  1298  	for _, c := range callers {
  1299  		if c == 0 {
  1300  			break
  1301  		}
  1302  		printOneCgoTraceback(c, 0x7fffffff, &arg)
  1303  	}
  1304  	arg.pc = 0
  1305  	callCgoSymbolizer(&arg)
  1306  }
  1307  
  1308  // printOneCgoTraceback prints the traceback of a single cgo caller.
  1309  // This can print more than one line because of inlining.
  1310  // Returns the number of frames printed.
  1311  func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
  1312  	c := 0
  1313  	arg.pc = pc
  1314  	for c <= max {
  1315  		callCgoSymbolizer(arg)
  1316  		if arg.funcName != nil {
  1317  			// Note that we don't print any argument
  1318  			// information here, not even parentheses.
  1319  			// The symbolizer must add that if appropriate.
  1320  			println(gostringnocopy(arg.funcName))
  1321  		} else {
  1322  			println("non-Go function")
  1323  		}
  1324  		print("\t")
  1325  		if arg.file != nil {
  1326  			print(gostringnocopy(arg.file), ":", arg.lineno, " ")
  1327  		}
  1328  		print("pc=", hex(pc), "\n")
  1329  		c++
  1330  		if arg.more == 0 {
  1331  			break
  1332  		}
  1333  	}
  1334  	return c
  1335  }
  1336  
  1337  // callCgoSymbolizer calls the cgoSymbolizer function.
  1338  func callCgoSymbolizer(arg *cgoSymbolizerArg) {
  1339  	call := cgocall
  1340  	if panicking.Load() > 0 || getg().m.curg != getg() {
  1341  		// We do not want to call into the scheduler when panicking
  1342  		// or when on the system stack.
  1343  		call = asmcgocall
  1344  	}
  1345  	if msanenabled {
  1346  		msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
  1347  	}
  1348  	if asanenabled {
  1349  		asanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
  1350  	}
  1351  	call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
  1352  }
  1353  
  1354  // cgoContextPCs gets the PC values from a cgo traceback.
  1355  func cgoContextPCs(ctxt uintptr, buf []uintptr) {
  1356  	if cgoTraceback == nil {
  1357  		return
  1358  	}
  1359  	call := cgocall
  1360  	if panicking.Load() > 0 || getg().m.curg != getg() {
  1361  		// We do not want to call into the scheduler when panicking
  1362  		// or when on the system stack.
  1363  		call = asmcgocall
  1364  	}
  1365  	arg := cgoTracebackArg{
  1366  		context: ctxt,
  1367  		buf:     (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
  1368  		max:     uintptr(len(buf)),
  1369  	}
  1370  	if msanenabled {
  1371  		msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
  1372  	}
  1373  	if asanenabled {
  1374  		asanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
  1375  	}
  1376  	call(cgoTraceback, noescape(unsafe.Pointer(&arg)))
  1377  }
  1378  

View as plain text