github.com/c0deoo1/golang1.5@v0.0.0-20220525150107-c87c805d4593/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 "unsafe"
     8  
     9  // The code in this file implements stack trace walking for all architectures.
    10  // The most important fact about a given architecture is whether it uses a link register.
    11  // On systems with link registers, the prologue for a non-leaf function stores the
    12  // incoming value of LR at the bottom of the newly allocated stack frame.
    13  // On systems without link registers, the architecture pushes a return PC during
    14  // the call instruction, so the return PC ends up above the stack frame.
    15  // In this file, the return PC is always called LR, no matter how it was found.
    16  //
    17  // To date, the opposite of a link register architecture is an x86 architecture.
    18  // This code may need to change if some other kind of non-link-register
    19  // architecture comes along.
    20  //
    21  // The other important fact is the size of a pointer: on 32-bit systems the LR
    22  // takes up only 4 bytes on the stack, while on 64-bit systems it takes up 8 bytes.
    23  // Typically this is ptrSize.
    24  //
    25  // As an exception, amd64p32 has ptrSize == 4 but the CALL instruction still
    26  // stores an 8-byte return PC onto the stack. To accommodate this, we use regSize
    27  // as the size of the architecture-pushed return PC.
    28  //
    29  // usesLR is defined below. ptrSize and regSize are defined in stubs.go.
    30  
    31  const usesLR = GOARCH != "amd64" && GOARCH != "amd64p32" && GOARCH != "386"
    32  
    33  var (
    34  	// initialized in tracebackinit
    35  	goexitPC             uintptr
    36  	jmpdeferPC           uintptr
    37  	mcallPC              uintptr
    38  	morestackPC          uintptr
    39  	mstartPC             uintptr
    40  	rt0_goPC             uintptr
    41  	sigpanicPC           uintptr
    42  	runfinqPC            uintptr
    43  	backgroundgcPC       uintptr
    44  	bgsweepPC            uintptr
    45  	forcegchelperPC      uintptr
    46  	timerprocPC          uintptr
    47  	gcBgMarkWorkerPC     uintptr
    48  	systemstack_switchPC uintptr
    49  	systemstackPC        uintptr
    50  	stackBarrierPC       uintptr
    51  
    52  	gogoPC uintptr
    53  
    54  	externalthreadhandlerp uintptr // initialized elsewhere
    55  )
    56  
    57  func tracebackinit() {
    58  	// Go variable initialization happens late during runtime startup.
    59  	// Instead of initializing the variables above in the declarations,
    60  	// schedinit calls this function so that the variables are
    61  	// initialized and available earlier in the startup sequence.
    62  	goexitPC = funcPC(goexit)
    63  	jmpdeferPC = funcPC(jmpdefer)
    64  	mcallPC = funcPC(mcall)
    65  	morestackPC = funcPC(morestack)
    66  	mstartPC = funcPC(mstart)
    67  	rt0_goPC = funcPC(rt0_go)
    68  	sigpanicPC = funcPC(sigpanic)
    69  	runfinqPC = funcPC(runfinq)
    70  	backgroundgcPC = funcPC(backgroundgc)
    71  	bgsweepPC = funcPC(bgsweep)
    72  	forcegchelperPC = funcPC(forcegchelper)
    73  	timerprocPC = funcPC(timerproc)
    74  	gcBgMarkWorkerPC = funcPC(gcBgMarkWorker)
    75  	systemstack_switchPC = funcPC(systemstack_switch)
    76  	systemstackPC = funcPC(systemstack)
    77  	stackBarrierPC = funcPC(stackBarrier)
    78  
    79  	// used by sigprof handler
    80  	gogoPC = funcPC(gogo)
    81  }
    82  
    83  // Traceback over the deferred function calls.
    84  // Report them like calls that have been invoked but not started executing yet.
    85  func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) {
    86  	var frame stkframe
    87  	for d := gp._defer; d != nil; d = d.link {
    88  		fn := d.fn
    89  		if fn == nil {
    90  			// Defer of nil function. Args don't matter.
    91  			frame.pc = 0
    92  			frame.fn = nil
    93  			frame.argp = 0
    94  			frame.arglen = 0
    95  			frame.argmap = nil
    96  		} else {
    97  			frame.pc = uintptr(fn.fn)
    98  			f := findfunc(frame.pc)
    99  			if f == nil {
   100  				print("runtime: unknown pc in defer ", hex(frame.pc), "\n")
   101  				throw("unknown pc")
   102  			}
   103  			frame.fn = f
   104  			frame.argp = uintptr(deferArgs(d))
   105  			setArgInfo(&frame, f, true)
   106  		}
   107  		frame.continpc = frame.pc
   108  		if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
   109  			return
   110  		}
   111  	}
   112  }
   113  
   114  // Generic traceback.  Handles runtime stack prints (pcbuf == nil),
   115  // the runtime.Callers function (pcbuf != nil), as well as the garbage
   116  // collector (callback != nil).  A little clunky to merge these, but avoids
   117  // duplicating the code and all its subtlety.
   118  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 {
   119  	if goexitPC == 0 {
   120  		throw("gentraceback before goexitPC initialization")
   121  	}
   122  	g := getg()
   123  	if g == gp && g == g.m.curg {
   124  		// The starting sp has been passed in as a uintptr, and the caller may
   125  		// have other uintptr-typed stack references as well.
   126  		// If during one of the calls that got us here or during one of the
   127  		// callbacks below the stack must be grown, all these uintptr references
   128  		// to the stack will not be updated, and gentraceback will continue
   129  		// to inspect the old stack memory, which may no longer be valid.
   130  		// Even if all the variables were updated correctly, it is not clear that
   131  		// we want to expose a traceback that begins on one stack and ends
   132  		// on another stack. That could confuse callers quite a bit.
   133  		// Instead, we require that gentraceback and any other function that
   134  		// accepts an sp for the current goroutine (typically obtained by
   135  		// calling getcallersp) must not run on that goroutine's stack but
   136  		// instead on the g0 stack.
   137  		throw("gentraceback cannot trace user goroutine on its own stack")
   138  	}
   139  	gotraceback := gotraceback(nil)
   140  
   141  	// Fix up returns to the stack barrier by fetching the
   142  	// original return PC from gp.stkbar.
   143  	stkbar := gp.stkbar[gp.stkbarPos:]
   144  
   145  	if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
   146  		if gp.syscallsp != 0 {
   147  			pc0 = gp.syscallpc
   148  			sp0 = gp.syscallsp
   149  			if usesLR {
   150  				lr0 = 0
   151  			}
   152  		} else {
   153  			pc0 = gp.sched.pc
   154  			sp0 = gp.sched.sp
   155  			if usesLR {
   156  				lr0 = gp.sched.lr
   157  			}
   158  		}
   159  	}
   160  
   161  	nprint := 0
   162  	var frame stkframe
   163  	frame.pc = pc0
   164  	frame.sp = sp0
   165  	if usesLR {
   166  		frame.lr = lr0
   167  	}
   168  	waspanic := false
   169  	printing := pcbuf == nil && callback == nil
   170  	_defer := gp._defer
   171  
   172  	for _defer != nil && uintptr(_defer.sp) == _NoArgs {
   173  		_defer = _defer.link
   174  	}
   175  
   176  	// If the PC is zero, it's likely a nil function call.
   177  	// Start in the caller's frame.
   178  	if frame.pc == 0 {
   179  		if usesLR {
   180  			frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
   181  			frame.lr = 0
   182  		} else {
   183  			frame.pc = uintptr(*(*uintreg)(unsafe.Pointer(frame.sp)))
   184  			frame.sp += regSize
   185  		}
   186  	}
   187  
   188  	f := findfunc(frame.pc)
   189  	if f == nil {
   190  		if callback != nil {
   191  			print("runtime: unknown pc ", hex(frame.pc), "\n")
   192  			throw("unknown pc")
   193  		}
   194  		return 0
   195  	}
   196  	frame.fn = f
   197  
   198  	n := 0
   199  	for n < max {
   200  		// Typically:
   201  		//	pc is the PC of the running function.
   202  		//	sp is the stack pointer at that program counter.
   203  		//	fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
   204  		//	stk is the stack containing sp.
   205  		//	The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
   206  		f = frame.fn
   207  
   208  		// Found an actual function.
   209  		// Derive frame pointer and link register.
   210  		if frame.fp == 0 {
   211  			// We want to jump over the systemstack switch. If we're running on the
   212  			// g0, this systemstack is at the top of the stack.
   213  			// if we're not on g0 or there's a no curg, then this is a regular call.
   214  			sp := frame.sp
   215  			if flags&_TraceJumpStack != 0 && f.entry == systemstackPC && gp == g.m.g0 && gp.m.curg != nil {
   216  				sp = gp.m.curg.sched.sp
   217  				stkbar = gp.m.curg.stkbar[gp.m.curg.stkbarPos:]
   218  			}
   219  			frame.fp = sp + uintptr(funcspdelta(f, frame.pc))
   220  			if !usesLR {
   221  				// On x86, call instruction pushes return PC before entering new function.
   222  				frame.fp += regSize
   223  			}
   224  		}
   225  		var flr *_func
   226  		if topofstack(f) {
   227  			frame.lr = 0
   228  			flr = nil
   229  		} else if usesLR && f.entry == jmpdeferPC {
   230  			// jmpdefer modifies SP/LR/PC non-atomically.
   231  			// If a profiling interrupt arrives during jmpdefer,
   232  			// the stack unwind may see a mismatched register set
   233  			// and get confused. Stop if we see PC within jmpdefer
   234  			// to avoid that confusion.
   235  			// See golang.org/issue/8153.
   236  			if callback != nil {
   237  				throw("traceback_arm: found jmpdefer when tracing with callback")
   238  			}
   239  			frame.lr = 0
   240  		} else {
   241  			var lrPtr uintptr
   242  			if usesLR {
   243  				if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
   244  					lrPtr = frame.sp
   245  					frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
   246  				}
   247  			} else {
   248  				if frame.lr == 0 {
   249  					lrPtr = frame.fp - regSize
   250  					frame.lr = uintptr(*(*uintreg)(unsafe.Pointer(lrPtr)))
   251  				}
   252  			}
   253  			if frame.lr == stackBarrierPC {
   254  				// Recover original PC.
   255  				if stkbar[0].savedLRPtr != lrPtr {
   256  					print("found next stack barrier at ", hex(lrPtr), "; expected ")
   257  					gcPrintStkbars(stkbar)
   258  					print("\n")
   259  					throw("missed stack barrier")
   260  				}
   261  				frame.lr = stkbar[0].savedLRVal
   262  				stkbar = stkbar[1:]
   263  			}
   264  			flr = findfunc(frame.lr)
   265  			if flr == nil {
   266  				// This happens if you get a profiling interrupt at just the wrong time.
   267  				// In that context it is okay to stop early.
   268  				// But if callback is set, we're doing a garbage collection and must
   269  				// get everything, so crash loudly.
   270  				if callback != nil {
   271  					print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
   272  					throw("unknown caller pc")
   273  				}
   274  			}
   275  		}
   276  
   277  		frame.varp = frame.fp
   278  		if !usesLR {
   279  			// On x86, call instruction pushes return PC before entering new function.
   280  			frame.varp -= regSize
   281  		}
   282  
   283  		// If framepointer_enabled and there's a frame, then
   284  		// there's a saved bp here.
   285  		if framepointer_enabled && GOARCH == "amd64" && frame.varp > frame.sp {
   286  			frame.varp -= regSize
   287  		}
   288  
   289  		// Derive size of arguments.
   290  		// Most functions have a fixed-size argument block,
   291  		// so we can use metadata about the function f.
   292  		// Not all, though: there are some variadic functions
   293  		// in package runtime and reflect, and for those we use call-specific
   294  		// metadata recorded by f's caller.
   295  		if callback != nil || printing {
   296  			frame.argp = frame.fp
   297  			if usesLR {
   298  				frame.argp += ptrSize
   299  			}
   300  			setArgInfo(&frame, f, callback != nil)
   301  		}
   302  
   303  		// Determine frame's 'continuation PC', where it can continue.
   304  		// Normally this is the return address on the stack, but if sigpanic
   305  		// is immediately below this function on the stack, then the frame
   306  		// stopped executing due to a trap, and frame.pc is probably not
   307  		// a safe point for looking up liveness information. In this panicking case,
   308  		// the function either doesn't return at all (if it has no defers or if the
   309  		// defers do not recover) or it returns from one of the calls to
   310  		// deferproc a second time (if the corresponding deferred func recovers).
   311  		// It suffices to assume that the most recent deferproc is the one that
   312  		// returns; everything live at earlier deferprocs is still live at that one.
   313  		frame.continpc = frame.pc
   314  		if waspanic {
   315  			if _defer != nil && _defer.sp == frame.sp {
   316  				frame.continpc = _defer.pc
   317  			} else {
   318  				frame.continpc = 0
   319  			}
   320  		}
   321  
   322  		// Unwind our local defer stack past this frame.
   323  		for _defer != nil && (_defer.sp == frame.sp || _defer.sp == _NoArgs) {
   324  			_defer = _defer.link
   325  		}
   326  
   327  		if skip > 0 {
   328  			skip--
   329  			goto skipped
   330  		}
   331  
   332  		if pcbuf != nil {
   333  			(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = frame.pc
   334  		}
   335  		if callback != nil {
   336  			if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
   337  				return n
   338  			}
   339  		}
   340  		if printing {
   341  			if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp) {
   342  				// Print during crash.
   343  				//	main(0x1, 0x2, 0x3)
   344  				//		/home/rsc/go/src/runtime/x.go:23 +0xf
   345  				//
   346  				tracepc := frame.pc // back up to CALL instruction for funcline.
   347  				if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
   348  					tracepc--
   349  				}
   350  				print(funcname(f), "(")
   351  				argp := (*[100]uintptr)(unsafe.Pointer(frame.argp))
   352  				for i := uintptr(0); i < frame.arglen/ptrSize; i++ {
   353  					if i >= 10 {
   354  						print(", ...")
   355  						break
   356  					}
   357  					if i != 0 {
   358  						print(", ")
   359  					}
   360  					print(hex(argp[i]))
   361  				}
   362  				print(")\n")
   363  				file, line := funcline(f, tracepc)
   364  				print("\t", file, ":", line)
   365  				if frame.pc > f.entry {
   366  					print(" +", hex(frame.pc-f.entry))
   367  				}
   368  				if g.m.throwing > 0 && gp == g.m.curg || gotraceback >= 2 {
   369  					print(" fp=", hex(frame.fp), " sp=", hex(frame.sp))
   370  				}
   371  				print("\n")
   372  				nprint++
   373  			}
   374  		}
   375  		n++
   376  
   377  	skipped:
   378  		waspanic = f.entry == sigpanicPC
   379  
   380  		// Do not unwind past the bottom of the stack.
   381  		if flr == nil {
   382  			break
   383  		}
   384  
   385  		// Unwind to next frame.
   386  		frame.fn = flr
   387  		frame.pc = frame.lr
   388  		frame.lr = 0
   389  		frame.sp = frame.fp
   390  		frame.fp = 0
   391  		frame.argmap = nil
   392  
   393  		// On link register architectures, sighandler saves the LR on stack
   394  		// before faking a call to sigpanic.
   395  		if usesLR && waspanic {
   396  			x := *(*uintptr)(unsafe.Pointer(frame.sp))
   397  			frame.sp += ptrSize
   398  			if GOARCH == "arm64" {
   399  				// arm64 needs 16-byte aligned SP, always
   400  				frame.sp += ptrSize
   401  			}
   402  			f = findfunc(frame.pc)
   403  			frame.fn = f
   404  			if f == nil {
   405  				frame.pc = x
   406  			} else if funcspdelta(f, frame.pc) == 0 {
   407  				frame.lr = x
   408  			}
   409  		}
   410  	}
   411  
   412  	if printing {
   413  		n = nprint
   414  	}
   415  
   416  	// If callback != nil, we're being called to gather stack information during
   417  	// garbage collection or stack growth. In that context, require that we used
   418  	// up the entire defer stack. If not, then there is a bug somewhere and the
   419  	// garbage collection or stack growth may not have seen the correct picture
   420  	// of the stack. Crash now instead of silently executing the garbage collection
   421  	// or stack copy incorrectly and setting up for a mysterious crash later.
   422  	//
   423  	// Note that panic != nil is okay here: there can be leftover panics,
   424  	// because the defers on the panic stack do not nest in frame order as
   425  	// they do on the defer stack. If you have:
   426  	//
   427  	//	frame 1 defers d1
   428  	//	frame 2 defers d2
   429  	//	frame 3 defers d3
   430  	//	frame 4 panics
   431  	//	frame 4's panic starts running defers
   432  	//	frame 5, running d3, defers d4
   433  	//	frame 5 panics
   434  	//	frame 5's panic starts running defers
   435  	//	frame 6, running d4, garbage collects
   436  	//	frame 6, running d2, garbage collects
   437  	//
   438  	// During the execution of d4, the panic stack is d4 -> d3, which
   439  	// is nested properly, and we'll treat frame 3 as resumable, because we
   440  	// can find d3. (And in fact frame 3 is resumable. If d4 recovers
   441  	// and frame 5 continues running, d3, d3 can recover and we'll
   442  	// resume execution in (returning from) frame 3.)
   443  	//
   444  	// During the execution of d2, however, the panic stack is d2 -> d3,
   445  	// which is inverted. The scan will match d2 to frame 2 but having
   446  	// d2 on the stack until then means it will not match d3 to frame 3.
   447  	// This is okay: if we're running d2, then all the defers after d2 have
   448  	// completed and their corresponding frames are dead. Not finding d3
   449  	// for frame 3 means we'll set frame 3's continpc == 0, which is correct
   450  	// (frame 3 is dead). At the end of the walk the panic stack can thus
   451  	// contain defers (d3 in this case) for dead frames. The inversion here
   452  	// always indicates a dead frame, and the effect of the inversion on the
   453  	// scan is to hide those dead frames, so the scan is still okay:
   454  	// what's left on the panic stack are exactly (and only) the dead frames.
   455  	//
   456  	// We require callback != nil here because only when callback != nil
   457  	// do we know that gentraceback is being called in a "must be correct"
   458  	// context as opposed to a "best effort" context. The tracebacks with
   459  	// callbacks only happen when everything is stopped nicely.
   460  	// At other times, such as when gathering a stack for a profiling signal
   461  	// or when printing a traceback during a crash, everything may not be
   462  	// stopped nicely, and the stack walk may not be able to complete.
   463  	// It's okay in those situations not to use up the entire defer stack:
   464  	// incomplete information then is still better than nothing.
   465  	if callback != nil && n < max && _defer != nil {
   466  		if _defer != nil {
   467  			print("runtime: g", gp.goid, ": leftover defer sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
   468  		}
   469  		for _defer = gp._defer; _defer != nil; _defer = _defer.link {
   470  			print("\tdefer ", _defer, " sp=", hex(_defer.sp), " pc=", hex(_defer.pc), "\n")
   471  		}
   472  		throw("traceback has leftover defers")
   473  	}
   474  
   475  	if callback != nil && n < max && len(stkbar) > 0 {
   476  		print("runtime: g", gp.goid, ": leftover stack barriers ")
   477  		gcPrintStkbars(stkbar)
   478  		print("\n")
   479  		throw("traceback has leftover stack barriers")
   480  	}
   481  
   482  	return n
   483  }
   484  
   485  func setArgInfo(frame *stkframe, f *_func, needArgMap bool) {
   486  	frame.arglen = uintptr(f.args)
   487  	if needArgMap && f.args == _ArgsSizeUnknown {
   488  		// Extract argument bitmaps for reflect stubs from the calls they made to reflect.
   489  		switch funcname(f) {
   490  		case "reflect.makeFuncStub", "reflect.methodValueCall":
   491  			arg0 := frame.sp
   492  			if usesLR {
   493  				arg0 += ptrSize
   494  			}
   495  			fn := *(**[2]uintptr)(unsafe.Pointer(arg0))
   496  			if fn[0] != f.entry {
   497  				print("runtime: confused by ", funcname(f), "\n")
   498  				throw("reflect mismatch")
   499  			}
   500  			bv := (*bitvector)(unsafe.Pointer(fn[1]))
   501  			frame.arglen = uintptr(bv.n * ptrSize)
   502  			frame.argmap = bv
   503  		}
   504  	}
   505  }
   506  
   507  func printcreatedby(gp *g) {
   508  	// Show what created goroutine, except main goroutine (goid 1).
   509  	pc := gp.gopc
   510  	f := findfunc(pc)
   511  	if f != nil && showframe(f, gp) && gp.goid != 1 {
   512  		print("created by ", funcname(f), "\n")
   513  		tracepc := pc // back up to CALL instruction for funcline.
   514  		if pc > f.entry {
   515  			tracepc -= _PCQuantum
   516  		}
   517  		file, line := funcline(f, tracepc)
   518  		print("\t", file, ":", line)
   519  		if pc > f.entry {
   520  			print(" +", hex(pc-f.entry))
   521  		}
   522  		print("\n")
   523  	}
   524  }
   525  
   526  func traceback(pc, sp, lr uintptr, gp *g) {
   527  	traceback1(pc, sp, lr, gp, 0)
   528  }
   529  
   530  // tracebacktrap is like traceback but expects that the PC and SP were obtained
   531  // from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
   532  // Because they are from a trap instead of from a saved pair,
   533  // the initial PC must not be rewound to the previous instruction.
   534  // (All the saved pairs record a PC that is a return address, so we
   535  // rewind it into the CALL instruction.)
   536  func tracebacktrap(pc, sp, lr uintptr, gp *g) {
   537  	traceback1(pc, sp, lr, gp, _TraceTrap)
   538  }
   539  
   540  func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
   541  	var n int
   542  	if readgstatus(gp)&^_Gscan == _Gsyscall {
   543  		// Override registers if blocked in system call.
   544  		pc = gp.syscallpc
   545  		sp = gp.syscallsp
   546  		flags &^= _TraceTrap
   547  	}
   548  	// Print traceback. By default, omits runtime frames.
   549  	// If that means we print nothing at all, repeat forcing all frames printed.
   550  	n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
   551  	if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
   552  		n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
   553  	}
   554  	if n == _TracebackMaxFrames {
   555  		print("...additional frames elided...\n")
   556  	}
   557  	printcreatedby(gp)
   558  }
   559  
   560  func callers(skip int, pcbuf []uintptr) int {
   561  	sp := getcallersp(unsafe.Pointer(&skip))
   562  	pc := uintptr(getcallerpc(unsafe.Pointer(&skip)))
   563  	gp := getg()
   564  	var n int
   565  	systemstack(func() {
   566  		n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   567  	})
   568  	return n
   569  }
   570  
   571  func gcallers(gp *g, skip int, pcbuf []uintptr) int {
   572  	return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   573  }
   574  
   575  func showframe(f *_func, gp *g) bool {
   576  	g := getg()
   577  	if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
   578  		return true
   579  	}
   580  	traceback := gotraceback(nil)
   581  	name := funcname(f)
   582  
   583  	// Special case: always show runtime.panic frame, so that we can
   584  	// see where a panic started in the middle of a stack trace.
   585  	// See golang.org/issue/5832.
   586  	if name == "runtime.panic" {
   587  		return true
   588  	}
   589  
   590  	return traceback > 1 || f != nil && contains(name, ".") && (!hasprefix(name, "runtime.") || isExportedRuntime(name))
   591  }
   592  
   593  // isExportedRuntime reports whether name is an exported runtime function.
   594  // It is only for runtime functions, so ASCII A-Z is fine.
   595  func isExportedRuntime(name string) bool {
   596  	const n = len("runtime.")
   597  	return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
   598  }
   599  
   600  var gStatusStrings = [...]string{
   601  	_Gidle:      "idle",
   602  	_Grunnable:  "runnable",
   603  	_Grunning:   "running",
   604  	_Gsyscall:   "syscall",
   605  	_Gwaiting:   "waiting",
   606  	_Gdead:      "dead",
   607  	_Genqueue:   "enqueue",
   608  	_Gcopystack: "copystack",
   609  }
   610  
   611  var gScanStatusStrings = [...]string{
   612  	0:          "scan",
   613  	_Grunnable: "scanrunnable",
   614  	_Grunning:  "scanrunning",
   615  	_Gsyscall:  "scansyscall",
   616  	_Gwaiting:  "scanwaiting",
   617  	_Gdead:     "scandead",
   618  	_Genqueue:  "scanenqueue",
   619  }
   620  
   621  func goroutineheader(gp *g) {
   622  	gpstatus := readgstatus(gp)
   623  
   624  	// Basic string status
   625  	var status string
   626  	if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
   627  		status = gStatusStrings[gpstatus]
   628  	} else if gpstatus&_Gscan != 0 && 0 <= gpstatus&^_Gscan && gpstatus&^_Gscan < uint32(len(gStatusStrings)) {
   629  		status = gStatusStrings[gpstatus&^_Gscan]
   630  	} else {
   631  		status = "???"
   632  	}
   633  
   634  	// Override.
   635  	if (gpstatus == _Gwaiting || gpstatus == _Gscanwaiting) && gp.waitreason != "" {
   636  		status = gp.waitreason
   637  	}
   638  
   639  	// approx time the G is blocked, in minutes
   640  	var waitfor int64
   641  	gpstatus &^= _Gscan // drop the scan bit
   642  	if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
   643  		waitfor = (nanotime() - gp.waitsince) / 60e9
   644  	}
   645  	print("goroutine ", gp.goid, " [", status)
   646  	if waitfor >= 1 {
   647  		print(", ", waitfor, " minutes")
   648  	}
   649  	if gp.lockedm != nil {
   650  		print(", locked to thread")
   651  	}
   652  	print("]:\n")
   653  }
   654  
   655  func tracebackothers(me *g) {
   656  	level := gotraceback(nil)
   657  
   658  	// Show the current goroutine first, if we haven't already.
   659  	g := getg()
   660  	gp := g.m.curg
   661  	if gp != nil && gp != me {
   662  		print("\n")
   663  		goroutineheader(gp)
   664  		traceback(^uintptr(0), ^uintptr(0), 0, gp)
   665  	}
   666  
   667  	lock(&allglock)
   668  	for _, gp := range allgs {
   669  		if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp) && level < 2 {
   670  			continue
   671  		}
   672  		print("\n")
   673  		goroutineheader(gp)
   674  		// Note: gp.m == g.m occurs when tracebackothers is
   675  		// called from a signal handler initiated during a
   676  		// systemstack call.  The original G is still in the
   677  		// running state, and we want to print its stack.
   678  		if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning {
   679  			print("\tgoroutine running on other thread; stack unavailable\n")
   680  			printcreatedby(gp)
   681  		} else {
   682  			traceback(^uintptr(0), ^uintptr(0), 0, gp)
   683  		}
   684  	}
   685  	unlock(&allglock)
   686  }
   687  
   688  // Does f mark the top of a goroutine stack?
   689  func topofstack(f *_func) bool {
   690  	pc := f.entry
   691  	return pc == goexitPC ||
   692  		pc == mstartPC ||
   693  		pc == mcallPC ||
   694  		pc == morestackPC ||
   695  		pc == rt0_goPC ||
   696  		externalthreadhandlerp != 0 && pc == externalthreadhandlerp
   697  }
   698  
   699  // isSystemGoroutine reports whether the goroutine g must be omitted in
   700  // stack dumps and deadlock detector.
   701  func isSystemGoroutine(gp *g) bool {
   702  	pc := gp.startpc
   703  	return pc == runfinqPC && !fingRunning ||
   704  		pc == backgroundgcPC ||
   705  		pc == bgsweepPC ||
   706  		pc == forcegchelperPC ||
   707  		pc == timerprocPC ||
   708  		pc == gcBgMarkWorkerPC
   709  }