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