github.com/4ad/go@v0.0.0-20161219182952-69a12818b605/src/runtime/traceback.go (about)

     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  const returnAddrOffset = sys.GoarchSparc64 * 120
    39  
    40  var (
    41  	// initialized in tracebackinit
    42  	goexitPC             uintptr
    43  	jmpdeferPC           uintptr
    44  	mcallPC              uintptr
    45  	morestackPC          uintptr
    46  	mstartPC             uintptr
    47  	rt0_goPC             uintptr
    48  	sigpanicPC           uintptr
    49  	runfinqPC            uintptr
    50  	bgsweepPC            uintptr
    51  	forcegchelperPC      uintptr
    52  	timerprocPC          uintptr
    53  	gcBgMarkWorkerPC     uintptr
    54  	systemstack_switchPC uintptr
    55  	systemstackPC        uintptr
    56  	stackBarrierPC       uintptr
    57  	cgocallback_gofuncPC uintptr
    58  
    59  	gogoPC uintptr
    60  
    61  	externalthreadhandlerp uintptr // initialized elsewhere
    62  )
    63  
    64  func tracebackinit() {
    65  	// Go variable initialization happens late during runtime startup.
    66  	// Instead of initializing the variables above in the declarations,
    67  	// schedinit calls this function so that the variables are
    68  	// initialized and available earlier in the startup sequence.
    69  	goexitPC = funcPC(goexit)
    70  	jmpdeferPC = funcPC(jmpdefer)
    71  	mcallPC = funcPC(mcall)
    72  	morestackPC = funcPC(morestack)
    73  	mstartPC = funcPC(mstart)
    74  	rt0_goPC = funcPC(rt0_go)
    75  	sigpanicPC = funcPC(sigpanic)
    76  	runfinqPC = funcPC(runfinq)
    77  	bgsweepPC = funcPC(bgsweep)
    78  	forcegchelperPC = funcPC(forcegchelper)
    79  	timerprocPC = funcPC(timerproc)
    80  	gcBgMarkWorkerPC = funcPC(gcBgMarkWorker)
    81  	systemstack_switchPC = funcPC(systemstack_switch)
    82  	systemstackPC = funcPC(systemstack)
    83  	stackBarrierPC = funcPC(stackBarrier)
    84  	cgocallback_gofuncPC = funcPC(cgocallback_gofunc)
    85  
    86  	// used by sigprof handler
    87  	gogoPC = funcPC(gogo)
    88  }
    89  
    90  // Traceback over the deferred function calls.
    91  // Report them like calls that have been invoked but not started executing yet.
    92  func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) {
    93  	var frame stkframe
    94  	for d := gp._defer; d != nil; d = d.link {
    95  		fn := d.fn
    96  		if fn == nil {
    97  			// Defer of nil function. Args don't matter.
    98  			frame.pc = 0
    99  			frame.fn = nil
   100  			frame.argp = 0
   101  			frame.arglen = 0
   102  			frame.argmap = nil
   103  		} else {
   104  			frame.pc = fn.fn
   105  			f := findfunc(frame.pc)
   106  			if f == nil {
   107  				print("runtime: unknown pc in defer ", hex(frame.pc), "\n")
   108  				throw("unknown pc")
   109  			}
   110  			frame.fn = f
   111  			frame.argp = uintptr(deferArgs(d))
   112  			frame.arglen, frame.argmap = getArgInfo(&frame, f, true)
   113  		}
   114  		frame.continpc = frame.pc
   115  		if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
   116  			return
   117  		}
   118  	}
   119  }
   120  
   121  // Generic traceback. Handles runtime stack prints (pcbuf == nil),
   122  // the runtime.Callers function (pcbuf != nil), as well as the garbage
   123  // collector (callback != nil).  A little clunky to merge these, but avoids
   124  // duplicating the code and all its subtlety.
   125  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 {
   126  	if goexitPC == 0 {
   127  		throw("gentraceback before goexitPC initialization")
   128  	}
   129  	g := getg()
   130  	if g == gp && g == g.m.curg {
   131  		// The starting sp has been passed in as a uintptr, and the caller may
   132  		// have other uintptr-typed stack references as well.
   133  		// If during one of the calls that got us here or during one of the
   134  		// callbacks below the stack must be grown, all these uintptr references
   135  		// to the stack will not be updated, and gentraceback will continue
   136  		// to inspect the old stack memory, which may no longer be valid.
   137  		// Even if all the variables were updated correctly, it is not clear that
   138  		// we want to expose a traceback that begins on one stack and ends
   139  		// on another stack. That could confuse callers quite a bit.
   140  		// Instead, we require that gentraceback and any other function that
   141  		// accepts an sp for the current goroutine (typically obtained by
   142  		// calling getcallersp) must not run on that goroutine's stack but
   143  		// instead on the g0 stack.
   144  		throw("gentraceback cannot trace user goroutine on its own stack")
   145  	}
   146  	level, _, _ := gotraceback()
   147  
   148  	// Fix up returns to the stack barrier by fetching the
   149  	// original return PC from gp.stkbar.
   150  	stkbarG := gp
   151  	stkbar := stkbarG.stkbar[stkbarG.stkbarPos:]
   152  
   153  	if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
   154  		if gp.syscallsp != 0 {
   155  			pc0 = gp.syscallpc
   156  			sp0 = gp.syscallsp
   157  			if usesLR {
   158  				lr0 = 0
   159  			}
   160  		} else {
   161  			pc0 = gp.sched.pc
   162  			sp0 = gp.sched.sp
   163  			if usesLR {
   164  				lr0 = gp.sched.lr
   165  			}
   166  		}
   167  	}
   168  
   169  	nprint := 0
   170  	var frame stkframe
   171  	frame.pc = pc0
   172  	frame.sp = sp0
   173  	if usesLR {
   174  		frame.lr = lr0
   175  	}
   176  	waspanic := false
   177  	cgoCtxt := gp.cgoCtxt
   178  	printing := pcbuf == nil && callback == nil
   179  	_defer := gp._defer
   180  
   181  	for _defer != nil && _defer.sp == _NoArgs {
   182  		_defer = _defer.link
   183  	}
   184  
   185  	// If the PC is zero, it's likely a nil function call.
   186  	// Start in the caller's frame.
   187  	if frame.pc == 0 {
   188  		if usesLR {
   189  			frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp + returnAddrOffset))
   190  			frame.lr = 0
   191  		} else {
   192  			frame.pc = uintptr(*(*sys.Uintreg)(unsafe.Pointer(frame.sp)))
   193  			frame.sp += sys.RegSize
   194  		}
   195  	}
   196  
   197  	f := findfunc(frame.pc)
   198  	if f != nil && f.entry == stackBarrierPC {
   199  		// We got caught in the middle of a stack barrier
   200  		// (presumably by a signal), so stkbar may be
   201  		// inconsistent with the barriers on the stack.
   202  		// Simulate the completion of the barrier.
   203  		//
   204  		// On x86, SP will be exactly one word above
   205  		// savedLRPtr. On LR machines, SP will be above
   206  		// savedLRPtr by some frame size.
   207  		var stkbarPos uintptr
   208  		if len(stkbar) > 0 && stkbar[0].savedLRPtr < sp0 {
   209  			// stackBarrier has not incremented stkbarPos.
   210  			stkbarPos = gp.stkbarPos
   211  		} else if gp.stkbarPos > 0 && gp.stkbar[gp.stkbarPos-1].savedLRPtr < sp0 {
   212  			// stackBarrier has incremented stkbarPos.
   213  			stkbarPos = gp.stkbarPos - 1
   214  		} else {
   215  			printlock()
   216  			print("runtime: failed to unwind through stackBarrier at SP ", hex(sp0), "; ")
   217  			gcPrintStkbars(gp, int(gp.stkbarPos))
   218  			print("\n")
   219  			throw("inconsistent state in stackBarrier")
   220  		}
   221  
   222  		frame.pc = gp.stkbar[stkbarPos].savedLRVal
   223  		stkbar = gp.stkbar[stkbarPos+1:]
   224  		f = findfunc(frame.pc)
   225  	}
   226  	if f == nil {
   227  		if callback != nil {
   228  			print("runtime: unknown pc ", hex(frame.pc), "\n")
   229  			throw("unknown pc")
   230  		}
   231  		return 0
   232  	}
   233  	frame.fn = f
   234  
   235  	var cache pcvalueCache
   236  
   237  	n := 0
   238  	for n < max {
   239  		// Typically:
   240  		//	pc is the PC of the running function.
   241  		//	sp is the stack pointer at that program counter.
   242  		//	fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
   243  		//	stk is the stack containing sp.
   244  		//	The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
   245  		f = frame.fn
   246  		if f.pcsp == 0 {
   247  			// No frame information, must be external function, like race support.
   248  			// See golang.org/issue/13568.
   249  			break
   250  		}
   251  
   252  		// Found an actual function.
   253  		// Derive frame pointer and link register.
   254  		if frame.fp == 0 {
   255  			// We want to jump over the systemstack switch. If we're running on the
   256  			// g0, this systemstack is at the top of the stack.
   257  			// if we're not on g0 or there's a no curg, then this is a regular call.
   258  			sp := frame.sp
   259  			if flags&_TraceJumpStack != 0 && f.entry == systemstackPC && gp == g.m.g0 && gp.m.curg != nil {
   260  				sp = gp.m.curg.sched.sp
   261  				frame.sp = sp
   262  				stkbarG = gp.m.curg
   263  				stkbar = stkbarG.stkbar[stkbarG.stkbarPos:]
   264  				cgoCtxt = gp.m.curg.cgoCtxt
   265  			}
   266  			frame.fp = sp + uintptr(funcspdelta(f, frame.pc, &cache))
   267  			if !usesLR {
   268  				// On x86, call instruction pushes return PC before entering new function.
   269  				frame.fp += sys.RegSize
   270  			}
   271  		}
   272  		var flr *_func
   273  		if topofstack(f) {
   274  			frame.lr = 0
   275  			flr = nil
   276  		} else if usesLR && f.entry == jmpdeferPC {
   277  			// jmpdefer modifies SP/LR/PC non-atomically.
   278  			// If a profiling interrupt arrives during jmpdefer,
   279  			// the stack unwind may see a mismatched register set
   280  			// and get confused. Stop if we see PC within jmpdefer
   281  			// to avoid that confusion.
   282  			// See golang.org/issue/8153.
   283  			if callback != nil {
   284  				throw("traceback_arm: found jmpdefer when tracing with callback")
   285  			}
   286  			frame.lr = 0
   287  		} else {
   288  			var lrPtr uintptr
   289  			if usesLR {
   290  				if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
   291  					lrPtr = frame.sp + returnAddrOffset
   292  					frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
   293  				}
   294  			} else {
   295  				if frame.lr == 0 {
   296  					lrPtr = frame.fp - sys.RegSize
   297  					frame.lr = uintptr(*(*sys.Uintreg)(unsafe.Pointer(lrPtr)))
   298  				}
   299  			}
   300  			if frame.lr == stackBarrierPC {
   301  				// Recover original PC.
   302  				if len(stkbar) == 0 || stkbar[0].savedLRPtr != lrPtr {
   303  					print("found next stack barrier at ", hex(lrPtr), "; expected ")
   304  					gcPrintStkbars(stkbarG, len(stkbarG.stkbar)-len(stkbar))
   305  					print("\n")
   306  					throw("missed stack barrier")
   307  				}
   308  				frame.lr = stkbar[0].savedLRVal
   309  				stkbar = stkbar[1:]
   310  			}
   311  			flr = findfunc(frame.lr)
   312  			if flr == nil {
   313  				// This happens if you get a profiling interrupt at just the wrong time.
   314  				// In that context it is okay to stop early.
   315  				// But if callback is set, we're doing a garbage collection and must
   316  				// get everything, so crash loudly.
   317  				if callback != nil {
   318  					print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
   319  					throw("unknown caller pc")
   320  				}
   321  			}
   322  		}
   323  
   324  		frame.varp = frame.fp
   325  		if !usesLR {
   326  			// On x86, call instruction pushes return PC before entering new function.
   327  			frame.varp -= sys.RegSize
   328  		}
   329  
   330  		// If framepointer_enabled and there's a frame, then
   331  		// there's a saved bp here.
   332  		if framepointer_enabled && GOARCH == "amd64" && frame.varp > frame.sp {
   333  			frame.varp -= sys.RegSize
   334  		}
   335  
   336  		// Derive size of arguments.
   337  		// Most functions have a fixed-size argument block,
   338  		// so we can use metadata about the function f.
   339  		// Not all, though: there are some variadic functions
   340  		// in package runtime and reflect, and for those we use call-specific
   341  		// metadata recorded by f's caller.
   342  		if callback != nil || printing {
   343  			frame.argp = frame.fp + sys.MinFrameSize
   344  			frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil)
   345  		}
   346  
   347  		// Determine frame's 'continuation PC', where it can continue.
   348  		// Normally this is the return address on the stack, but if sigpanic
   349  		// is immediately below this function on the stack, then the frame
   350  		// stopped executing due to a trap, and frame.pc is probably not
   351  		// a safe point for looking up liveness information. In this panicking case,
   352  		// the function either doesn't return at all (if it has no defers or if the
   353  		// defers do not recover) or it returns from one of the calls to
   354  		// deferproc a second time (if the corresponding deferred func recovers).
   355  		// It suffices to assume that the most recent deferproc is the one that
   356  		// returns; everything live at earlier deferprocs is still live at that one.
   357  		frame.continpc = frame.pc
   358  		if waspanic {
   359  			if _defer != nil && _defer.sp == frame.sp {
   360  				frame.continpc = _defer.pc
   361  			} else {
   362  				frame.continpc = 0
   363  			}
   364  		}
   365  
   366  		// Unwind our local defer stack past this frame.
   367  		for _defer != nil && (_defer.sp == frame.sp || _defer.sp == _NoArgs) {
   368  			_defer = _defer.link
   369  		}
   370  
   371  		if skip > 0 {
   372  			skip--
   373  			goto skipped
   374  		}
   375  
   376  		if pcbuf != nil {
   377  			(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc
   378  		}
   379  		if callback != nil {
   380  			if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
   381  				return n
   382  			}
   383  		}
   384  		if printing {
   385  			if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp) {
   386  				// Print during crash.
   387  				//	main(0x1, 0x2, 0x3)
   388  				//		/home/rsc/go/src/runtime/x.go:23 +0xf
   389  				//
   390  				tracepc := frame.pc // back up to CALL instruction for funcline.
   391  				// SPARC64's PC holds the address of the *current* 
   392  				// instruction, so it doesn't need this.
   393  				if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic && sys.GoarchSparc64 == 0 {
   394  					tracepc--
   395  				}
   396  				name := funcname(f)
   397  				if name == "runtime.gopanic" {
   398  					name = "panic"
   399  				}
   400  				print(name, "(")
   401  				argp := (*[100]uintptr)(unsafe.Pointer(frame.argp))
   402  				for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ {
   403  					if i >= 10 {
   404  						print(", ...")
   405  						break
   406  					}
   407  					if i != 0 {
   408  						print(", ")
   409  					}
   410  					print(hex(argp[i]))
   411  				}
   412  				print(")\n")
   413  				file, line := funcline(f, tracepc)
   414  				print("\t", file, ":", line)
   415  				if frame.pc > f.entry {
   416  					print(" +", hex(frame.pc-f.entry))
   417  				}
   418  				if g.m.throwing > 0 && gp == g.m.curg || level >= 2 {
   419  					print(" fp=", hex(frame.fp), " sp=", hex(frame.sp))
   420  				}
   421  				print("\n")
   422  				nprint++
   423  			}
   424  		}
   425  		n++
   426  
   427  	skipped:
   428  		if f.entry == cgocallback_gofuncPC && len(cgoCtxt) > 0 {
   429  			ctxt := cgoCtxt[len(cgoCtxt)-1]
   430  			cgoCtxt = cgoCtxt[:len(cgoCtxt)-1]
   431  
   432  			// skip only applies to Go frames.
   433  			// callback != nil only used when we only care
   434  			// about Go frames.
   435  			if skip == 0 && callback == nil {
   436  				n = tracebackCgoContext(pcbuf, printing, ctxt, n, max)
   437  			}
   438  		}
   439  
   440  		waspanic = f.entry == sigpanicPC
   441  
   442  		// Do not unwind past the bottom of the stack.
   443  		if flr == nil {
   444  			break
   445  		}
   446  
   447  		// Unwind to next frame.
   448  		frame.fn = flr
   449  		frame.pc = frame.lr
   450  		frame.lr = 0
   451  		frame.sp = frame.fp
   452  		frame.fp = 0
   453  		frame.argmap = nil
   454  
   455  		// On link register architectures, sighandler saves the LR on stack
   456  		// before faking a call to sigpanic.
   457  		if usesLR && waspanic {
   458  			x := *(*uintptr)(unsafe.Pointer(frame.sp + returnAddrOffset))
   459  			frame.sp += sys.MinFrameSize
   460  			if GOARCH == "arm64" {
   461  				// arm64 needs 16-byte aligned SP, always
   462  				frame.sp += sys.PtrSize
   463  			}
   464  			f = findfunc(frame.pc)
   465  			frame.fn = f
   466  			if f == nil {
   467  				frame.pc = x
   468  			} else if funcspdelta(f, frame.pc, &cache) == 0 {
   469  				frame.lr = x
   470  			}
   471  		}
   472  	}
   473  
   474  	if printing {
   475  		n = nprint
   476  	}
   477  
   478  	// If callback != nil, we're being called to gather stack information during
   479  	// garbage collection or stack growth. In that context, require that we used
   480  	// up the entire defer stack. If not, then there is a bug somewhere and the
   481  	// garbage collection or stack growth may not have seen the correct picture
   482  	// of the stack. Crash now instead of silently executing the garbage collection
   483  	// or stack copy incorrectly and setting up for a mysterious crash later.
   484  	//
   485  	// Note that panic != nil is okay here: there can be leftover panics,
   486  	// because the defers on the panic stack do not nest in frame order as
   487  	// they do on the defer stack. If you have:
   488  	//
   489  	//	frame 1 defers d1
   490  	//	frame 2 defers d2
   491  	//	frame 3 defers d3
   492  	//	frame 4 panics
   493  	//	frame 4's panic starts running defers
   494  	//	frame 5, running d3, defers d4
   495  	//	frame 5 panics
   496  	//	frame 5's panic starts running defers
   497  	//	frame 6, running d4, garbage collects
   498  	//	frame 6, running d2, garbage collects
   499  	//
   500  	// During the execution of d4, the panic stack is d4 -> d3, which
   501  	// is nested properly, and we'll treat frame 3 as resumable, because we
   502  	// can find d3. (And in fact frame 3 is resumable. If d4 recovers
   503  	// and frame 5 continues running, d3, d3 can recover and we'll
   504  	// resume execution in (returning from) frame 3.)
   505  	//
   506  	// During the execution of d2, however, the panic stack is d2 -> d3,
   507  	// which is inverted. The scan will match d2 to frame 2 but having
   508  	// d2 on the stack until then means it will not match d3 to frame 3.
   509  	// This is okay: if we're running d2, then all the defers after d2 have
   510  	// completed and their corresponding frames are dead. Not finding d3
   511  	// for frame 3 means we'll set frame 3's continpc == 0, which is correct
   512  	// (frame 3 is dead). At the end of the walk the panic stack can thus
   513  	// contain defers (d3 in this case) for dead frames. The inversion here
   514  	// always indicates a dead frame, and the effect of the inversion on the
   515  	// scan is to hide those dead frames, so the scan is still okay:
   516  	// what's left on the panic stack are exactly (and only) the dead frames.
   517  	//
   518  	// We require callback != nil here because only when callback != nil
   519  	// do we know that gentraceback is being called in a "must be correct"
   520  	// context as opposed to a "best effort" context. The tracebacks with
   521  	// callbacks only happen when everything is stopped nicely.
   522  	// At other times, such as when gathering a stack for a profiling signal
   523  	// or when printing a traceback during a crash, everything may not be
   524  	// stopped nicely, and the stack walk may not be able to complete.
   525  	// It's okay in those situations not to use up the entire defer stack:
   526  	// incomplete information then is still better than nothing.
   527  	if callback != nil && n < max && _defer != nil {
   528  		if _defer != nil {
   529  			print("runtime: g", gp.goid, ": leftover defer sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
   530  		}
   531  		for _defer = gp._defer; _defer != nil; _defer = _defer.link {
   532  			print("\tdefer ", _defer, " sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
   533  		}
   534  		throw("traceback has leftover defers")
   535  	}
   536  
   537  	if callback != nil && n < max && len(stkbar) > 0 {
   538  		print("runtime: g", gp.goid, ": leftover stack barriers ")
   539  		gcPrintStkbars(stkbarG, len(stkbarG.stkbar)-len(stkbar))
   540  		print("\n")
   541  		throw("traceback has leftover stack barriers")
   542  	}
   543  
   544  	if callback != nil && n < max && frame.sp != gp.stktopsp {
   545  		print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n")
   546  		print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n")
   547  		throw("traceback did not unwind completely")
   548  	}
   549  
   550  	return n
   551  }
   552  
   553  func getArgInfo(frame *stkframe, f *_func, needArgMap bool) (arglen uintptr, argmap *bitvector) {
   554  	arglen = uintptr(f.args)
   555  	if needArgMap && f.args == _ArgsSizeUnknown {
   556  		// Extract argument bitmaps for reflect stubs from the calls they made to reflect.
   557  		switch funcname(f) {
   558  		case "reflect.makeFuncStub", "reflect.methodValueCall":
   559  			arg0 := frame.sp + sys.MinFrameSize
   560  			fn := *(**[2]uintptr)(unsafe.Pointer(arg0))
   561  			if fn[0] != f.entry {
   562  				print("runtime: confused by ", funcname(f), "\n")
   563  				throw("reflect mismatch")
   564  			}
   565  			bv := (*bitvector)(unsafe.Pointer(fn[1]))
   566  			arglen = uintptr(bv.n * sys.PtrSize)
   567  			argmap = bv
   568  		}
   569  	}
   570  	return
   571  }
   572  
   573  // tracebackCgoContext handles tracing back a cgo context value, from
   574  // the context argument to setCgoTraceback, for the gentraceback
   575  // function. It returns the new value of n.
   576  func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int {
   577  	var cgoPCs [32]uintptr
   578  	cgoContextPCs(ctxt, cgoPCs[:])
   579  	var arg cgoSymbolizerArg
   580  	anySymbolized := false
   581  	for _, pc := range cgoPCs {
   582  		if pc == 0 || n >= max {
   583  			break
   584  		}
   585  		if pcbuf != nil {
   586  			(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   587  		}
   588  		if printing {
   589  			if cgoSymbolizer == nil {
   590  				print("non-Go function at pc=", hex(pc), "\n")
   591  			} else {
   592  				c := printOneCgoTraceback(pc, max-n, &arg)
   593  				n += c - 1 // +1 a few lines down
   594  				anySymbolized = true
   595  			}
   596  		}
   597  		n++
   598  	}
   599  	if anySymbolized {
   600  		arg.pc = 0
   601  		callCgoSymbolizer(&arg)
   602  	}
   603  	return n
   604  }
   605  
   606  func printcreatedby(gp *g) {
   607  	// Show what created goroutine, except main goroutine (goid 1).
   608  	pc := gp.gopc
   609  	f := findfunc(pc)
   610  	if f != nil && showframe(f, gp) && gp.goid != 1 {
   611  		print("created by ", funcname(f), "\n")
   612  		tracepc := pc // back up to CALL instruction for funcline.
   613  		// SPARC64's PC holds the address of the *current* 
   614  		// instruction, so it doesn't need this.
   615  		if pc > f.entry && sys.GoarchSparc64 == 0 {
   616  			tracepc -= sys.PCQuantum
   617  		}
   618  		file, line := funcline(f, tracepc)
   619  		print("\t", file, ":", line)
   620  		if pc > f.entry {
   621  			print(" +", hex(pc-f.entry))
   622  		}
   623  		print("\n")
   624  	}
   625  }
   626  
   627  func traceback(pc, sp, lr uintptr, gp *g) {
   628  	traceback1(pc, sp, lr, gp, 0)
   629  }
   630  
   631  // tracebacktrap is like traceback but expects that the PC and SP were obtained
   632  // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
   633  // Because they are from a trap instead of from a saved pair,
   634  // the initial PC must not be rewound to the previous instruction.
   635  // (All the saved pairs record a PC that is a return address, so we
   636  // rewind it into the CALL instruction.)
   637  func tracebacktrap(pc, sp, lr uintptr, gp *g) {
   638  	traceback1(pc, sp, lr, gp, _TraceTrap)
   639  }
   640  
   641  func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
   642  	// If the goroutine is in cgo, and we have a cgo traceback, print that.
   643  	if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
   644  		// Lock cgoCallers so that a signal handler won't
   645  		// change it, copy the array, reset it, unlock it.
   646  		// We are locked to the thread and are not running
   647  		// concurrently with a signal handler.
   648  		// We just have to stop a signal handler from interrupting
   649  		// in the middle of our copy.
   650  		atomic.Store(&gp.m.cgoCallersUse, 1)
   651  		cgoCallers := *gp.m.cgoCallers
   652  		gp.m.cgoCallers[0] = 0
   653  		atomic.Store(&gp.m.cgoCallersUse, 0)
   654  
   655  		printCgoTraceback(&cgoCallers)
   656  	}
   657  
   658  	var n int
   659  	if readgstatus(gp)&^_Gscan == _Gsyscall {
   660  		// Override registers if blocked in system call.
   661  		pc = gp.syscallpc
   662  		sp = gp.syscallsp
   663  		flags &^= _TraceTrap
   664  	}
   665  	// Print traceback. By default, omits runtime frames.
   666  	// If that means we print nothing at all, repeat forcing all frames printed.
   667  	n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
   668  	if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
   669  		n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
   670  	}
   671  	if n == _TracebackMaxFrames {
   672  		print("...additional frames elided...\n")
   673  	}
   674  	printcreatedby(gp)
   675  }
   676  
   677  func callers(skip int, pcbuf []uintptr) int {
   678  	sp := getcallersp(unsafe.Pointer(&skip))
   679  	pc := getcallerpc(unsafe.Pointer(&skip))
   680  	gp := getg()
   681  	var n int
   682  	systemstack(func() {
   683  		n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   684  	})
   685  	return n
   686  }
   687  
   688  func gcallers(gp *g, skip int, pcbuf []uintptr) int {
   689  	return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   690  }
   691  
   692  func showframe(f *_func, gp *g) bool {
   693  	g := getg()
   694  	if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
   695  		return true
   696  	}
   697  	level, _, _ := gotraceback()
   698  	name := funcname(f)
   699  
   700  	// Special case: always show runtime.gopanic frame, so that we can
   701  	// see where a panic started in the middle of a stack trace.
   702  	// See golang.org/issue/5832.
   703  	if name == "runtime.gopanic" {
   704  		return true
   705  	}
   706  
   707  	return level > 1 || f != nil && contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name))
   708  }
   709  
   710  // isExportedRuntime reports whether name is an exported runtime function.
   711  // It is only for runtime functions, so ASCII A-Z is fine.
   712  func isExportedRuntime(name string) bool {
   713  	const n = len("runtime.")
   714  	return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
   715  }
   716  
   717  var gStatusStrings = [...]string{
   718  	_Gidle:      "idle",
   719  	_Grunnable:  "runnable",
   720  	_Grunning:   "running",
   721  	_Gsyscall:   "syscall",
   722  	_Gwaiting:   "waiting",
   723  	_Gdead:      "dead",
   724  	_Gcopystack: "copystack",
   725  }
   726  
   727  func goroutineheader(gp *g) {
   728  	gpstatus := readgstatus(gp)
   729  
   730  	isScan := gpstatus&_Gscan != 0
   731  	gpstatus &^= _Gscan // drop the scan bit
   732  
   733  	// Basic string status
   734  	var status string
   735  	if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
   736  		status = gStatusStrings[gpstatus]
   737  	} else {
   738  		status = "???"
   739  	}
   740  
   741  	// Override.
   742  	if gpstatus == _Gwaiting && gp.waitreason != "" {
   743  		status = gp.waitreason
   744  	}
   745  
   746  	// approx time the G is blocked, in minutes
   747  	var waitfor int64
   748  	if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
   749  		waitfor = (nanotime() - gp.waitsince) / 60e9
   750  	}
   751  	print("goroutine ", gp.goid, " [", status)
   752  	if isScan {
   753  		print(" (scan)")
   754  	}
   755  	if waitfor >= 1 {
   756  		print(", ", waitfor, " minutes")
   757  	}
   758  	if gp.lockedm != nil {
   759  		print(", locked to thread")
   760  	}
   761  	print("]:\n")
   762  }
   763  
   764  func tracebackothers(me *g) {
   765  	level, _, _ := gotraceback()
   766  
   767  	// Show the current goroutine first, if we haven't already.
   768  	g := getg()
   769  	gp := g.m.curg
   770  	if gp != nil && gp != me {
   771  		print("\n")
   772  		goroutineheader(gp)
   773  		traceback(^uintptr(0), ^uintptr(0), 0, gp)
   774  	}
   775  
   776  	lock(&allglock)
   777  	for _, gp := range allgs {
   778  		if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 {
   779  			continue
   780  		}
   781  		print("\n")
   782  		goroutineheader(gp)
   783  		// Note: gp.m == g.m occurs when tracebackothers is
   784  		// called from a signal handler initiated during a
   785  		// systemstack call. The original G is still in the
   786  		// running state, and we want to print its stack.
   787  		if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning {
   788  			print("\tgoroutine running on other thread; stack unavailable\n")
   789  			printcreatedby(gp)
   790  		} else {
   791  			traceback(^uintptr(0), ^uintptr(0), 0, gp)
   792  		}
   793  	}
   794  	unlock(&allglock)
   795  }
   796  
   797  // Does f mark the top of a goroutine stack?
   798  func topofstack(f *_func) bool {
   799  	pc := f.entry
   800  	return pc == goexitPC ||
   801  		pc == mstartPC ||
   802  		pc == mcallPC ||
   803  		pc == morestackPC ||
   804  		pc == rt0_goPC ||
   805  		externalthreadhandlerp != 0 && pc == externalthreadhandlerp
   806  }
   807  
   808  // isSystemGoroutine reports whether the goroutine g must be omitted in
   809  // stack dumps and deadlock detector.
   810  func isSystemGoroutine(gp *g) bool {
   811  	pc := gp.startpc
   812  	return pc == runfinqPC && !fingRunning ||
   813  		pc == bgsweepPC ||
   814  		pc == forcegchelperPC ||
   815  		pc == timerprocPC ||
   816  		pc == gcBgMarkWorkerPC
   817  }
   818  
   819  // SetCgoTraceback records three C functions to use to gather
   820  // traceback information from C code and to convert that traceback
   821  // information into symbolic information. These are used when printing
   822  // stack traces for a program that uses cgo.
   823  //
   824  // The traceback and context functions may be called from a signal
   825  // handler, and must therefore use only async-signal safe functions.
   826  // The symbolizer function may be called while the program is
   827  // crashing, and so must be cautious about using memory.  None of the
   828  // functions may call back into Go.
   829  //
   830  // The context function will be called with a single argument, a
   831  // pointer to a struct:
   832  //
   833  //	struct {
   834  //		Context uintptr
   835  //	}
   836  //
   837  // In C syntax, this struct will be
   838  //
   839  //	struct {
   840  //		uintptr_t Context;
   841  //	};
   842  //
   843  // If the Context field is 0, the context function is being called to
   844  // record the current traceback context. It should record in the
   845  // Context field whatever information is needed about the current
   846  // point of execution to later produce a stack trace, probably the
   847  // stack pointer and PC. In this case the context function will be
   848  // called from C code.
   849  //
   850  // If the Context field is not 0, then it is a value returned by a
   851  // previous call to the context function. This case is called when the
   852  // context is no longer needed; that is, when the Go code is returning
   853  // to its C code caller. This permits the context function to release
   854  // any associated resources.
   855  //
   856  // While it would be correct for the context function to record a
   857  // complete a stack trace whenever it is called, and simply copy that
   858  // out in the traceback function, in a typical program the context
   859  // function will be called many times without ever recording a
   860  // traceback for that context. Recording a complete stack trace in a
   861  // call to the context function is likely to be inefficient.
   862  //
   863  // The traceback function will be called with a single argument, a
   864  // pointer to a struct:
   865  //
   866  //	struct {
   867  //		Context    uintptr
   868  //		SigContext uintptr
   869  //		Buf        *uintptr
   870  //		Max        uintptr
   871  //	}
   872  //
   873  // In C syntax, this struct will be
   874  //
   875  //	struct {
   876  //		uintptr_t  Context;
   877  //		uintptr_t  SigContext;
   878  //		uintptr_t* Buf;
   879  //		uintptr_t  Max;
   880  //	};
   881  //
   882  // The Context field will be zero to gather a traceback from the
   883  // current program execution point. In this case, the traceback
   884  // function will be called from C code.
   885  //
   886  // Otherwise Context will be a value previously returned by a call to
   887  // the context function. The traceback function should gather a stack
   888  // trace from that saved point in the program execution. The traceback
   889  // function may be called from an execution thread other than the one
   890  // that recorded the context, but only when the context is known to be
   891  // valid and unchanging. The traceback function may also be called
   892  // deeper in the call stack on the same thread that recorded the
   893  // context. The traceback function may be called multiple times with
   894  // the same Context value; it will usually be appropriate to cache the
   895  // result, if possible, the first time this is called for a specific
   896  // context value.
   897  //
   898  // If the traceback function is called from a signal handler on a Unix
   899  // system, SigContext will be the signal context argument passed to
   900  // the signal handler (a C ucontext_t* cast to uintptr_t). This may be
   901  // used to start tracing at the point where the signal occurred. If
   902  // the traceback function is not called from a signal handler,
   903  // SigContext will be zero.
   904  //
   905  // Buf is where the traceback information should be stored. It should
   906  // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
   907  // the PC of that function's caller, and so on.  Max is the maximum
   908  // number of entries to store.  The function should store a zero to
   909  // indicate the top of the stack, or that the caller is on a different
   910  // stack, presumably a Go stack.
   911  //
   912  // Unlike runtime.Callers, the PC values returned should, when passed
   913  // to the symbolizer function, return the file/line of the call
   914  // instruction.  No additional subtraction is required or appropriate.
   915  //
   916  // The symbolizer function will be called with a single argument, a
   917  // pointer to a struct:
   918  //
   919  //	struct {
   920  //		PC      uintptr // program counter to fetch information for
   921  //		File    *byte   // file name (NUL terminated)
   922  //		Lineno  uintptr // line number
   923  //		Func    *byte   // function name (NUL terminated)
   924  //		Entry   uintptr // function entry point
   925  //		More    uintptr // set non-zero if more info for this PC
   926  //		Data    uintptr // unused by runtime, available for function
   927  //	}
   928  //
   929  // In C syntax, this struct will be
   930  //
   931  //	struct {
   932  //		uintptr_t PC;
   933  //		char*     File;
   934  //		uintptr_t Lineno;
   935  //		char*     Func;
   936  //		uintptr_t Entry;
   937  //		uintptr_t More;
   938  //		uintptr_t Data;
   939  //	};
   940  //
   941  // The PC field will be a value returned by a call to the traceback
   942  // function.
   943  //
   944  // The first time the function is called for a particular traceback,
   945  // all the fields except PC will be 0. The function should fill in the
   946  // other fields if possible, setting them to 0/nil if the information
   947  // is not available. The Data field may be used to store any useful
   948  // information across calls. The More field should be set to non-zero
   949  // if there is more information for this PC, zero otherwise. If More
   950  // is set non-zero, the function will be called again with the same
   951  // PC, and may return different information (this is intended for use
   952  // with inlined functions). If More is zero, the function will be
   953  // called with the next PC value in the traceback. When the traceback
   954  // is complete, the function will be called once more with PC set to
   955  // zero; this may be used to free any information. Each call will
   956  // leave the fields of the struct set to the same values they had upon
   957  // return, except for the PC field when the More field is zero. The
   958  // function must not keep a copy of the struct pointer between calls.
   959  //
   960  // When calling SetCgoTraceback, the version argument is the version
   961  // number of the structs that the functions expect to receive.
   962  // Currently this must be zero.
   963  //
   964  // The symbolizer function may be nil, in which case the results of
   965  // the traceback function will be displayed as numbers. If the
   966  // traceback function is nil, the symbolizer function will never be
   967  // called. The context function may be nil, in which case the
   968  // traceback function will only be called with the context field set
   969  // to zero.  If the context function is nil, then calls from Go to C
   970  // to Go will not show a traceback for the C portion of the call stack.
   971  //
   972  // SetCgoTraceback should be called only once, ideally from an init function.
   973  func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
   974  	if version != 0 {
   975  		panic("unsupported version")
   976  	}
   977  
   978  	if cgoTraceback != nil && cgoTraceback != traceback ||
   979  		cgoContext != nil && cgoContext != context ||
   980  		cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
   981  		panic("call SetCgoTraceback only once")
   982  	}
   983  
   984  	cgoTraceback = traceback
   985  	cgoContext = context
   986  	cgoSymbolizer = symbolizer
   987  
   988  	// The context function is called when a C function calls a Go
   989  	// function. As such it is only called by C code in runtime/cgo.
   990  	if _cgo_set_context_function != nil {
   991  		cgocall(_cgo_set_context_function, context)
   992  	}
   993  }
   994  
   995  var cgoTraceback unsafe.Pointer
   996  var cgoContext unsafe.Pointer
   997  var cgoSymbolizer unsafe.Pointer
   998  
   999  // cgoTracebackArg is the type passed to cgoTraceback.
  1000  type cgoTracebackArg struct {
  1001  	context    uintptr
  1002  	sigContext uintptr
  1003  	buf        *uintptr
  1004  	max        uintptr
  1005  }
  1006  
  1007  // cgoContextArg is the type passed to the context function.
  1008  type cgoContextArg struct {
  1009  	context uintptr
  1010  }
  1011  
  1012  // cgoSymbolizerArg is the type passed to cgoSymbolizer.
  1013  type cgoSymbolizerArg struct {
  1014  	pc       uintptr
  1015  	file     *byte
  1016  	lineno   uintptr
  1017  	funcName *byte
  1018  	entry    uintptr
  1019  	more     uintptr
  1020  	data     uintptr
  1021  }
  1022  
  1023  // cgoTraceback prints a traceback of callers.
  1024  func printCgoTraceback(callers *cgoCallers) {
  1025  	if cgoSymbolizer == nil {
  1026  		for _, c := range callers {
  1027  			if c == 0 {
  1028  				break
  1029  			}
  1030  			print("non-Go function at pc=", hex(c), "\n")
  1031  		}
  1032  		return
  1033  	}
  1034  
  1035  	var arg cgoSymbolizerArg
  1036  	for _, c := range callers {
  1037  		if c == 0 {
  1038  			break
  1039  		}
  1040  		printOneCgoTraceback(c, 0x7fffffff, &arg)
  1041  	}
  1042  	arg.pc = 0
  1043  	callCgoSymbolizer(&arg)
  1044  }
  1045  
  1046  // printOneCgoTraceback prints the traceback of a single cgo caller.
  1047  // This can print more than one line because of inlining.
  1048  // Returns the number of frames printed.
  1049  func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
  1050  	c := 0
  1051  	arg.pc = pc
  1052  	for {
  1053  		if c > max {
  1054  			break
  1055  		}
  1056  		callCgoSymbolizer(arg)
  1057  		if arg.funcName != nil {
  1058  			// Note that we don't print any argument
  1059  			// information here, not even parentheses.
  1060  			// The symbolizer must add that if appropriate.
  1061  			println(gostringnocopy(arg.funcName))
  1062  		} else {
  1063  			println("non-Go function")
  1064  		}
  1065  		print("\t")
  1066  		if arg.file != nil {
  1067  			print(gostringnocopy(arg.file), ":", arg.lineno, " ")
  1068  		}
  1069  		print("pc=", hex(pc), "\n")
  1070  		c++
  1071  		if arg.more == 0 {
  1072  			break
  1073  		}
  1074  	}
  1075  	return c
  1076  }
  1077  
  1078  // callCgoSymbolizer calls the cgoSymbolizer function.
  1079  func callCgoSymbolizer(arg *cgoSymbolizerArg) {
  1080  	call := cgocall
  1081  	if panicking > 0 || getg().m.curg != getg() {
  1082  		// We do not want to call into the scheduler when panicking
  1083  		// or when on the system stack.
  1084  		call = asmcgocall
  1085  	}
  1086  	call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
  1087  }
  1088  
  1089  // cgoContextPCs gets the PC values from a cgo traceback.
  1090  func cgoContextPCs(ctxt uintptr, buf []uintptr) {
  1091  	if cgoTraceback == nil {
  1092  		return
  1093  	}
  1094  	call := cgocall
  1095  	if panicking > 0 || getg().m.curg != getg() {
  1096  		// We do not want to call into the scheduler when panicking
  1097  		// or when on the system stack.
  1098  		call = asmcgocall
  1099  	}
  1100  	arg := cgoTracebackArg{
  1101  		context: ctxt,
  1102  		buf:     (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
  1103  		max:     uintptr(len(buf)),
  1104  	}
  1105  	call(cgoTraceback, noescape(unsafe.Pointer(&arg)))
  1106  }