github.com/eun/go@v0.0.0-20170811110501-92cfd07a6cfd/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(unsafe.Pointer(&skip))
   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  	name := funcname(f)
   737  
   738  	// Special case: always show runtime.gopanic frame
   739  	// in the middle of a stack trace, so that we can
   740  	// see the boundary between ordinary code and
   741  	// panic-induced deferred code.
   742  	// See golang.org/issue/5832.
   743  	if name == "runtime.gopanic" && !firstFrame {
   744  		return true
   745  	}
   746  
   747  	return level > 1 || f.valid() && contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name))
   748  }
   749  
   750  // isExportedRuntime reports whether name is an exported runtime function.
   751  // It is only for runtime functions, so ASCII A-Z is fine.
   752  func isExportedRuntime(name string) bool {
   753  	const n = len("runtime.")
   754  	return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
   755  }
   756  
   757  var gStatusStrings = [...]string{
   758  	_Gidle:      "idle",
   759  	_Grunnable:  "runnable",
   760  	_Grunning:   "running",
   761  	_Gsyscall:   "syscall",
   762  	_Gwaiting:   "waiting",
   763  	_Gdead:      "dead",
   764  	_Gcopystack: "copystack",
   765  }
   766  
   767  func goroutineheader(gp *g) {
   768  	gpstatus := readgstatus(gp)
   769  
   770  	isScan := gpstatus&_Gscan != 0
   771  	gpstatus &^= _Gscan // drop the scan bit
   772  
   773  	// Basic string status
   774  	var status string
   775  	if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
   776  		status = gStatusStrings[gpstatus]
   777  	} else {
   778  		status = "???"
   779  	}
   780  
   781  	// Override.
   782  	if gpstatus == _Gwaiting && gp.waitreason != "" {
   783  		status = gp.waitreason
   784  	}
   785  
   786  	// approx time the G is blocked, in minutes
   787  	var waitfor int64
   788  	if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
   789  		waitfor = (nanotime() - gp.waitsince) / 60e9
   790  	}
   791  	print("goroutine ", gp.goid, " [", status)
   792  	if isScan {
   793  		print(" (scan)")
   794  	}
   795  	if waitfor >= 1 {
   796  		print(", ", waitfor, " minutes")
   797  	}
   798  	if gp.lockedm != nil {
   799  		print(", locked to thread")
   800  	}
   801  	print("]:\n")
   802  }
   803  
   804  func tracebackothers(me *g) {
   805  	level, _, _ := gotraceback()
   806  
   807  	// Show the current goroutine first, if we haven't already.
   808  	g := getg()
   809  	gp := g.m.curg
   810  	if gp != nil && gp != me {
   811  		print("\n")
   812  		goroutineheader(gp)
   813  		traceback(^uintptr(0), ^uintptr(0), 0, gp)
   814  	}
   815  
   816  	lock(&allglock)
   817  	for _, gp := range allgs {
   818  		if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 {
   819  			continue
   820  		}
   821  		print("\n")
   822  		goroutineheader(gp)
   823  		// Note: gp.m == g.m occurs when tracebackothers is
   824  		// called from a signal handler initiated during a
   825  		// systemstack call. The original G is still in the
   826  		// running state, and we want to print its stack.
   827  		if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning {
   828  			print("\tgoroutine running on other thread; stack unavailable\n")
   829  			printcreatedby(gp)
   830  		} else {
   831  			traceback(^uintptr(0), ^uintptr(0), 0, gp)
   832  		}
   833  	}
   834  	unlock(&allglock)
   835  }
   836  
   837  // Does f mark the top of a goroutine stack?
   838  func topofstack(f funcInfo) bool {
   839  	pc := f.entry
   840  	return pc == goexitPC ||
   841  		pc == mstartPC ||
   842  		pc == mcallPC ||
   843  		pc == morestackPC ||
   844  		pc == rt0_goPC ||
   845  		externalthreadhandlerp != 0 && pc == externalthreadhandlerp
   846  }
   847  
   848  // isSystemGoroutine reports whether the goroutine g must be omitted in
   849  // stack dumps and deadlock detector.
   850  func isSystemGoroutine(gp *g) bool {
   851  	pc := gp.startpc
   852  	return pc == runfinqPC && !fingRunning ||
   853  		pc == bgsweepPC ||
   854  		pc == forcegchelperPC ||
   855  		pc == timerprocPC ||
   856  		pc == gcBgMarkWorkerPC
   857  }
   858  
   859  // SetCgoTraceback records three C functions to use to gather
   860  // traceback information from C code and to convert that traceback
   861  // information into symbolic information. These are used when printing
   862  // stack traces for a program that uses cgo.
   863  //
   864  // The traceback and context functions may be called from a signal
   865  // handler, and must therefore use only async-signal safe functions.
   866  // The symbolizer function may be called while the program is
   867  // crashing, and so must be cautious about using memory.  None of the
   868  // functions may call back into Go.
   869  //
   870  // The context function will be called with a single argument, a
   871  // pointer to a struct:
   872  //
   873  //	struct {
   874  //		Context uintptr
   875  //	}
   876  //
   877  // In C syntax, this struct will be
   878  //
   879  //	struct {
   880  //		uintptr_t Context;
   881  //	};
   882  //
   883  // If the Context field is 0, the context function is being called to
   884  // record the current traceback context. It should record in the
   885  // Context field whatever information is needed about the current
   886  // point of execution to later produce a stack trace, probably the
   887  // stack pointer and PC. In this case the context function will be
   888  // called from C code.
   889  //
   890  // If the Context field is not 0, then it is a value returned by a
   891  // previous call to the context function. This case is called when the
   892  // context is no longer needed; that is, when the Go code is returning
   893  // to its C code caller. This permits the context function to release
   894  // any associated resources.
   895  //
   896  // While it would be correct for the context function to record a
   897  // complete a stack trace whenever it is called, and simply copy that
   898  // out in the traceback function, in a typical program the context
   899  // function will be called many times without ever recording a
   900  // traceback for that context. Recording a complete stack trace in a
   901  // call to the context function is likely to be inefficient.
   902  //
   903  // The traceback function will be called with a single argument, a
   904  // pointer to a struct:
   905  //
   906  //	struct {
   907  //		Context    uintptr
   908  //		SigContext uintptr
   909  //		Buf        *uintptr
   910  //		Max        uintptr
   911  //	}
   912  //
   913  // In C syntax, this struct will be
   914  //
   915  //	struct {
   916  //		uintptr_t  Context;
   917  //		uintptr_t  SigContext;
   918  //		uintptr_t* Buf;
   919  //		uintptr_t  Max;
   920  //	};
   921  //
   922  // The Context field will be zero to gather a traceback from the
   923  // current program execution point. In this case, the traceback
   924  // function will be called from C code.
   925  //
   926  // Otherwise Context will be a value previously returned by a call to
   927  // the context function. The traceback function should gather a stack
   928  // trace from that saved point in the program execution. The traceback
   929  // function may be called from an execution thread other than the one
   930  // that recorded the context, but only when the context is known to be
   931  // valid and unchanging. The traceback function may also be called
   932  // deeper in the call stack on the same thread that recorded the
   933  // context. The traceback function may be called multiple times with
   934  // the same Context value; it will usually be appropriate to cache the
   935  // result, if possible, the first time this is called for a specific
   936  // context value.
   937  //
   938  // If the traceback function is called from a signal handler on a Unix
   939  // system, SigContext will be the signal context argument passed to
   940  // the signal handler (a C ucontext_t* cast to uintptr_t). This may be
   941  // used to start tracing at the point where the signal occurred. If
   942  // the traceback function is not called from a signal handler,
   943  // SigContext will be zero.
   944  //
   945  // Buf is where the traceback information should be stored. It should
   946  // be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
   947  // the PC of that function's caller, and so on.  Max is the maximum
   948  // number of entries to store.  The function should store a zero to
   949  // indicate the top of the stack, or that the caller is on a different
   950  // stack, presumably a Go stack.
   951  //
   952  // Unlike runtime.Callers, the PC values returned should, when passed
   953  // to the symbolizer function, return the file/line of the call
   954  // instruction.  No additional subtraction is required or appropriate.
   955  //
   956  // The symbolizer function will be called with a single argument, a
   957  // pointer to a struct:
   958  //
   959  //	struct {
   960  //		PC      uintptr // program counter to fetch information for
   961  //		File    *byte   // file name (NUL terminated)
   962  //		Lineno  uintptr // line number
   963  //		Func    *byte   // function name (NUL terminated)
   964  //		Entry   uintptr // function entry point
   965  //		More    uintptr // set non-zero if more info for this PC
   966  //		Data    uintptr // unused by runtime, available for function
   967  //	}
   968  //
   969  // In C syntax, this struct will be
   970  //
   971  //	struct {
   972  //		uintptr_t PC;
   973  //		char*     File;
   974  //		uintptr_t Lineno;
   975  //		char*     Func;
   976  //		uintptr_t Entry;
   977  //		uintptr_t More;
   978  //		uintptr_t Data;
   979  //	};
   980  //
   981  // The PC field will be a value returned by a call to the traceback
   982  // function.
   983  //
   984  // The first time the function is called for a particular traceback,
   985  // all the fields except PC will be 0. The function should fill in the
   986  // other fields if possible, setting them to 0/nil if the information
   987  // is not available. The Data field may be used to store any useful
   988  // information across calls. The More field should be set to non-zero
   989  // if there is more information for this PC, zero otherwise. If More
   990  // is set non-zero, the function will be called again with the same
   991  // PC, and may return different information (this is intended for use
   992  // with inlined functions). If More is zero, the function will be
   993  // called with the next PC value in the traceback. When the traceback
   994  // is complete, the function will be called once more with PC set to
   995  // zero; this may be used to free any information. Each call will
   996  // leave the fields of the struct set to the same values they had upon
   997  // return, except for the PC field when the More field is zero. The
   998  // function must not keep a copy of the struct pointer between calls.
   999  //
  1000  // When calling SetCgoTraceback, the version argument is the version
  1001  // number of the structs that the functions expect to receive.
  1002  // Currently this must be zero.
  1003  //
  1004  // The symbolizer function may be nil, in which case the results of
  1005  // the traceback function will be displayed as numbers. If the
  1006  // traceback function is nil, the symbolizer function will never be
  1007  // called. The context function may be nil, in which case the
  1008  // traceback function will only be called with the context field set
  1009  // to zero.  If the context function is nil, then calls from Go to C
  1010  // to Go will not show a traceback for the C portion of the call stack.
  1011  //
  1012  // SetCgoTraceback should be called only once, ideally from an init function.
  1013  func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
  1014  	if version != 0 {
  1015  		panic("unsupported version")
  1016  	}
  1017  
  1018  	if cgoTraceback != nil && cgoTraceback != traceback ||
  1019  		cgoContext != nil && cgoContext != context ||
  1020  		cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
  1021  		panic("call SetCgoTraceback only once")
  1022  	}
  1023  
  1024  	cgoTraceback = traceback
  1025  	cgoContext = context
  1026  	cgoSymbolizer = symbolizer
  1027  
  1028  	// The context function is called when a C function calls a Go
  1029  	// function. As such it is only called by C code in runtime/cgo.
  1030  	if _cgo_set_context_function != nil {
  1031  		cgocall(_cgo_set_context_function, context)
  1032  	}
  1033  }
  1034  
  1035  var cgoTraceback unsafe.Pointer
  1036  var cgoContext unsafe.Pointer
  1037  var cgoSymbolizer unsafe.Pointer
  1038  
  1039  // cgoTracebackArg is the type passed to cgoTraceback.
  1040  type cgoTracebackArg struct {
  1041  	context    uintptr
  1042  	sigContext uintptr
  1043  	buf        *uintptr
  1044  	max        uintptr
  1045  }
  1046  
  1047  // cgoContextArg is the type passed to the context function.
  1048  type cgoContextArg struct {
  1049  	context uintptr
  1050  }
  1051  
  1052  // cgoSymbolizerArg is the type passed to cgoSymbolizer.
  1053  type cgoSymbolizerArg struct {
  1054  	pc       uintptr
  1055  	file     *byte
  1056  	lineno   uintptr
  1057  	funcName *byte
  1058  	entry    uintptr
  1059  	more     uintptr
  1060  	data     uintptr
  1061  }
  1062  
  1063  // cgoTraceback prints a traceback of callers.
  1064  func printCgoTraceback(callers *cgoCallers) {
  1065  	if cgoSymbolizer == nil {
  1066  		for _, c := range callers {
  1067  			if c == 0 {
  1068  				break
  1069  			}
  1070  			print("non-Go function at pc=", hex(c), "\n")
  1071  		}
  1072  		return
  1073  	}
  1074  
  1075  	var arg cgoSymbolizerArg
  1076  	for _, c := range callers {
  1077  		if c == 0 {
  1078  			break
  1079  		}
  1080  		printOneCgoTraceback(c, 0x7fffffff, &arg)
  1081  	}
  1082  	arg.pc = 0
  1083  	callCgoSymbolizer(&arg)
  1084  }
  1085  
  1086  // printOneCgoTraceback prints the traceback of a single cgo caller.
  1087  // This can print more than one line because of inlining.
  1088  // Returns the number of frames printed.
  1089  func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
  1090  	c := 0
  1091  	arg.pc = pc
  1092  	for {
  1093  		if c > max {
  1094  			break
  1095  		}
  1096  		callCgoSymbolizer(arg)
  1097  		if arg.funcName != nil {
  1098  			// Note that we don't print any argument
  1099  			// information here, not even parentheses.
  1100  			// The symbolizer must add that if appropriate.
  1101  			println(gostringnocopy(arg.funcName))
  1102  		} else {
  1103  			println("non-Go function")
  1104  		}
  1105  		print("\t")
  1106  		if arg.file != nil {
  1107  			print(gostringnocopy(arg.file), ":", arg.lineno, " ")
  1108  		}
  1109  		print("pc=", hex(pc), "\n")
  1110  		c++
  1111  		if arg.more == 0 {
  1112  			break
  1113  		}
  1114  	}
  1115  	return c
  1116  }
  1117  
  1118  // callCgoSymbolizer calls the cgoSymbolizer function.
  1119  func callCgoSymbolizer(arg *cgoSymbolizerArg) {
  1120  	call := cgocall
  1121  	if panicking > 0 || getg().m.curg != getg() {
  1122  		// We do not want to call into the scheduler when panicking
  1123  		// or when on the system stack.
  1124  		call = asmcgocall
  1125  	}
  1126  	if msanenabled {
  1127  		msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
  1128  	}
  1129  	call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
  1130  }
  1131  
  1132  // cgoContextPCs gets the PC values from a cgo traceback.
  1133  func cgoContextPCs(ctxt uintptr, buf []uintptr) {
  1134  	if cgoTraceback == nil {
  1135  		return
  1136  	}
  1137  	call := cgocall
  1138  	if panicking > 0 || getg().m.curg != getg() {
  1139  		// We do not want to call into the scheduler when panicking
  1140  		// or when on the system stack.
  1141  		call = asmcgocall
  1142  	}
  1143  	arg := cgoTracebackArg{
  1144  		context: ctxt,
  1145  		buf:     (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
  1146  		max:     uintptr(len(buf)),
  1147  	}
  1148  	if msanenabled {
  1149  		msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
  1150  	}
  1151  	call(cgoTraceback, noescape(unsafe.Pointer(&arg)))
  1152  }