Source file src/runtime/traceback.go

Documentation: runtime

     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  	"runtime/internal/atomic"
     9  	"runtime/internal/sys"
    10  	"unsafe"
    11  )
    12  
    13  // The code in this file implements stack trace walking for all architectures.
    14  // The most important fact about a given architecture is whether it uses a link register.
    15  // On systems with link registers, the prologue for a non-leaf function stores the
    16  // incoming value of LR at the bottom of the newly allocated stack frame.
    17  // On systems without link registers, the architecture pushes a return PC during
    18  // the call instruction, so the return PC ends up above the stack frame.
    19  // In this file, the return PC is always called LR, no matter how it was found.
    20  //
    21  // To date, the opposite of a link register architecture is an x86 architecture.
    22  // This code may need to change if some other kind of non-link-register
    23  // architecture comes along.
    24  //
    25  // The other important fact is the size of a pointer: on 32-bit systems the LR
    26  // takes up only 4 bytes on the stack, while on 64-bit systems it takes up 8 bytes.
    27  // Typically this is ptrSize.
    28  //
    29  // As an exception, amd64p32 had ptrSize == 4 but the CALL instruction still
    30  // stored an 8-byte return PC onto the stack. To accommodate this, we used regSize
    31  // as the size of the architecture-pushed return PC.
    32  //
    33  // usesLR is defined below in terms of minFrameSize, which is defined in
    34  // arch_$GOARCH.go. ptrSize and regSize are defined in stubs.go.
    35  
    36  const usesLR = sys.MinFrameSize > 0
    37  
    38  var skipPC uintptr
    39  
    40  func tracebackinit() {
    41  	// Go variable initialization happens late during runtime startup.
    42  	// Instead of initializing the variables above in the declarations,
    43  	// schedinit calls this function so that the variables are
    44  	// initialized and available earlier in the startup sequence.
    45  	skipPC = funcPC(skipPleaseUseCallersFrames)
    46  }
    47  
    48  // Traceback over the deferred function calls.
    49  // Report them like calls that have been invoked but not started executing yet.
    50  func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) {
    51  	var frame stkframe
    52  	for d := gp._defer; d != nil; d = d.link {
    53  		fn := d.fn
    54  		if fn == nil {
    55  			// Defer of nil function. Args don't matter.
    56  			frame.pc = 0
    57  			frame.fn = funcInfo{}
    58  			frame.argp = 0
    59  			frame.arglen = 0
    60  			frame.argmap = nil
    61  		} else {
    62  			frame.pc = fn.fn
    63  			f := findfunc(frame.pc)
    64  			if !f.valid() {
    65  				print("runtime: unknown pc in defer ", hex(frame.pc), "\n")
    66  				throw("unknown pc")
    67  			}
    68  			frame.fn = f
    69  			frame.argp = uintptr(deferArgs(d))
    70  			var ok bool
    71  			frame.arglen, frame.argmap, ok = getArgInfoFast(f, true)
    72  			if !ok {
    73  				frame.arglen, frame.argmap = getArgInfo(&frame, f, true, fn)
    74  			}
    75  		}
    76  		frame.continpc = frame.pc
    77  		if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
    78  			return
    79  		}
    80  	}
    81  }
    82  
    83  const sizeofSkipFunction = 256
    84  
    85  // This function is defined in asm.s to be sizeofSkipFunction bytes long.
    86  func skipPleaseUseCallersFrames()
    87  
    88  // Generic traceback. Handles runtime stack prints (pcbuf == nil),
    89  // the runtime.Callers function (pcbuf != nil), as well as the garbage
    90  // collector (callback != nil).  A little clunky to merge these, but avoids
    91  // duplicating the code and all its subtlety.
    92  //
    93  // The skip argument is only valid with pcbuf != nil and counts the number
    94  // of logical frames to skip rather than physical frames (with inlining, a
    95  // PC in pcbuf can represent multiple calls). If a PC is partially skipped
    96  // and max > 1, pcbuf[1] will be runtime.skipPleaseUseCallersFrames+N where
    97  // N indicates the number of logical frames to skip in pcbuf[0].
    98  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 {
    99  	if skip > 0 && callback != nil {
   100  		throw("gentraceback callback cannot be used with non-zero skip")
   101  	}
   102  
   103  	// Don't call this "g"; it's too easy get "g" and "gp" confused.
   104  	if ourg := getg(); ourg == gp && ourg == ourg.m.curg {
   105  		// The starting sp has been passed in as a uintptr, and the caller may
   106  		// have other uintptr-typed stack references as well.
   107  		// If during one of the calls that got us here or during one of the
   108  		// callbacks below the stack must be grown, all these uintptr references
   109  		// to the stack will not be updated, and gentraceback will continue
   110  		// to inspect the old stack memory, which may no longer be valid.
   111  		// Even if all the variables were updated correctly, it is not clear that
   112  		// we want to expose a traceback that begins on one stack and ends
   113  		// on another stack. That could confuse callers quite a bit.
   114  		// Instead, we require that gentraceback and any other function that
   115  		// accepts an sp for the current goroutine (typically obtained by
   116  		// calling getcallersp) must not run on that goroutine's stack but
   117  		// instead on the g0 stack.
   118  		throw("gentraceback cannot trace user goroutine on its own stack")
   119  	}
   120  	level, _, _ := gotraceback()
   121  
   122  	var ctxt *funcval // Context pointer for unstarted goroutines. See issue #25897.
   123  
   124  	if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
   125  		if gp.syscallsp != 0 {
   126  			pc0 = gp.syscallpc
   127  			sp0 = gp.syscallsp
   128  			if usesLR {
   129  				lr0 = 0
   130  			}
   131  		} else {
   132  			pc0 = gp.sched.pc
   133  			sp0 = gp.sched.sp
   134  			if usesLR {
   135  				lr0 = gp.sched.lr
   136  			}
   137  			ctxt = (*funcval)(gp.sched.ctxt)
   138  		}
   139  	}
   140  
   141  	nprint := 0
   142  	var frame stkframe
   143  	frame.pc = pc0
   144  	frame.sp = sp0
   145  	if usesLR {
   146  		frame.lr = lr0
   147  	}
   148  	waspanic := false
   149  	cgoCtxt := gp.cgoCtxt
   150  	printing := pcbuf == nil && callback == nil
   151  
   152  	// If the PC is zero, it's likely a nil function call.
   153  	// Start in the caller's frame.
   154  	if frame.pc == 0 {
   155  		if usesLR {
   156  			frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
   157  			frame.lr = 0
   158  		} else {
   159  			frame.pc = uintptr(*(*sys.Uintreg)(unsafe.Pointer(frame.sp)))
   160  			frame.sp += sys.RegSize
   161  		}
   162  	}
   163  
   164  	f := findfunc(frame.pc)
   165  	if !f.valid() {
   166  		if callback != nil || printing {
   167  			print("runtime: unknown pc ", hex(frame.pc), "\n")
   168  			tracebackHexdump(gp.stack, &frame, 0)
   169  		}
   170  		if callback != nil {
   171  			throw("unknown pc")
   172  		}
   173  		return 0
   174  	}
   175  	frame.fn = f
   176  
   177  	var cache pcvalueCache
   178  
   179  	lastFuncID := funcID_normal
   180  	n := 0
   181  	for n < max {
   182  		// Typically:
   183  		//	pc is the PC of the running function.
   184  		//	sp is the stack pointer at that program counter.
   185  		//	fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
   186  		//	stk is the stack containing sp.
   187  		//	The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
   188  		f = frame.fn
   189  		if f.pcsp == 0 {
   190  			// No frame information, must be external function, like race support.
   191  			// See golang.org/issue/13568.
   192  			break
   193  		}
   194  
   195  		// Found an actual function.
   196  		// Derive frame pointer and link register.
   197  		if frame.fp == 0 {
   198  			// Jump over system stack transitions. If we're on g0 and there's a user
   199  			// goroutine, try to jump. Otherwise this is a regular call.
   200  			if flags&_TraceJumpStack != 0 && gp == gp.m.g0 && gp.m.curg != nil {
   201  				switch f.funcID {
   202  				case funcID_morestack:
   203  					// morestack does not return normally -- newstack()
   204  					// gogo's to curg.sched. Match that.
   205  					// This keeps morestack() from showing up in the backtrace,
   206  					// but that makes some sense since it'll never be returned
   207  					// to.
   208  					frame.pc = gp.m.curg.sched.pc
   209  					frame.fn = findfunc(frame.pc)
   210  					f = frame.fn
   211  					frame.sp = gp.m.curg.sched.sp
   212  					cgoCtxt = gp.m.curg.cgoCtxt
   213  				case funcID_systemstack:
   214  					// systemstack returns normally, so just follow the
   215  					// stack transition.
   216  					frame.sp = gp.m.curg.sched.sp
   217  					cgoCtxt = gp.m.curg.cgoCtxt
   218  				}
   219  			}
   220  			frame.fp = frame.sp + uintptr(funcspdelta(f, frame.pc, &cache))
   221  			if !usesLR {
   222  				// On x86, call instruction pushes return PC before entering new function.
   223  				frame.fp += sys.RegSize
   224  			}
   225  		}
   226  		var flr funcInfo
   227  		if topofstack(f, gp.m != nil && gp == gp.m.g0) {
   228  			frame.lr = 0
   229  			flr = funcInfo{}
   230  		} else if usesLR && f.funcID == funcID_jmpdefer {
   231  			// jmpdefer modifies SP/LR/PC non-atomically.
   232  			// If a profiling interrupt arrives during jmpdefer,
   233  			// the stack unwind may see a mismatched register set
   234  			// and get confused. Stop if we see PC within jmpdefer
   235  			// to avoid that confusion.
   236  			// See golang.org/issue/8153.
   237  			if callback != nil {
   238  				throw("traceback_arm: found jmpdefer when tracing with callback")
   239  			}
   240  			frame.lr = 0
   241  		} else {
   242  			var lrPtr uintptr
   243  			if usesLR {
   244  				if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
   245  					lrPtr = frame.sp
   246  					frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
   247  				}
   248  			} else {
   249  				if frame.lr == 0 {
   250  					lrPtr = frame.fp - sys.RegSize
   251  					frame.lr = uintptr(*(*sys.Uintreg)(unsafe.Pointer(lrPtr)))
   252  				}
   253  			}
   254  			flr = findfunc(frame.lr)
   255  			if !flr.valid() {
   256  				// This happens if you get a profiling interrupt at just the wrong time.
   257  				// In that context it is okay to stop early.
   258  				// But if callback is set, we're doing a garbage collection and must
   259  				// get everything, so crash loudly.
   260  				doPrint := printing
   261  				if doPrint && gp.m.incgo && f.funcID == funcID_sigpanic {
   262  					// We can inject sigpanic
   263  					// calls directly into C code,
   264  					// in which case we'll see a C
   265  					// return PC. Don't complain.
   266  					doPrint = false
   267  				}
   268  				if callback != nil || doPrint {
   269  					print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
   270  					tracebackHexdump(gp.stack, &frame, lrPtr)
   271  				}
   272  				if callback != nil {
   273  					throw("unknown caller pc")
   274  				}
   275  			}
   276  		}
   277  
   278  		frame.varp = frame.fp
   279  		if !usesLR {
   280  			// On x86, call instruction pushes return PC before entering new function.
   281  			frame.varp -= sys.RegSize
   282  		}
   283  
   284  		// If framepointer_enabled and there's a frame, then
   285  		// there's a saved bp here.
   286  		if frame.varp > frame.sp && (framepointer_enabled && GOARCH == "amd64" || GOARCH == "arm64") {
   287  			frame.varp -= sys.RegSize
   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  				for {
   412  					ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil)
   413  					if ix < 0 {
   414  						break
   415  					}
   416  					if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, inltree[ix].funcID, lastFuncID) {
   417  						name := funcnameFromNameoff(f, inltree[ix].func_)
   418  						file, line := funcline(f, tracepc)
   419  						print(name, "(...)\n")
   420  						print("\t", file, ":", line, "\n")
   421  						nprint++
   422  					}
   423  					lastFuncID = inltree[ix].funcID
   424  					// Back up to an instruction in the "caller".
   425  					tracepc = frame.fn.entry + uintptr(inltree[ix].parentPc)
   426  				}
   427  			}
   428  			if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, f.funcID, lastFuncID) {
   429  				// Print during crash.
   430  				//	main(0x1, 0x2, 0x3)
   431  				//		/home/rsc/go/src/runtime/x.go:23 +0xf
   432  				//
   433  				name := funcname(f)
   434  				file, line := funcline(f, tracepc)
   435  				if name == "runtime.gopanic" {
   436  					name = "panic"
   437  				}
   438  				print(name, "(")
   439  				argp := (*[100]uintptr)(unsafe.Pointer(frame.argp))
   440  				for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ {
   441  					if i >= 10 {
   442  						print(", ...")
   443  						break
   444  					}
   445  					if i != 0 {
   446  						print(", ")
   447  					}
   448  					print(hex(argp[i]))
   449  				}
   450  				print(")\n")
   451  				print("\t", file, ":", line)
   452  				if frame.pc > f.entry {
   453  					print(" +", hex(frame.pc-f.entry))
   454  				}
   455  				if gp.m != nil && gp.m.throwing > 0 && gp == gp.m.curg || level >= 2 {
   456  					print(" fp=", hex(frame.fp), " sp=", hex(frame.sp), " pc=", hex(frame.pc))
   457  				}
   458  				print("\n")
   459  				nprint++
   460  			}
   461  			lastFuncID = f.funcID
   462  		}
   463  		n++
   464  
   465  		if f.funcID == funcID_cgocallback_gofunc && len(cgoCtxt) > 0 {
   466  			ctxt := cgoCtxt[len(cgoCtxt)-1]
   467  			cgoCtxt = cgoCtxt[:len(cgoCtxt)-1]
   468  
   469  			// skip only applies to Go frames.
   470  			// callback != nil only used when we only care
   471  			// about Go frames.
   472  			if skip == 0 && callback == nil {
   473  				n = tracebackCgoContext(pcbuf, printing, ctxt, n, max)
   474  			}
   475  		}
   476  
   477  		waspanic = f.funcID == funcID_sigpanic
   478  		injectedCall := waspanic || f.funcID == funcID_asyncPreempt
   479  
   480  		// Do not unwind past the bottom of the stack.
   481  		if !flr.valid() {
   482  			break
   483  		}
   484  
   485  		// Unwind to next frame.
   486  		frame.fn = flr
   487  		frame.pc = frame.lr
   488  		frame.lr = 0
   489  		frame.sp = frame.fp
   490  		frame.fp = 0
   491  		frame.argmap = nil
   492  
   493  		// On link register architectures, sighandler saves the LR on stack
   494  		// before faking a call.
   495  		if usesLR && injectedCall {
   496  			x := *(*uintptr)(unsafe.Pointer(frame.sp))
   497  			frame.sp += sys.MinFrameSize
   498  			if GOARCH == "arm64" {
   499  				// arm64 needs 16-byte aligned SP, always
   500  				frame.sp += sys.PtrSize
   501  			}
   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  // reflectMethodValue is a partial duplicate of reflect.makeFuncImpl
   566  // and reflect.methodValue.
   567  type reflectMethodValue struct {
   568  	fn     uintptr
   569  	stack  *bitvector // ptrmap for both args and results
   570  	argLen uintptr    // just args
   571  }
   572  
   573  // getArgInfoFast returns the argument frame information for a call to f.
   574  // It is short and inlineable. However, it does not handle all functions.
   575  // If ok reports false, you must call getArgInfo instead.
   576  // TODO(josharian): once we do mid-stack inlining,
   577  // call getArgInfo directly from getArgInfoFast and stop returning an ok bool.
   578  func getArgInfoFast(f funcInfo, needArgMap bool) (arglen uintptr, argmap *bitvector, ok bool) {
   579  	return uintptr(f.args), nil, !(needArgMap && f.args == _ArgsSizeUnknown)
   580  }
   581  
   582  // getArgInfo returns the argument frame information for a call to f
   583  // with call frame frame.
   584  //
   585  // This is used for both actual calls with active stack frames and for
   586  // deferred calls or goroutines that are not yet executing. If this is an actual
   587  // call, ctxt must be nil (getArgInfo will retrieve what it needs from
   588  // the active stack frame). If this is a deferred call or unstarted goroutine,
   589  // ctxt must be the function object that was deferred or go'd.
   590  func getArgInfo(frame *stkframe, f funcInfo, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) {
   591  	arglen = uintptr(f.args)
   592  	if needArgMap && f.args == _ArgsSizeUnknown {
   593  		// Extract argument bitmaps for reflect stubs from the calls they made to reflect.
   594  		switch funcname(f) {
   595  		case "reflect.makeFuncStub", "reflect.methodValueCall":
   596  			// These take a *reflect.methodValue as their
   597  			// context register.
   598  			var mv *reflectMethodValue
   599  			var retValid bool
   600  			if ctxt != nil {
   601  				// This is not an actual call, but a
   602  				// deferred call or an unstarted goroutine.
   603  				// The function value is itself the *reflect.methodValue.
   604  				mv = (*reflectMethodValue)(unsafe.Pointer(ctxt))
   605  			} else {
   606  				// This is a real call that took the
   607  				// *reflect.methodValue as its context
   608  				// register and immediately saved it
   609  				// to 0(SP). Get the methodValue from
   610  				// 0(SP).
   611  				arg0 := frame.sp + sys.MinFrameSize
   612  				mv = *(**reflectMethodValue)(unsafe.Pointer(arg0))
   613  				// Figure out whether the return values are valid.
   614  				// Reflect will update this value after it copies
   615  				// in the return values.
   616  				retValid = *(*bool)(unsafe.Pointer(arg0 + 3*sys.PtrSize))
   617  			}
   618  			if mv.fn != f.entry {
   619  				print("runtime: confused by ", funcname(f), "\n")
   620  				throw("reflect mismatch")
   621  			}
   622  			bv := mv.stack
   623  			arglen = uintptr(bv.n * sys.PtrSize)
   624  			if !retValid {
   625  				arglen = uintptr(mv.argLen) &^ (sys.PtrSize - 1)
   626  			}
   627  			argmap = bv
   628  		}
   629  	}
   630  	return
   631  }
   632  
   633  // tracebackCgoContext handles tracing back a cgo context value, from
   634  // the context argument to setCgoTraceback, for the gentraceback
   635  // function. It returns the new value of n.
   636  func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int {
   637  	var cgoPCs [32]uintptr
   638  	cgoContextPCs(ctxt, cgoPCs[:])
   639  	var arg cgoSymbolizerArg
   640  	anySymbolized := false
   641  	for _, pc := range cgoPCs {
   642  		if pc == 0 || n >= max {
   643  			break
   644  		}
   645  		if pcbuf != nil {
   646  			(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   647  		}
   648  		if printing {
   649  			if cgoSymbolizer == nil {
   650  				print("non-Go function at pc=", hex(pc), "\n")
   651  			} else {
   652  				c := printOneCgoTraceback(pc, max-n, &arg)
   653  				n += c - 1 // +1 a few lines down
   654  				anySymbolized = true
   655  			}
   656  		}
   657  		n++
   658  	}
   659  	if anySymbolized {
   660  		arg.pc = 0
   661  		callCgoSymbolizer(&arg)
   662  	}
   663  	return n
   664  }
   665  
   666  func printcreatedby(gp *g) {
   667  	// Show what created goroutine, except main goroutine (goid 1).
   668  	pc := gp.gopc
   669  	f := findfunc(pc)
   670  	if f.valid() && showframe(f, gp, false, funcID_normal, funcID_normal) && gp.goid != 1 {
   671  		printcreatedby1(f, pc)
   672  	}
   673  }
   674  
   675  func printcreatedby1(f funcInfo, pc uintptr) {
   676  	print("created by ", funcname(f), "\n")
   677  	tracepc := pc // back up to CALL instruction for funcline.
   678  	if pc > f.entry {
   679  		tracepc -= sys.PCQuantum
   680  	}
   681  	file, line := funcline(f, tracepc)
   682  	print("\t", file, ":", line)
   683  	if pc > f.entry {
   684  		print(" +", hex(pc-f.entry))
   685  	}
   686  	print("\n")
   687  }
   688  
   689  func traceback(pc, sp, lr uintptr, gp *g) {
   690  	traceback1(pc, sp, lr, gp, 0)
   691  }
   692  
   693  // tracebacktrap is like traceback but expects that the PC and SP were obtained
   694  // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
   695  // Because they are from a trap instead of from a saved pair,
   696  // the initial PC must not be rewound to the previous instruction.
   697  // (All the saved pairs record a PC that is a return address, so we
   698  // rewind it into the CALL instruction.)
   699  // If gp.m.libcall{g,pc,sp} information is available, it uses that information in preference to
   700  // the pc/sp/lr passed in.
   701  func tracebacktrap(pc, sp, lr uintptr, gp *g) {
   702  	if gp.m.libcallsp != 0 {
   703  		// We're in C code somewhere, traceback from the saved position.
   704  		traceback1(gp.m.libcallpc, gp.m.libcallsp, 0, gp.m.libcallg.ptr(), 0)
   705  		return
   706  	}
   707  	traceback1(pc, sp, lr, gp, _TraceTrap)
   708  }
   709  
   710  func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
   711  	// If the goroutine is in cgo, and we have a cgo traceback, print that.
   712  	if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
   713  		// Lock cgoCallers so that a signal handler won't
   714  		// change it, copy the array, reset it, unlock it.
   715  		// We are locked to the thread and are not running
   716  		// concurrently with a signal handler.
   717  		// We just have to stop a signal handler from interrupting
   718  		// in the middle of our copy.
   719  		atomic.Store(&gp.m.cgoCallersUse, 1)
   720  		cgoCallers := *gp.m.cgoCallers
   721  		gp.m.cgoCallers[0] = 0
   722  		atomic.Store(&gp.m.cgoCallersUse, 0)
   723  
   724  		printCgoTraceback(&cgoCallers)
   725  	}
   726  
   727  	var n int
   728  	if readgstatus(gp)&^_Gscan == _Gsyscall {
   729  		// Override registers if blocked in system call.
   730  		pc = gp.syscallpc
   731  		sp = gp.syscallsp
   732  		flags &^= _TraceTrap
   733  	}
   734  	// Print traceback. By default, omits runtime frames.
   735  	// If that means we print nothing at all, repeat forcing all frames printed.
   736  	n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
   737  	if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
   738  		n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
   739  	}
   740  	if n == _TracebackMaxFrames {
   741  		print("...additional frames elided...\n")
   742  	}
   743  	printcreatedby(gp)
   744  
   745  	if gp.ancestors == nil {
   746  		return
   747  	}
   748  	for _, ancestor := range *gp.ancestors {
   749  		printAncestorTraceback(ancestor)
   750  	}
   751  }
   752  
   753  // printAncestorTraceback prints the traceback of the given ancestor.
   754  // TODO: Unify this with gentraceback and CallersFrames.
   755  func printAncestorTraceback(ancestor ancestorInfo) {
   756  	print("[originating from goroutine ", ancestor.goid, "]:\n")
   757  	for fidx, pc := range ancestor.pcs {
   758  		f := findfunc(pc) // f previously validated
   759  		if showfuncinfo(f, fidx == 0, funcID_normal, funcID_normal) {
   760  			printAncestorTracebackFuncInfo(f, pc)
   761  		}
   762  	}
   763  	if len(ancestor.pcs) == _TracebackMaxFrames {
   764  		print("...additional frames elided...\n")
   765  	}
   766  	// Show what created goroutine, except main goroutine (goid 1).
   767  	f := findfunc(ancestor.gopc)
   768  	if f.valid() && showfuncinfo(f, false, funcID_normal, funcID_normal) && ancestor.goid != 1 {
   769  		printcreatedby1(f, ancestor.gopc)
   770  	}
   771  }
   772  
   773  // printAncestorTraceback prints the given function info at a given pc
   774  // within an ancestor traceback. The precision of this info is reduced
   775  // due to only have access to the pcs at the time of the caller
   776  // goroutine being created.
   777  func printAncestorTracebackFuncInfo(f funcInfo, pc uintptr) {
   778  	name := funcname(f)
   779  	if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
   780  		inltree := (*[1 << 20]inlinedCall)(inldata)
   781  		ix := pcdatavalue(f, _PCDATA_InlTreeIndex, pc, nil)
   782  		if ix >= 0 {
   783  			name = funcnameFromNameoff(f, inltree[ix].func_)
   784  		}
   785  	}
   786  	file, line := funcline(f, pc)
   787  	if name == "runtime.gopanic" {
   788  		name = "panic"
   789  	}
   790  	print(name, "(...)\n")
   791  	print("\t", file, ":", line)
   792  	if pc > f.entry {
   793  		print(" +", hex(pc-f.entry))
   794  	}
   795  	print("\n")
   796  }
   797  
   798  func callers(skip int, pcbuf []uintptr) int {
   799  	sp := getcallersp()
   800  	pc := getcallerpc()
   801  	gp := getg()
   802  	var n int
   803  	systemstack(func() {
   804  		n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   805  	})
   806  	return n
   807  }
   808  
   809  func gcallers(gp *g, skip int, pcbuf []uintptr) int {
   810  	return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   811  }
   812  
   813  // showframe reports whether the frame with the given characteristics should
   814  // be printed during a traceback.
   815  func showframe(f funcInfo, gp *g, firstFrame bool, funcID, childID funcID) bool {
   816  	g := getg()
   817  	if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
   818  		return true
   819  	}
   820  	return showfuncinfo(f, firstFrame, funcID, childID)
   821  }
   822  
   823  // showfuncinfo reports whether a function with the given characteristics should
   824  // be printed during a traceback.
   825  func showfuncinfo(f funcInfo, firstFrame bool, funcID, childID funcID) bool {
   826  	level, _, _ := gotraceback()
   827  	if level > 1 {
   828  		// Show all frames.
   829  		return true
   830  	}
   831  
   832  	if !f.valid() {
   833  		return false
   834  	}
   835  
   836  	if funcID == funcID_wrapper && elideWrapperCalling(childID) {
   837  		return false
   838  	}
   839  
   840  	name := funcname(f)
   841  
   842  	// Special case: always show runtime.gopanic frame
   843  	// in the middle of a stack trace, so that we can
   844  	// see the boundary between ordinary code and
   845  	// panic-induced deferred code.
   846  	// See golang.org/issue/5832.
   847  	if name == "runtime.gopanic" && !firstFrame {
   848  		return true
   849  	}
   850  
   851  	return contains(name, ".") && (!hasPrefix(name, "runtime.") || isExportedRuntime(name))
   852  }
   853  
   854  // isExportedRuntime reports whether name is an exported runtime function.
   855  // It is only for runtime functions, so ASCII A-Z is fine.
   856  func isExportedRuntime(name string) bool {
   857  	const n = len("runtime.")
   858  	return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
   859  }
   860  
   861  // elideWrapperCalling reports whether a wrapper function that called
   862  // function id should be elided from stack traces.
   863  func elideWrapperCalling(id funcID) bool {
   864  	// If the wrapper called a panic function instead of the
   865  	// wrapped function, we want to include it in stacks.
   866  	return !(id == funcID_gopanic || id == funcID_sigpanic || id == funcID_panicwrap)
   867  }
   868  
   869  var gStatusStrings = [...]string{
   870  	_Gidle:      "idle",
   871  	_Grunnable:  "runnable",
   872  	_Grunning:   "running",
   873  	_Gsyscall:   "syscall",
   874  	_Gwaiting:   "waiting",
   875  	_Gdead:      "dead",
   876  	_Gcopystack: "copystack",
   877  	_Gpreempted: "preempted",
   878  }
   879  
   880  func goroutineheader(gp *g) {
   881  	gpstatus := readgstatus(gp)
   882  
   883  	isScan := gpstatus&_Gscan != 0
   884  	gpstatus &^= _Gscan // drop the scan bit
   885  
   886  	// Basic string status
   887  	var status string
   888  	if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
   889  		status = gStatusStrings[gpstatus]
   890  	} else {
   891  		status = "???"
   892  	}
   893  
   894  	// Override.
   895  	if gpstatus == _Gwaiting && gp.waitreason != waitReasonZero {
   896  		status = gp.waitreason.String()
   897  	}
   898  
   899  	// approx time the G is blocked, in minutes
   900  	var waitfor int64
   901  	if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
   902  		waitfor = (nanotime() - gp.waitsince) / 60e9
   903  	}
   904  	print("goroutine ", gp.goid, " [", status)
   905  	if isScan {
   906  		print(" (scan)")
   907  	}
   908  	if waitfor >= 1 {
   909  		print(", ", waitfor, " minutes")
   910  	}
   911  	if gp.lockedm != 0 {
   912  		print(", locked to thread")
   913  	}
   914  	print("]:\n")
   915  }
   916  
   917  func tracebackothers(me *g) {
   918  	level, _, _ := gotraceback()
   919  
   920  	// Show the current goroutine first, if we haven't already.
   921  	g := getg()
   922  	gp := g.m.curg
   923  	if gp != nil && gp != me {
   924  		print("\n")
   925  		goroutineheader(gp)
   926  		traceback(^uintptr(0), ^uintptr(0), 0, gp)
   927  	}
   928  
   929  	lock(&allglock)
   930  	for _, gp := range allgs {
   931  		if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp, false) && level < 2 {
   932  			continue
   933  		}
   934  		print("\n")
   935  		goroutineheader(gp)
   936  		// Note: gp.m == g.m occurs when tracebackothers is
   937  		// called from a signal handler initiated during a
   938  		// systemstack call. The original G is still in the
   939  		// running state, and we want to print its stack.
   940  		if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning {
   941  			print("\tgoroutine running on other thread; stack unavailable\n")
   942  			printcreatedby(gp)
   943  		} else {
   944  			traceback(^uintptr(0), ^uintptr(0), 0, gp)
   945  		}
   946  	}
   947  	unlock(&allglock)
   948  }
   949  
   950  // tracebackHexdump hexdumps part of stk around frame.sp and frame.fp
   951  // for debugging purposes. If the address bad is included in the
   952  // hexdumped range, it will mark it as well.
   953  func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) {
   954  	const expand = 32 * sys.PtrSize
   955  	const maxExpand = 256 * sys.PtrSize
   956  	// Start around frame.sp.
   957  	lo, hi := frame.sp, frame.sp
   958  	// Expand to include frame.fp.
   959  	if frame.fp != 0 && frame.fp < lo {
   960  		lo = frame.fp
   961  	}
   962  	if frame.fp != 0 && frame.fp > hi {
   963  		hi = frame.fp
   964  	}
   965  	// Expand a bit more.
   966  	lo, hi = lo-expand, hi+expand
   967  	// But don't go too far from frame.sp.
   968  	if lo < frame.sp-maxExpand {
   969  		lo = frame.sp - maxExpand
   970  	}
   971  	if hi > frame.sp+maxExpand {
   972  		hi = frame.sp + maxExpand
   973  	}
   974  	// And don't go outside the stack bounds.
   975  	if lo < stk.lo {
   976  		lo = stk.lo
   977  	}
   978  	if hi > stk.hi {
   979  		hi = stk.hi
   980  	}
   981  
   982  	// Print the hex dump.
   983  	print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n")
   984  	hexdumpWords(lo, hi, func(p uintptr) byte {
   985  		switch p {
   986  		case frame.fp:
   987  			return '>'
   988  		case frame.sp:
   989  			return '<'
   990  		case bad:
   991  			return '!'
   992  		}
   993  		return 0
   994  	})
   995  }
   996  
   997  // Does f mark the top of a goroutine stack?
   998  func topofstack(f funcInfo, g0 bool) bool {
   999  	return f.funcID == funcID_goexit ||
  1000  		f.funcID == funcID_mstart ||
  1001  		f.funcID == funcID_mcall ||
  1002  		f.funcID == funcID_morestack ||
  1003  		f.funcID == funcID_rt0_go ||
  1004  		f.funcID == funcID_externalthreadhandler ||
  1005  		// asmcgocall is TOS on the system stack because it
  1006  		// switches to the system stack, but in this case we
  1007  		// can come back to the regular stack and still want
  1008  		// to be able to unwind through the call that appeared
  1009  		// on the regular stack.
  1010  		(g0 && f.funcID == funcID_asmcgocall)
  1011  }
  1012  
  1013  // isSystemGoroutine reports whether the goroutine g must be omitted
  1014  // in stack dumps and deadlock detector. This is any goroutine that
  1015  // starts at a runtime.* entry point, except for runtime.main,
  1016  // runtime.handleAsyncEvent (wasm only) and sometimes runtime.runfinq.
  1017  //
  1018  // If fixed is true, any goroutine that can vary between user and
  1019  // system (that is, the finalizer goroutine) is considered a user
  1020  // goroutine.
  1021  func isSystemGoroutine(gp *g, fixed bool) bool {
  1022  	// Keep this in sync with cmd/trace/trace.go:isSystemGoroutine.
  1023  	f := findfunc(gp.startpc)
  1024  	if !f.valid() {
  1025  		return false
  1026  	}
  1027  	if f.funcID == funcID_runtime_main || f.funcID == funcID_handleAsyncEvent {
  1028  		return false
  1029  	}
  1030  	if f.funcID == funcID_runfinq {
  1031  		// We include the finalizer goroutine if it's calling
  1032  		// back into user code.
  1033  		if fixed {
  1034  			// This goroutine can vary. In fixed mode,
  1035  			// always consider it a user goroutine.
  1036  			return false
  1037  		}
  1038  		return !fingRunning
  1039  	}
  1040  	return hasPrefix(funcname(f), "runtime.")
  1041  }
  1042  
  1043  // SetCgoTraceback records three C functions to use to gather
  1044  // traceback information from C code and to convert that traceback
  1045  // information into symbolic information. These are used when printing
  1046  // stack traces for a program that uses cgo.
  1047  //
  1048  // The traceback and context functions may be called from a signal
  1049  // handler, and must therefore use only async-signal safe functions.
  1050  // The symbolizer function may be called while the program is
  1051  // crashing, and so must be cautious about using memory.  None of the
  1052  // functions may call back into Go.
  1053  //
  1054  // The context function will be called with a single argument, a
  1055  // pointer to a struct:
  1056  //
  1057  //	struct {
  1058  //		Context uintptr
  1059  //	}
  1060  //
  1061  // In C syntax, this struct will be
  1062  //
  1063  //	struct {
  1064  //		uintptr_t Context;
  1065  //	};
  1066  //
  1067  // If the Context field is 0, the context function is being called to
  1068  // record the current traceback context. It should record in the
  1069  // Context field whatever information is needed about the current
  1070  // point of execution to later produce a stack trace, probably the
  1071  // stack pointer and PC. In this case the context function will be
  1072  // called from C code.
  1073  //
  1074  // If the Context field is not 0, then it is a value returned by a
  1075  // previous call to the context function. This case is called when the
  1076  // context is no longer needed; that is, when the Go code is returning
  1077  // to its C code caller. This permits the context function to release
  1078  // any associated resources.
  1079  //
  1080  // While it would be correct for the context function to record a
  1081  // complete a stack trace whenever it is called, and simply copy that
  1082  // out in the traceback function, in a typical program the context
  1083  // function will be called many times without ever recording a
  1084  // traceback for that context. Recording a complete stack trace in a
  1085  // call to the context function is likely to be inefficient.
  1086  //
  1087  // The traceback function will be called with a single argument, a
  1088  // pointer to a struct:
  1089  //
  1090  //	struct {
  1091  //		Context    uintptr
  1092  //		SigContext uintptr
  1093  //		Buf        *uintptr
  1094  //		Max        uintptr
  1095  //	}
  1096  //
  1097  // In C syntax, this struct will be
  1098  //
  1099  //	struct {
  1100  //		uintptr_t  Context;
  1101  //		uintptr_t  SigContext;
  1102  //		uintptr_t* Buf;
  1103  //		uintptr_t  Max;
  1104  //	};
  1105  //
  1106  // The Context field will be zero to gather a traceback from the
  1107  // current program execution point. In this case, the traceback
  1108  // function will be called from C code.
  1109  //
  1110  // Otherwise Context will be a value previously returned by a call to
  1111  // the context function. The traceback function should gather a stack
  1112  // trace from that saved point in the program execution. The traceback
  1113  // function may be called from an execution thread other than the one
  1114  // that recorded the context, but only when the context is known to be
  1115  // valid and unchanging. The traceback function may also be called
  1116  // deeper in the call stack on the same thread that recorded the
  1117  // context. The traceback function may be called multiple times with
  1118  // the same Context value; it will usually be appropriate to cache the
  1119  // result, if possible, the first time this is called for a specific
  1120  // context value.
  1121  //
  1122  // If the traceback function is called from a signal handler on a Unix
  1123  // system, SigContext will be the signal context argument passed to
  1124  // the signal handler (a C ucontext_t* cast to uintptr_t). This may be
  1125  // used to start tracing at the point where the signal occurred. If
  1126  // the traceback function is not called from a signal handler,
  1127  // SigContext will be zero.
  1128  //
  1129  // Buf is where the traceback information should be stored. It should
  1130  // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
  1131  // the PC of that function's caller, and so on.  Max is the maximum
  1132  // number of entries to store.  The function should store a zero to
  1133  // indicate the top of the stack, or that the caller is on a different
  1134  // stack, presumably a Go stack.
  1135  //
  1136  // Unlike runtime.Callers, the PC values returned should, when passed
  1137  // to the symbolizer function, return the file/line of the call
  1138  // instruction.  No additional subtraction is required or appropriate.
  1139  //
  1140  // On all platforms, the traceback function is invoked when a call from
  1141  // Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le,
  1142  // and freebsd/amd64, the traceback function is also invoked when a
  1143  // signal is received by a thread that is executing a cgo call. The
  1144  // traceback function should not make assumptions about when it is
  1145  // called, as future versions of Go may make additional calls.
  1146  //
  1147  // The symbolizer function will be called with a single argument, a
  1148  // pointer to a struct:
  1149  //
  1150  //	struct {
  1151  //		PC      uintptr // program counter to fetch information for
  1152  //		File    *byte   // file name (NUL terminated)
  1153  //		Lineno  uintptr // line number
  1154  //		Func    *byte   // function name (NUL terminated)
  1155  //		Entry   uintptr // function entry point
  1156  //		More    uintptr // set non-zero if more info for this PC
  1157  //		Data    uintptr // unused by runtime, available for function
  1158  //	}
  1159  //
  1160  // In C syntax, this struct will be
  1161  //
  1162  //	struct {
  1163  //		uintptr_t PC;
  1164  //		char*     File;
  1165  //		uintptr_t Lineno;
  1166  //		char*     Func;
  1167  //		uintptr_t Entry;
  1168  //		uintptr_t More;
  1169  //		uintptr_t Data;
  1170  //	};
  1171  //
  1172  // The PC field will be a value returned by a call to the traceback
  1173  // function.
  1174  //
  1175  // The first time the function is called for a particular traceback,
  1176  // all the fields except PC will be 0. The function should fill in the
  1177  // other fields if possible, setting them to 0/nil if the information
  1178  // is not available. The Data field may be used to store any useful
  1179  // information across calls. The More field should be set to non-zero
  1180  // if there is more information for this PC, zero otherwise. If More
  1181  // is set non-zero, the function will be called again with the same
  1182  // PC, and may return different information (this is intended for use
  1183  // with inlined functions). If More is zero, the function will be
  1184  // called with the next PC value in the traceback. When the traceback
  1185  // is complete, the function will be called once more with PC set to
  1186  // zero; this may be used to free any information. Each call will
  1187  // leave the fields of the struct set to the same values they had upon
  1188  // return, except for the PC field when the More field is zero. The
  1189  // function must not keep a copy of the struct pointer between calls.
  1190  //
  1191  // When calling SetCgoTraceback, the version argument is the version
  1192  // number of the structs that the functions expect to receive.
  1193  // Currently this must be zero.
  1194  //
  1195  // The symbolizer function may be nil, in which case the results of
  1196  // the traceback function will be displayed as numbers. If the
  1197  // traceback function is nil, the symbolizer function will never be
  1198  // called. The context function may be nil, in which case the
  1199  // traceback function will only be called with the context field set
  1200  // to zero.  If the context function is nil, then calls from Go to C
  1201  // to Go will not show a traceback for the C portion of the call stack.
  1202  //
  1203  // SetCgoTraceback should be called only once, ideally from an init function.
  1204  func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
  1205  	if version != 0 {
  1206  		panic("unsupported version")
  1207  	}
  1208  
  1209  	if cgoTraceback != nil && cgoTraceback != traceback ||
  1210  		cgoContext != nil && cgoContext != context ||
  1211  		cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
  1212  		panic("call SetCgoTraceback only once")
  1213  	}
  1214  
  1215  	cgoTraceback = traceback
  1216  	cgoContext = context
  1217  	cgoSymbolizer = symbolizer
  1218  
  1219  	// The context function is called when a C function calls a Go
  1220  	// function. As such it is only called by C code in runtime/cgo.
  1221  	if _cgo_set_context_function != nil {
  1222  		cgocall(_cgo_set_context_function, context)
  1223  	}
  1224  }
  1225  
  1226  var cgoTraceback unsafe.Pointer
  1227  var cgoContext unsafe.Pointer
  1228  var cgoSymbolizer unsafe.Pointer
  1229  
  1230  // cgoTracebackArg is the type passed to cgoTraceback.
  1231  type cgoTracebackArg struct {
  1232  	context    uintptr
  1233  	sigContext uintptr
  1234  	buf        *uintptr
  1235  	max        uintptr
  1236  }
  1237  
  1238  // cgoContextArg is the type passed to the context function.
  1239  type cgoContextArg struct {
  1240  	context uintptr
  1241  }
  1242  
  1243  // cgoSymbolizerArg is the type passed to cgoSymbolizer.
  1244  type cgoSymbolizerArg struct {
  1245  	pc       uintptr
  1246  	file     *byte
  1247  	lineno   uintptr
  1248  	funcName *byte
  1249  	entry    uintptr
  1250  	more     uintptr
  1251  	data     uintptr
  1252  }
  1253  
  1254  // cgoTraceback prints a traceback of callers.
  1255  func printCgoTraceback(callers *cgoCallers) {
  1256  	if cgoSymbolizer == nil {
  1257  		for _, c := range callers {
  1258  			if c == 0 {
  1259  				break
  1260  			}
  1261  			print("non-Go function at pc=", hex(c), "\n")
  1262  		}
  1263  		return
  1264  	}
  1265  
  1266  	var arg cgoSymbolizerArg
  1267  	for _, c := range callers {
  1268  		if c == 0 {
  1269  			break
  1270  		}
  1271  		printOneCgoTraceback(c, 0x7fffffff, &arg)
  1272  	}
  1273  	arg.pc = 0
  1274  	callCgoSymbolizer(&arg)
  1275  }
  1276  
  1277  // printOneCgoTraceback prints the traceback of a single cgo caller.
  1278  // This can print more than one line because of inlining.
  1279  // Returns the number of frames printed.
  1280  func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
  1281  	c := 0
  1282  	arg.pc = pc
  1283  	for c <= max {
  1284  		callCgoSymbolizer(arg)
  1285  		if arg.funcName != nil {
  1286  			// Note that we don't print any argument
  1287  			// information here, not even parentheses.
  1288  			// The symbolizer must add that if appropriate.
  1289  			println(gostringnocopy(arg.funcName))
  1290  		} else {
  1291  			println("non-Go function")
  1292  		}
  1293  		print("\t")
  1294  		if arg.file != nil {
  1295  			print(gostringnocopy(arg.file), ":", arg.lineno, " ")
  1296  		}
  1297  		print("pc=", hex(pc), "\n")
  1298  		c++
  1299  		if arg.more == 0 {
  1300  			break
  1301  		}
  1302  	}
  1303  	return c
  1304  }
  1305  
  1306  // callCgoSymbolizer calls the cgoSymbolizer function.
  1307  func callCgoSymbolizer(arg *cgoSymbolizerArg) {
  1308  	call := cgocall
  1309  	if panicking > 0 || getg().m.curg != getg() {
  1310  		// We do not want to call into the scheduler when panicking
  1311  		// or when on the system stack.
  1312  		call = asmcgocall
  1313  	}
  1314  	if msanenabled {
  1315  		msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
  1316  	}
  1317  	call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
  1318  }
  1319  
  1320  // cgoContextPCs gets the PC values from a cgo traceback.
  1321  func cgoContextPCs(ctxt uintptr, buf []uintptr) {
  1322  	if cgoTraceback == nil {
  1323  		return
  1324  	}
  1325  	call := cgocall
  1326  	if panicking > 0 || getg().m.curg != getg() {
  1327  		// We do not want to call into the scheduler when panicking
  1328  		// or when on the system stack.
  1329  		call = asmcgocall
  1330  	}
  1331  	arg := cgoTracebackArg{
  1332  		context: ctxt,
  1333  		buf:     (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
  1334  		max:     uintptr(len(buf)),
  1335  	}
  1336  	if msanenabled {
  1337  		msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
  1338  	}
  1339  	call(cgoTraceback, noescape(unsafe.Pointer(&arg)))
  1340  }
  1341  

View as plain text