...
Run Format

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 has ptrSize == 4 but the CALL instruction still
    30  // stores an 8-byte return PC onto the stack. To accommodate this, we use 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  	g := getg()
   103  	if g == gp && g == g.m.curg {
   104  		// The starting sp has been passed in as a uintptr, and the caller may
   105  		// have other uintptr-typed stack references as well.
   106  		// If during one of the calls that got us here or during one of the
   107  		// callbacks below the stack must be grown, all these uintptr references
   108  		// to the stack will not be updated, and gentraceback will continue
   109  		// to inspect the old stack memory, which may no longer be valid.
   110  		// Even if all the variables were updated correctly, it is not clear that
   111  		// we want to expose a traceback that begins on one stack and ends
   112  		// on another stack. That could confuse callers quite a bit.
   113  		// Instead, we require that gentraceback and any other function that
   114  		// accepts an sp for the current goroutine (typically obtained by
   115  		// calling getcallersp) must not run on that goroutine's stack but
   116  		// instead on the g0 stack.
   117  		throw("gentraceback cannot trace user goroutine on its own stack")
   118  	}
   119  	level, _, _ := gotraceback()
   120  
   121  	if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
   122  		if gp.syscallsp != 0 {
   123  			pc0 = gp.syscallpc
   124  			sp0 = gp.syscallsp
   125  			if usesLR {
   126  				lr0 = 0
   127  			}
   128  		} else {
   129  			pc0 = gp.sched.pc
   130  			sp0 = gp.sched.sp
   131  			if usesLR {
   132  				lr0 = gp.sched.lr
   133  			}
   134  		}
   135  	}
   136  
   137  	nprint := 0
   138  	var frame stkframe
   139  	frame.pc = pc0
   140  	frame.sp = sp0
   141  	if usesLR {
   142  		frame.lr = lr0
   143  	}
   144  	waspanic := false
   145  	cgoCtxt := gp.cgoCtxt
   146  	printing := pcbuf == nil && callback == nil
   147  	_defer := gp._defer
   148  	elideWrapper := false
   149  
   150  	for _defer != nil && _defer.sp == _NoArgs {
   151  		_defer = _defer.link
   152  	}
   153  
   154  	// If the PC is zero, it's likely a nil function call.
   155  	// Start in the caller's frame.
   156  	if frame.pc == 0 {
   157  		if usesLR {
   158  			frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
   159  			frame.lr = 0
   160  		} else {
   161  			frame.pc = uintptr(*(*sys.Uintreg)(unsafe.Pointer(frame.sp)))
   162  			frame.sp += sys.RegSize
   163  		}
   164  	}
   165  
   166  	f := findfunc(frame.pc)
   167  	if !f.valid() {
   168  		if callback != nil || printing {
   169  			print("runtime: unknown pc ", hex(frame.pc), "\n")
   170  			tracebackHexdump(gp.stack, &frame, 0)
   171  		}
   172  		if callback != nil {
   173  			throw("unknown pc")
   174  		}
   175  		return 0
   176  	}
   177  	frame.fn = f
   178  
   179  	var cache pcvalueCache
   180  
   181  	n := 0
   182  	for n < max {
   183  		// Typically:
   184  		//	pc is the PC of the running function.
   185  		//	sp is the stack pointer at that program counter.
   186  		//	fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
   187  		//	stk is the stack containing sp.
   188  		//	The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
   189  		f = frame.fn
   190  		if f.pcsp == 0 {
   191  			// No frame information, must be external function, like race support.
   192  			// See golang.org/issue/13568.
   193  			break
   194  		}
   195  
   196  		// Found an actual function.
   197  		// Derive frame pointer and link register.
   198  		if frame.fp == 0 {
   199  			// We want to jump over the systemstack switch. If we're running on the
   200  			// g0, this systemstack is at the top of the stack.
   201  			// if we're not on g0 or there's a no curg, then this is a regular call.
   202  			sp := frame.sp
   203  			if flags&_TraceJumpStack != 0 && f.funcID == funcID_systemstack && gp == g.m.g0 && gp.m.curg != nil {
   204  				sp = gp.m.curg.sched.sp
   205  				frame.sp = sp
   206  				cgoCtxt = gp.m.curg.cgoCtxt
   207  			}
   208  			frame.fp = sp + uintptr(funcspdelta(f, frame.pc, &cache))
   209  			if !usesLR {
   210  				// On x86, call instruction pushes return PC before entering new function.
   211  				frame.fp += sys.RegSize
   212  			}
   213  		}
   214  		var flr funcInfo
   215  		if topofstack(f, gp.m != nil && gp == gp.m.g0) {
   216  			frame.lr = 0
   217  			flr = funcInfo{}
   218  		} else if usesLR && f.funcID == funcID_jmpdefer {
   219  			// jmpdefer modifies SP/LR/PC non-atomically.
   220  			// If a profiling interrupt arrives during jmpdefer,
   221  			// the stack unwind may see a mismatched register set
   222  			// and get confused. Stop if we see PC within jmpdefer
   223  			// to avoid that confusion.
   224  			// See golang.org/issue/8153.
   225  			if callback != nil {
   226  				throw("traceback_arm: found jmpdefer when tracing with callback")
   227  			}
   228  			frame.lr = 0
   229  		} else {
   230  			var lrPtr uintptr
   231  			if usesLR {
   232  				if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
   233  					lrPtr = frame.sp
   234  					frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
   235  				}
   236  			} else {
   237  				if frame.lr == 0 {
   238  					lrPtr = frame.fp - sys.RegSize
   239  					frame.lr = uintptr(*(*sys.Uintreg)(unsafe.Pointer(lrPtr)))
   240  				}
   241  			}
   242  			flr = findfunc(frame.lr)
   243  			if !flr.valid() {
   244  				// This happens if you get a profiling interrupt at just the wrong time.
   245  				// In that context it is okay to stop early.
   246  				// But if callback is set, we're doing a garbage collection and must
   247  				// get everything, so crash loudly.
   248  				doPrint := printing
   249  				if doPrint && gp.m.incgo && f.funcID == funcID_sigpanic {
   250  					// We can inject sigpanic
   251  					// calls directly into C code,
   252  					// in which case we'll see a C
   253  					// return PC. Don't complain.
   254  					doPrint = false
   255  				}
   256  				if callback != nil || doPrint {
   257  					print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
   258  					tracebackHexdump(gp.stack, &frame, lrPtr)
   259  				}
   260  				if callback != nil {
   261  					throw("unknown caller pc")
   262  				}
   263  			}
   264  		}
   265  
   266  		frame.varp = frame.fp
   267  		if !usesLR {
   268  			// On x86, call instruction pushes return PC before entering new function.
   269  			frame.varp -= sys.RegSize
   270  		}
   271  
   272  		// If framepointer_enabled and there's a frame, then
   273  		// there's a saved bp here.
   274  		if framepointer_enabled && GOARCH == "amd64" && frame.varp > frame.sp {
   275  			frame.varp -= sys.RegSize
   276  		}
   277  
   278  		// Derive size of arguments.
   279  		// Most functions have a fixed-size argument block,
   280  		// so we can use metadata about the function f.
   281  		// Not all, though: there are some variadic functions
   282  		// in package runtime and reflect, and for those we use call-specific
   283  		// metadata recorded by f's caller.
   284  		if callback != nil || printing {
   285  			frame.argp = frame.fp + sys.MinFrameSize
   286  			var ok bool
   287  			frame.arglen, frame.argmap, ok = getArgInfoFast(f, callback != nil)
   288  			if !ok {
   289  				frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil, nil)
   290  			}
   291  		}
   292  
   293  		// Determine frame's 'continuation PC', where it can continue.
   294  		// Normally this is the return address on the stack, but if sigpanic
   295  		// is immediately below this function on the stack, then the frame
   296  		// stopped executing due to a trap, and frame.pc is probably not
   297  		// a safe point for looking up liveness information. In this panicking case,
   298  		// the function either doesn't return at all (if it has no defers or if the
   299  		// defers do not recover) or it returns from one of the calls to
   300  		// deferproc a second time (if the corresponding deferred func recovers).
   301  		// It suffices to assume that the most recent deferproc is the one that
   302  		// returns; everything live at earlier deferprocs is still live at that one.
   303  		frame.continpc = frame.pc
   304  		if waspanic {
   305  			// We match up defers with frames using the SP.
   306  			// However, if the function has an empty stack
   307  			// frame, then it's possible (on LR machines)
   308  			// for multiple call frames to have the same
   309  			// SP. But, since a function with no frame
   310  			// can't push a defer, the defer can't belong
   311  			// to that frame.
   312  			if _defer != nil && _defer.sp == frame.sp && frame.sp != frame.fp {
   313  				frame.continpc = _defer.pc
   314  			} else {
   315  				frame.continpc = 0
   316  			}
   317  		}
   318  
   319  		// Unwind our local defer stack past this frame.
   320  		for _defer != nil && ((_defer.sp == frame.sp && frame.sp != frame.fp) || _defer.sp == _NoArgs) {
   321  			_defer = _defer.link
   322  		}
   323  
   324  		if callback != nil {
   325  			if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
   326  				return n
   327  			}
   328  		}
   329  
   330  		if pcbuf != nil {
   331  			if skip == 0 {
   332  				(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc
   333  			} else {
   334  				// backup to CALL instruction to read inlining info (same logic as below)
   335  				tracepc := frame.pc
   336  				if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
   337  					tracepc--
   338  				}
   339  				inldata := funcdata(f, _FUNCDATA_InlTree)
   340  
   341  				// no inlining info, skip the physical frame
   342  				if inldata == nil {
   343  					skip--
   344  					goto skipped
   345  				}
   346  
   347  				ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, &cache)
   348  				inltree := (*[1 << 20]inlinedCall)(inldata)
   349  				// skip the logical (inlined) frames
   350  				logicalSkipped := 0
   351  				for ix >= 0 && skip > 0 {
   352  					skip--
   353  					logicalSkipped++
   354  					ix = inltree[ix].parent
   355  				}
   356  
   357  				// skip the physical frame if there's more to skip
   358  				if skip > 0 {
   359  					skip--
   360  					goto skipped
   361  				}
   362  
   363  				// now we have a partially skipped frame
   364  				(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc
   365  
   366  				// if there's room, pcbuf[1] is a skip PC that encodes the number of skipped frames in pcbuf[0]
   367  				if n+1 < max {
   368  					n++
   369  					pc := skipPC + uintptr(logicalSkipped)
   370  					(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   371  				}
   372  			}
   373  		}
   374  
   375  		if printing {
   376  			// assume skip=0 for printing.
   377  			//
   378  			// Never elide wrappers if we haven't printed
   379  			// any frames. And don't elide wrappers that
   380  			// called panic rather than the wrapped
   381  			// function. Otherwise, leave them out.
   382  			name := funcname(f)
   383  			nextElideWrapper := elideWrapperCalling(name)
   384  			if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, elideWrapper && nprint != 0) {
   385  				// Print during crash.
   386  				//	main(0x1, 0x2, 0x3)
   387  				//		/home/rsc/go/src/runtime/x.go:23 +0xf
   388  				//
   389  				tracepc := frame.pc // back up to CALL instruction for funcline.
   390  				if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
   391  					tracepc--
   392  				}
   393  				file, line := funcline(f, tracepc)
   394  				inldata := funcdata(f, _FUNCDATA_InlTree)
   395  				if inldata != nil {
   396  					inltree := (*[1 << 20]inlinedCall)(inldata)
   397  					ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil)
   398  					for ix != -1 {
   399  						name := funcnameFromNameoff(f, inltree[ix].func_)
   400  						print(name, "(...)\n")
   401  						print("\t", file, ":", line, "\n")
   402  
   403  						file = funcfile(f, inltree[ix].file)
   404  						line = inltree[ix].line
   405  						ix = inltree[ix].parent
   406  					}
   407  				}
   408  				if name == "runtime.gopanic" {
   409  					name = "panic"
   410  				}
   411  				print(name, "(")
   412  				argp := (*[100]uintptr)(unsafe.Pointer(frame.argp))
   413  				for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ {
   414  					if i >= 10 {
   415  						print(", ...")
   416  						break
   417  					}
   418  					if i != 0 {
   419  						print(", ")
   420  					}
   421  					print(hex(argp[i]))
   422  				}
   423  				print(")\n")
   424  				print("\t", file, ":", line)
   425  				if frame.pc > f.entry {
   426  					print(" +", hex(frame.pc-f.entry))
   427  				}
   428  				if g.m.throwing > 0 && gp == g.m.curg || level >= 2 {
   429  					print(" fp=", hex(frame.fp), " sp=", hex(frame.sp), " pc=", hex(frame.pc))
   430  				}
   431  				print("\n")
   432  				nprint++
   433  			}
   434  			elideWrapper = nextElideWrapper
   435  		}
   436  		n++
   437  
   438  	skipped:
   439  		if f.funcID == funcID_cgocallback_gofunc && len(cgoCtxt) > 0 {
   440  			ctxt := cgoCtxt[len(cgoCtxt)-1]
   441  			cgoCtxt = cgoCtxt[:len(cgoCtxt)-1]
   442  
   443  			// skip only applies to Go frames.
   444  			// callback != nil only used when we only care
   445  			// about Go frames.
   446  			if skip == 0 && callback == nil {
   447  				n = tracebackCgoContext(pcbuf, printing, ctxt, n, max)
   448  			}
   449  		}
   450  
   451  		waspanic = f.funcID == funcID_sigpanic
   452  
   453  		// Do not unwind past the bottom of the stack.
   454  		if !flr.valid() {
   455  			break
   456  		}
   457  
   458  		// Unwind to next frame.
   459  		frame.fn = flr
   460  		frame.pc = frame.lr
   461  		frame.lr = 0
   462  		frame.sp = frame.fp
   463  		frame.fp = 0
   464  		frame.argmap = nil
   465  
   466  		// On link register architectures, sighandler saves the LR on stack
   467  		// before faking a call to sigpanic.
   468  		if usesLR && waspanic {
   469  			x := *(*uintptr)(unsafe.Pointer(frame.sp))
   470  			frame.sp += sys.MinFrameSize
   471  			if GOARCH == "arm64" {
   472  				// arm64 needs 16-byte aligned SP, always
   473  				frame.sp += sys.PtrSize
   474  			}
   475  			f = findfunc(frame.pc)
   476  			frame.fn = f
   477  			if !f.valid() {
   478  				frame.pc = x
   479  			} else if funcspdelta(f, frame.pc, &cache) == 0 {
   480  				frame.lr = x
   481  			}
   482  		}
   483  	}
   484  
   485  	if printing {
   486  		n = nprint
   487  	}
   488  
   489  	// If callback != nil, we're being called to gather stack information during
   490  	// garbage collection or stack growth. In that context, require that we used
   491  	// up the entire defer stack. If not, then there is a bug somewhere and the
   492  	// garbage collection or stack growth may not have seen the correct picture
   493  	// of the stack. Crash now instead of silently executing the garbage collection
   494  	// or stack copy incorrectly and setting up for a mysterious crash later.
   495  	//
   496  	// Note that panic != nil is okay here: there can be leftover panics,
   497  	// because the defers on the panic stack do not nest in frame order as
   498  	// they do on the defer stack. If you have:
   499  	//
   500  	//	frame 1 defers d1
   501  	//	frame 2 defers d2
   502  	//	frame 3 defers d3
   503  	//	frame 4 panics
   504  	//	frame 4's panic starts running defers
   505  	//	frame 5, running d3, defers d4
   506  	//	frame 5 panics
   507  	//	frame 5's panic starts running defers
   508  	//	frame 6, running d4, garbage collects
   509  	//	frame 6, running d2, garbage collects
   510  	//
   511  	// During the execution of d4, the panic stack is d4 -> d3, which
   512  	// is nested properly, and we'll treat frame 3 as resumable, because we
   513  	// can find d3. (And in fact frame 3 is resumable. If d4 recovers
   514  	// and frame 5 continues running, d3, d3 can recover and we'll
   515  	// resume execution in (returning from) frame 3.)
   516  	//
   517  	// During the execution of d2, however, the panic stack is d2 -> d3,
   518  	// which is inverted. The scan will match d2 to frame 2 but having
   519  	// d2 on the stack until then means it will not match d3 to frame 3.
   520  	// This is okay: if we're running d2, then all the defers after d2 have
   521  	// completed and their corresponding frames are dead. Not finding d3
   522  	// for frame 3 means we'll set frame 3's continpc == 0, which is correct
   523  	// (frame 3 is dead). At the end of the walk the panic stack can thus
   524  	// contain defers (d3 in this case) for dead frames. The inversion here
   525  	// always indicates a dead frame, and the effect of the inversion on the
   526  	// scan is to hide those dead frames, so the scan is still okay:
   527  	// what's left on the panic stack are exactly (and only) the dead frames.
   528  	//
   529  	// We require callback != nil here because only when callback != nil
   530  	// do we know that gentraceback is being called in a "must be correct"
   531  	// context as opposed to a "best effort" context. The tracebacks with
   532  	// callbacks only happen when everything is stopped nicely.
   533  	// At other times, such as when gathering a stack for a profiling signal
   534  	// or when printing a traceback during a crash, everything may not be
   535  	// stopped nicely, and the stack walk may not be able to complete.
   536  	// It's okay in those situations not to use up the entire defer stack:
   537  	// incomplete information then is still better than nothing.
   538  	if callback != nil && n < max && _defer != nil {
   539  		if _defer != nil {
   540  			print("runtime: g", gp.goid, ": leftover defer sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
   541  		}
   542  		for _defer = gp._defer; _defer != nil; _defer = _defer.link {
   543  			print("\tdefer ", _defer, " sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
   544  		}
   545  		throw("traceback has leftover defers")
   546  	}
   547  
   548  	if callback != nil && n < max && frame.sp != gp.stktopsp {
   549  		print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n")
   550  		print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n")
   551  		throw("traceback did not unwind completely")
   552  	}
   553  
   554  	return n
   555  }
   556  
   557  // reflectMethodValue is a partial duplicate of reflect.makeFuncImpl
   558  // and reflect.methodValue.
   559  type reflectMethodValue struct {
   560  	fn     uintptr
   561  	stack  *bitvector // ptrmap for both args and results
   562  	argLen uintptr    // just args
   563  }
   564  
   565  // getArgInfoFast returns the argument frame information for a call to f.
   566  // It is short and inlineable. However, it does not handle all functions.
   567  // If ok reports false, you must call getArgInfo instead.
   568  // TODO(josharian): once we do mid-stack inlining,
   569  // call getArgInfo directly from getArgInfoFast and stop returning an ok bool.
   570  func getArgInfoFast(f funcInfo, needArgMap bool) (arglen uintptr, argmap *bitvector, ok bool) {
   571  	return uintptr(f.args), nil, !(needArgMap && f.args == _ArgsSizeUnknown)
   572  }
   573  
   574  // getArgInfo returns the argument frame information for a call to f
   575  // with call frame frame.
   576  //
   577  // This is used for both actual calls with active stack frames and for
   578  // deferred calls that are not yet executing. If this is an actual
   579  // call, ctxt must be nil (getArgInfo will retrieve what it needs from
   580  // the active stack frame). If this is a deferred call, ctxt must be
   581  // the function object that was deferred.
   582  func getArgInfo(frame *stkframe, f funcInfo, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) {
   583  	arglen = uintptr(f.args)
   584  	if needArgMap && f.args == _ArgsSizeUnknown {
   585  		// Extract argument bitmaps for reflect stubs from the calls they made to reflect.
   586  		switch funcname(f) {
   587  		case "reflect.makeFuncStub", "reflect.methodValueCall":
   588  			// These take a *reflect.methodValue as their
   589  			// context register.
   590  			var mv *reflectMethodValue
   591  			var retValid bool
   592  			if ctxt != nil {
   593  				// This is not an actual call, but a
   594  				// deferred call. The function value
   595  				// is itself the *reflect.methodValue.
   596  				mv = (*reflectMethodValue)(unsafe.Pointer(ctxt))
   597  			} else {
   598  				// This is a real call that took the
   599  				// *reflect.methodValue as its context
   600  				// register and immediately saved it
   601  				// to 0(SP). Get the methodValue from
   602  				// 0(SP).
   603  				arg0 := frame.sp + sys.MinFrameSize
   604  				mv = *(**reflectMethodValue)(unsafe.Pointer(arg0))
   605  				// Figure out whether the return values are valid.
   606  				// Reflect will update this value after it copies
   607  				// in the return values.
   608  				retValid = *(*bool)(unsafe.Pointer(arg0 + 3*sys.PtrSize))
   609  			}
   610  			if mv.fn != f.entry {
   611  				print("runtime: confused by ", funcname(f), "\n")
   612  				throw("reflect mismatch")
   613  			}
   614  			bv := mv.stack
   615  			arglen = uintptr(bv.n * sys.PtrSize)
   616  			if !retValid {
   617  				arglen = uintptr(mv.argLen) &^ (sys.PtrSize - 1)
   618  			}
   619  			argmap = bv
   620  		}
   621  	}
   622  	return
   623  }
   624  
   625  // tracebackCgoContext handles tracing back a cgo context value, from
   626  // the context argument to setCgoTraceback, for the gentraceback
   627  // function. It returns the new value of n.
   628  func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int {
   629  	var cgoPCs [32]uintptr
   630  	cgoContextPCs(ctxt, cgoPCs[:])
   631  	var arg cgoSymbolizerArg
   632  	anySymbolized := false
   633  	for _, pc := range cgoPCs {
   634  		if pc == 0 || n >= max {
   635  			break
   636  		}
   637  		if pcbuf != nil {
   638  			(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   639  		}
   640  		if printing {
   641  			if cgoSymbolizer == nil {
   642  				print("non-Go function at pc=", hex(pc), "\n")
   643  			} else {
   644  				c := printOneCgoTraceback(pc, max-n, &arg)
   645  				n += c - 1 // +1 a few lines down
   646  				anySymbolized = true
   647  			}
   648  		}
   649  		n++
   650  	}
   651  	if anySymbolized {
   652  		arg.pc = 0
   653  		callCgoSymbolizer(&arg)
   654  	}
   655  	return n
   656  }
   657  
   658  func printcreatedby(gp *g) {
   659  	// Show what created goroutine, except main goroutine (goid 1).
   660  	pc := gp.gopc
   661  	f := findfunc(pc)
   662  	if f.valid() && showframe(f, gp, false, false) && gp.goid != 1 {
   663  		printcreatedby1(f, pc)
   664  	}
   665  }
   666  
   667  func printcreatedby1(f funcInfo, pc uintptr) {
   668  	print("created by ", funcname(f), "\n")
   669  	tracepc := pc // back up to CALL instruction for funcline.
   670  	if pc > f.entry {
   671  		tracepc -= sys.PCQuantum
   672  	}
   673  	file, line := funcline(f, tracepc)
   674  	print("\t", file, ":", line)
   675  	if pc > f.entry {
   676  		print(" +", hex(pc-f.entry))
   677  	}
   678  	print("\n")
   679  }
   680  
   681  func traceback(pc, sp, lr uintptr, gp *g) {
   682  	traceback1(pc, sp, lr, gp, 0)
   683  }
   684  
   685  // tracebacktrap is like traceback but expects that the PC and SP were obtained
   686  // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
   687  // Because they are from a trap instead of from a saved pair,
   688  // the initial PC must not be rewound to the previous instruction.
   689  // (All the saved pairs record a PC that is a return address, so we
   690  // rewind it into the CALL instruction.)
   691  // If gp.m.libcall{g,pc,sp} information is available, it uses that information in preference to
   692  // the pc/sp/lr passed in.
   693  func tracebacktrap(pc, sp, lr uintptr, gp *g) {
   694  	if gp.m.libcallsp != 0 {
   695  		// We're in C code somewhere, traceback from the saved position.
   696  		traceback1(gp.m.libcallpc, gp.m.libcallsp, 0, gp.m.libcallg.ptr(), 0)
   697  		return
   698  	}
   699  	traceback1(pc, sp, lr, gp, _TraceTrap)
   700  }
   701  
   702  func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
   703  	// If the goroutine is in cgo, and we have a cgo traceback, print that.
   704  	if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
   705  		// Lock cgoCallers so that a signal handler won't
   706  		// change it, copy the array, reset it, unlock it.
   707  		// We are locked to the thread and are not running
   708  		// concurrently with a signal handler.
   709  		// We just have to stop a signal handler from interrupting
   710  		// in the middle of our copy.
   711  		atomic.Store(&gp.m.cgoCallersUse, 1)
   712  		cgoCallers := *gp.m.cgoCallers
   713  		gp.m.cgoCallers[0] = 0
   714  		atomic.Store(&gp.m.cgoCallersUse, 0)
   715  
   716  		printCgoTraceback(&cgoCallers)
   717  	}
   718  
   719  	var n int
   720  	if readgstatus(gp)&^_Gscan == _Gsyscall {
   721  		// Override registers if blocked in system call.
   722  		pc = gp.syscallpc
   723  		sp = gp.syscallsp
   724  		flags &^= _TraceTrap
   725  	}
   726  	// Print traceback. By default, omits runtime frames.
   727  	// If that means we print nothing at all, repeat forcing all frames printed.
   728  	n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
   729  	if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
   730  		n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
   731  	}
   732  	if n == _TracebackMaxFrames {
   733  		print("...additional frames elided...\n")
   734  	}
   735  	printcreatedby(gp)
   736  
   737  	if gp.ancestors == nil {
   738  		return
   739  	}
   740  	for _, ancestor := range *gp.ancestors {
   741  		printAncestorTraceback(ancestor)
   742  	}
   743  }
   744  
   745  // printAncestorTraceback prints the traceback of the given ancestor.
   746  // TODO: Unify this with gentraceback and CallersFrames.
   747  func printAncestorTraceback(ancestor ancestorInfo) {
   748  	print("[originating from goroutine ", ancestor.goid, "]:\n")
   749  	elideWrapper := false
   750  	for fidx, pc := range ancestor.pcs {
   751  		f := findfunc(pc) // f previously validated
   752  		if showfuncinfo(f, fidx == 0, elideWrapper && fidx != 0) {
   753  			elideWrapper = printAncestorTracebackFuncInfo(f, pc)
   754  		}
   755  	}
   756  	if len(ancestor.pcs) == _TracebackMaxFrames {
   757  		print("...additional frames elided...\n")
   758  	}
   759  	// Show what created goroutine, except main goroutine (goid 1).
   760  	f := findfunc(ancestor.gopc)
   761  	if f.valid() && showfuncinfo(f, false, false) && ancestor.goid != 1 {
   762  		printcreatedby1(f, ancestor.gopc)
   763  	}
   764  }
   765  
   766  // printAncestorTraceback prints the given function info at a given pc
   767  // within an ancestor traceback. The precision of this info is reduced
   768  // due to only have access to the pcs at the time of the caller
   769  // goroutine being created.
   770  func printAncestorTracebackFuncInfo(f funcInfo, pc uintptr) bool {
   771  	tracepc := pc // back up to CALL instruction for funcline.
   772  	if pc > f.entry {
   773  		tracepc -= sys.PCQuantum
   774  	}
   775  	file, line := funcline(f, tracepc)
   776  	inldata := funcdata(f, _FUNCDATA_InlTree)
   777  	if inldata != nil {
   778  		inltree := (*[1 << 20]inlinedCall)(inldata)
   779  		ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil)
   780  		for ix != -1 {
   781  			name := funcnameFromNameoff(f, inltree[ix].func_)
   782  			print(name, "(...)\n")
   783  			print("\t", file, ":", line, "\n")
   784  
   785  			file = funcfile(f, inltree[ix].file)
   786  			line = inltree[ix].line
   787  			ix = inltree[ix].parent
   788  		}
   789  	}
   790  	name := funcname(f)
   791  	if name == "runtime.gopanic" {
   792  		name = "panic"
   793  	}
   794  	print(name, "(...)\n")
   795  	print("\t", file, ":", line)
   796  	if pc > f.entry {
   797  		print(" +", hex(pc-f.entry))
   798  	}
   799  	print("\n")
   800  	return elideWrapperCalling(name)
   801  }
   802  
   803  func callers(skip int, pcbuf []uintptr) int {
   804  	sp := getcallersp()
   805  	pc := getcallerpc()
   806  	gp := getg()
   807  	var n int
   808  	systemstack(func() {
   809  		n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   810  	})
   811  	return n
   812  }
   813  
   814  func gcallers(gp *g, skip int, pcbuf []uintptr) int {
   815  	return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   816  }
   817  
   818  func showframe(f funcInfo, gp *g, firstFrame, elideWrapper bool) bool {
   819  	g := getg()
   820  	if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
   821  		return true
   822  	}
   823  	return showfuncinfo(f, firstFrame, elideWrapper)
   824  }
   825  
   826  func showfuncinfo(f funcInfo, firstFrame, elideWrapper bool) bool {
   827  	level, _, _ := gotraceback()
   828  	if level > 1 {
   829  		// Show all frames.
   830  		return true
   831  	}
   832  
   833  	if !f.valid() {
   834  		return false
   835  	}
   836  
   837  	if elideWrapper {
   838  		file, _ := funcline(f, f.entry)
   839  		if file == "<autogenerated>" {
   840  			return false
   841  		}
   842  	}
   843  
   844  	name := funcname(f)
   845  
   846  	// Special case: always show runtime.gopanic frame
   847  	// in the middle of a stack trace, so that we can
   848  	// see the boundary between ordinary code and
   849  	// panic-induced deferred code.
   850  	// See golang.org/issue/5832.
   851  	if name == "runtime.gopanic" && !firstFrame {
   852  		return true
   853  	}
   854  
   855  	return contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name))
   856  }
   857  
   858  // isExportedRuntime reports whether name is an exported runtime function.
   859  // It is only for runtime functions, so ASCII A-Z is fine.
   860  func isExportedRuntime(name string) bool {
   861  	const n = len("runtime.")
   862  	return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
   863  }
   864  
   865  // elideWrapperCalling returns whether a wrapper function that called
   866  // function "name" should be elided from stack traces.
   867  func elideWrapperCalling(name string) bool {
   868  	// If the wrapper called a panic function instead of the
   869  	// wrapped function, we want to include it in stacks.
   870  	return !(name == "runtime.gopanic" || name == "runtime.sigpanic" || name == "runtime.panicwrap")
   871  }
   872  
   873  var gStatusStrings = [...]string{
   874  	_Gidle:      "idle",
   875  	_Grunnable:  "runnable",
   876  	_Grunning:   "running",
   877  	_Gsyscall:   "syscall",
   878  	_Gwaiting:   "waiting",
   879  	_Gdead:      "dead",
   880  	_Gcopystack: "copystack",
   881  }
   882  
   883  func goroutineheader(gp *g) {
   884  	gpstatus := readgstatus(gp)
   885  
   886  	isScan := gpstatus&_Gscan != 0
   887  	gpstatus &^= _Gscan // drop the scan bit
   888  
   889  	// Basic string status
   890  	var status string
   891  	if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
   892  		status = gStatusStrings[gpstatus]
   893  	} else {
   894  		status = "???"
   895  	}
   896  
   897  	// Override.
   898  	if gpstatus == _Gwaiting && gp.waitreason != waitReasonZero {
   899  		status = gp.waitreason.String()
   900  	}
   901  
   902  	// approx time the G is blocked, in minutes
   903  	var waitfor int64
   904  	if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
   905  		waitfor = (nanotime() - gp.waitsince) / 60e9
   906  	}
   907  	print("goroutine ", gp.goid, " [", status)
   908  	if isScan {
   909  		print(" (scan)")
   910  	}
   911  	if waitfor >= 1 {
   912  		print(", ", waitfor, " minutes")
   913  	}
   914  	if gp.lockedm != 0 {
   915  		print(", locked to thread")
   916  	}
   917  	print("]:\n")
   918  }
   919  
   920  func tracebackothers(me *g) {
   921  	level, _, _ := gotraceback()
   922  
   923  	// Show the current goroutine first, if we haven't already.
   924  	g := getg()
   925  	gp := g.m.curg
   926  	if gp != nil && gp != me {
   927  		print("\n")
   928  		goroutineheader(gp)
   929  		traceback(^uintptr(0), ^uintptr(0), 0, gp)
   930  	}
   931  
   932  	lock(&allglock)
   933  	for _, gp := range allgs {
   934  		if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 {
   935  			continue
   936  		}
   937  		print("\n")
   938  		goroutineheader(gp)
   939  		// Note: gp.m == g.m occurs when tracebackothers is
   940  		// called from a signal handler initiated during a
   941  		// systemstack call. The original G is still in the
   942  		// running state, and we want to print its stack.
   943  		if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning {
   944  			print("\tgoroutine running on other thread; stack unavailable\n")
   945  			printcreatedby(gp)
   946  		} else {
   947  			traceback(^uintptr(0), ^uintptr(0), 0, gp)
   948  		}
   949  	}
   950  	unlock(&allglock)
   951  }
   952  
   953  // tracebackHexdump hexdumps part of stk around frame.sp and frame.fp
   954  // for debugging purposes. If the address bad is included in the
   955  // hexdumped range, it will mark it as well.
   956  func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) {
   957  	const expand = 32 * sys.PtrSize
   958  	const maxExpand = 256 * sys.PtrSize
   959  	// Start around frame.sp.
   960  	lo, hi := frame.sp, frame.sp
   961  	// Expand to include frame.fp.
   962  	if frame.fp != 0 && frame.fp < lo {
   963  		lo = frame.fp
   964  	}
   965  	if frame.fp != 0 && frame.fp > hi {
   966  		hi = frame.fp
   967  	}
   968  	// Expand a bit more.
   969  	lo, hi = lo-expand, hi+expand
   970  	// But don't go too far from frame.sp.
   971  	if lo < frame.sp-maxExpand {
   972  		lo = frame.sp - maxExpand
   973  	}
   974  	if hi > frame.sp+maxExpand {
   975  		hi = frame.sp + maxExpand
   976  	}
   977  	// And don't go outside the stack bounds.
   978  	if lo < stk.lo {
   979  		lo = stk.lo
   980  	}
   981  	if hi > stk.hi {
   982  		hi = stk.hi
   983  	}
   984  
   985  	// Print the hex dump.
   986  	print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n")
   987  	hexdumpWords(lo, hi, func(p uintptr) byte {
   988  		switch p {
   989  		case frame.fp:
   990  			return '>'
   991  		case frame.sp:
   992  			return '<'
   993  		case bad:
   994  			return '!'
   995  		}
   996  		return 0
   997  	})
   998  }
   999  
  1000  // Does f mark the top of a goroutine stack?
  1001  func topofstack(f funcInfo, g0 bool) bool {
  1002  	return f.funcID == funcID_goexit ||
  1003  		f.funcID == funcID_mstart ||
  1004  		f.funcID == funcID_mcall ||
  1005  		f.funcID == funcID_morestack ||
  1006  		f.funcID == funcID_rt0_go ||
  1007  		f.funcID == funcID_externalthreadhandler ||
  1008  		// asmcgocall is TOS on the system stack because it
  1009  		// switches to the system stack, but in this case we
  1010  		// can come back to the regular stack and still want
  1011  		// to be able to unwind through the call that appeared
  1012  		// on the regular stack.
  1013  		(g0 && f.funcID == funcID_asmcgocall)
  1014  }
  1015  
  1016  // isSystemGoroutine reports whether the goroutine g must be omitted
  1017  // in stack dumps and deadlock detector. This is any goroutine that
  1018  // starts at a runtime.* entry point, except for runtime.main and
  1019  // sometimes runtime.runfinq.
  1020  func isSystemGoroutine(gp *g) bool {
  1021  	// Keep this in sync with cmd/trace/trace.go:isSystemGoroutine.
  1022  	f := findfunc(gp.startpc)
  1023  	if !f.valid() {
  1024  		return false
  1025  	}
  1026  	if f.funcID == funcID_runtime_main {
  1027  		return false
  1028  	}
  1029  	if f.funcID == funcID_runfinq {
  1030  		// We include the finalizer goroutine if it's calling
  1031  		// back into user code.
  1032  		return !fingRunning
  1033  	}
  1034  	return hasprefix(funcname(f), "runtime.")
  1035  }
  1036  
  1037  // SetCgoTraceback records three C functions to use to gather
  1038  // traceback information from C code and to convert that traceback
  1039  // information into symbolic information. These are used when printing
  1040  // stack traces for a program that uses cgo.
  1041  //
  1042  // The traceback and context functions may be called from a signal
  1043  // handler, and must therefore use only async-signal safe functions.
  1044  // The symbolizer function may be called while the program is
  1045  // crashing, and so must be cautious about using memory.  None of the
  1046  // functions may call back into Go.
  1047  //
  1048  // The context function will be called with a single argument, a
  1049  // pointer to a struct:
  1050  //
  1051  //	struct {
  1052  //		Context uintptr
  1053  //	}
  1054  //
  1055  // In C syntax, this struct will be
  1056  //
  1057  //	struct {
  1058  //		uintptr_t Context;
  1059  //	};
  1060  //
  1061  // If the Context field is 0, the context function is being called to
  1062  // record the current traceback context. It should record in the
  1063  // Context field whatever information is needed about the current
  1064  // point of execution to later produce a stack trace, probably the
  1065  // stack pointer and PC. In this case the context function will be
  1066  // called from C code.
  1067  //
  1068  // If the Context field is not 0, then it is a value returned by a
  1069  // previous call to the context function. This case is called when the
  1070  // context is no longer needed; that is, when the Go code is returning
  1071  // to its C code caller. This permits the context function to release
  1072  // any associated resources.
  1073  //
  1074  // While it would be correct for the context function to record a
  1075  // complete a stack trace whenever it is called, and simply copy that
  1076  // out in the traceback function, in a typical program the context
  1077  // function will be called many times without ever recording a
  1078  // traceback for that context. Recording a complete stack trace in a
  1079  // call to the context function is likely to be inefficient.
  1080  //
  1081  // The traceback function will be called with a single argument, a
  1082  // pointer to a struct:
  1083  //
  1084  //	struct {
  1085  //		Context    uintptr
  1086  //		SigContext uintptr
  1087  //		Buf        *uintptr
  1088  //		Max        uintptr
  1089  //	}
  1090  //
  1091  // In C syntax, this struct will be
  1092  //
  1093  //	struct {
  1094  //		uintptr_t  Context;
  1095  //		uintptr_t  SigContext;
  1096  //		uintptr_t* Buf;
  1097  //		uintptr_t  Max;
  1098  //	};
  1099  //
  1100  // The Context field will be zero to gather a traceback from the
  1101  // current program execution point. In this case, the traceback
  1102  // function will be called from C code.
  1103  //
  1104  // Otherwise Context will be a value previously returned by a call to
  1105  // the context function. The traceback function should gather a stack
  1106  // trace from that saved point in the program execution. The traceback
  1107  // function may be called from an execution thread other than the one
  1108  // that recorded the context, but only when the context is known to be
  1109  // valid and unchanging. The traceback function may also be called
  1110  // deeper in the call stack on the same thread that recorded the
  1111  // context. The traceback function may be called multiple times with
  1112  // the same Context value; it will usually be appropriate to cache the
  1113  // result, if possible, the first time this is called for a specific
  1114  // context value.
  1115  //
  1116  // If the traceback function is called from a signal handler on a Unix
  1117  // system, SigContext will be the signal context argument passed to
  1118  // the signal handler (a C ucontext_t* cast to uintptr_t). This may be
  1119  // used to start tracing at the point where the signal occurred. If
  1120  // the traceback function is not called from a signal handler,
  1121  // SigContext will be zero.
  1122  //
  1123  // Buf is where the traceback information should be stored. It should
  1124  // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
  1125  // the PC of that function's caller, and so on.  Max is the maximum
  1126  // number of entries to store.  The function should store a zero to
  1127  // indicate the top of the stack, or that the caller is on a different
  1128  // stack, presumably a Go stack.
  1129  //
  1130  // Unlike runtime.Callers, the PC values returned should, when passed
  1131  // to the symbolizer function, return the file/line of the call
  1132  // instruction.  No additional subtraction is required or appropriate.
  1133  //
  1134  // On all platforms, the traceback function is invoked when a call from
  1135  // Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le,
  1136  // and freebsd/amd64, the traceback function is also invoked when a
  1137  // signal is received by a thread that is executing a cgo call. The
  1138  // traceback function should not make assumptions about when it is
  1139  // called, as future versions of Go may make additional calls.
  1140  //
  1141  // The symbolizer function will be called with a single argument, a
  1142  // pointer to a struct:
  1143  //
  1144  //	struct {
  1145  //		PC      uintptr // program counter to fetch information for
  1146  //		File    *byte   // file name (NUL terminated)
  1147  //		Lineno  uintptr // line number
  1148  //		Func    *byte   // function name (NUL terminated)
  1149  //		Entry   uintptr // function entry point
  1150  //		More    uintptr // set non-zero if more info for this PC
  1151  //		Data    uintptr // unused by runtime, available for function
  1152  //	}
  1153  //
  1154  // In C syntax, this struct will be
  1155  //
  1156  //	struct {
  1157  //		uintptr_t PC;
  1158  //		char*     File;
  1159  //		uintptr_t Lineno;
  1160  //		char*     Func;
  1161  //		uintptr_t Entry;
  1162  //		uintptr_t More;
  1163  //		uintptr_t Data;
  1164  //	};
  1165  //
  1166  // The PC field will be a value returned by a call to the traceback
  1167  // function.
  1168  //
  1169  // The first time the function is called for a particular traceback,
  1170  // all the fields except PC will be 0. The function should fill in the
  1171  // other fields if possible, setting them to 0/nil if the information
  1172  // is not available. The Data field may be used to store any useful
  1173  // information across calls. The More field should be set to non-zero
  1174  // if there is more information for this PC, zero otherwise. If More
  1175  // is set non-zero, the function will be called again with the same
  1176  // PC, and may return different information (this is intended for use
  1177  // with inlined functions). If More is zero, the function will be
  1178  // called with the next PC value in the traceback. When the traceback
  1179  // is complete, the function will be called once more with PC set to
  1180  // zero; this may be used to free any information. Each call will
  1181  // leave the fields of the struct set to the same values they had upon
  1182  // return, except for the PC field when the More field is zero. The
  1183  // function must not keep a copy of the struct pointer between calls.
  1184  //
  1185  // When calling SetCgoTraceback, the version argument is the version
  1186  // number of the structs that the functions expect to receive.
  1187  // Currently this must be zero.
  1188  //
  1189  // The symbolizer function may be nil, in which case the results of
  1190  // the traceback function will be displayed as numbers. If the
  1191  // traceback function is nil, the symbolizer function will never be
  1192  // called. The context function may be nil, in which case the
  1193  // traceback function will only be called with the context field set
  1194  // to zero.  If the context function is nil, then calls from Go to C
  1195  // to Go will not show a traceback for the C portion of the call stack.
  1196  //
  1197  // SetCgoTraceback should be called only once, ideally from an init function.
  1198  func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
  1199  	if version != 0 {
  1200  		panic("unsupported version")
  1201  	}
  1202  
  1203  	if cgoTraceback != nil && cgoTraceback != traceback ||
  1204  		cgoContext != nil && cgoContext != context ||
  1205  		cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
  1206  		panic("call SetCgoTraceback only once")
  1207  	}
  1208  
  1209  	cgoTraceback = traceback
  1210  	cgoContext = context
  1211  	cgoSymbolizer = symbolizer
  1212  
  1213  	// The context function is called when a C function calls a Go
  1214  	// function. As such it is only called by C code in runtime/cgo.
  1215  	if _cgo_set_context_function != nil {
  1216  		cgocall(_cgo_set_context_function, context)
  1217  	}
  1218  }
  1219  
  1220  var cgoTraceback unsafe.Pointer
  1221  var cgoContext unsafe.Pointer
  1222  var cgoSymbolizer unsafe.Pointer
  1223  
  1224  // cgoTracebackArg is the type passed to cgoTraceback.
  1225  type cgoTracebackArg struct {
  1226  	context    uintptr
  1227  	sigContext uintptr
  1228  	buf        *uintptr
  1229  	max        uintptr
  1230  }
  1231  
  1232  // cgoContextArg is the type passed to the context function.
  1233  type cgoContextArg struct {
  1234  	context uintptr
  1235  }
  1236  
  1237  // cgoSymbolizerArg is the type passed to cgoSymbolizer.
  1238  type cgoSymbolizerArg struct {
  1239  	pc       uintptr
  1240  	file     *byte
  1241  	lineno   uintptr
  1242  	funcName *byte
  1243  	entry    uintptr
  1244  	more     uintptr
  1245  	data     uintptr
  1246  }
  1247  
  1248  // cgoTraceback prints a traceback of callers.
  1249  func printCgoTraceback(callers *cgoCallers) {
  1250  	if cgoSymbolizer == nil {
  1251  		for _, c := range callers {
  1252  			if c == 0 {
  1253  				break
  1254  			}
  1255  			print("non-Go function at pc=", hex(c), "\n")
  1256  		}
  1257  		return
  1258  	}
  1259  
  1260  	var arg cgoSymbolizerArg
  1261  	for _, c := range callers {
  1262  		if c == 0 {
  1263  			break
  1264  		}
  1265  		printOneCgoTraceback(c, 0x7fffffff, &arg)
  1266  	}
  1267  	arg.pc = 0
  1268  	callCgoSymbolizer(&arg)
  1269  }
  1270  
  1271  // printOneCgoTraceback prints the traceback of a single cgo caller.
  1272  // This can print more than one line because of inlining.
  1273  // Returns the number of frames printed.
  1274  func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
  1275  	c := 0
  1276  	arg.pc = pc
  1277  	for {
  1278  		if c > max {
  1279  			break
  1280  		}
  1281  		callCgoSymbolizer(arg)
  1282  		if arg.funcName != nil {
  1283  			// Note that we don't print any argument
  1284  			// information here, not even parentheses.
  1285  			// The symbolizer must add that if appropriate.
  1286  			println(gostringnocopy(arg.funcName))
  1287  		} else {
  1288  			println("non-Go function")
  1289  		}
  1290  		print("\t")
  1291  		if arg.file != nil {
  1292  			print(gostringnocopy(arg.file), ":", arg.lineno, " ")
  1293  		}
  1294  		print("pc=", hex(pc), "\n")
  1295  		c++
  1296  		if arg.more == 0 {
  1297  			break
  1298  		}
  1299  	}
  1300  	return c
  1301  }
  1302  
  1303  // callCgoSymbolizer calls the cgoSymbolizer function.
  1304  func callCgoSymbolizer(arg *cgoSymbolizerArg) {
  1305  	call := cgocall
  1306  	if panicking > 0 || getg().m.curg != getg() {
  1307  		// We do not want to call into the scheduler when panicking
  1308  		// or when on the system stack.
  1309  		call = asmcgocall
  1310  	}
  1311  	if msanenabled {
  1312  		msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
  1313  	}
  1314  	call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
  1315  }
  1316  
  1317  // cgoContextPCs gets the PC values from a cgo traceback.
  1318  func cgoContextPCs(ctxt uintptr, buf []uintptr) {
  1319  	if cgoTraceback == nil {
  1320  		return
  1321  	}
  1322  	call := cgocall
  1323  	if panicking > 0 || getg().m.curg != getg() {
  1324  		// We do not want to call into the scheduler when panicking
  1325  		// or when on the system stack.
  1326  		call = asmcgocall
  1327  	}
  1328  	arg := cgoTracebackArg{
  1329  		context: ctxt,
  1330  		buf:     (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
  1331  		max:     uintptr(len(buf)),
  1332  	}
  1333  	if msanenabled {
  1334  		msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
  1335  	}
  1336  	call(cgoTraceback, noescape(unsafe.Pointer(&arg)))
  1337  }
  1338  

View as plain text