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

View as plain text