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