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