...

Source file src/runtime/traceback.go

     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 skipPC uintptr
    39	
    40	func tracebackinit() {
    41		// Go variable initialization happens late during runtime startup.
    42		// Instead of initializing the variables above in the declarations,
    43		// schedinit calls this function so that the variables are
    44		// initialized and available earlier in the startup sequence.
    45		skipPC = funcPC(skipPleaseUseCallersFrames)
    46	}
    47	
    48	// Traceback over the deferred function calls.
    49	// Report them like calls that have been invoked but not started executing yet.
    50	func tracebackdefers(gp *g, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer) {
    51		var frame stkframe
    52		for d := gp._defer; d != nil; d = d.link {
    53			fn := d.fn
    54			if fn == nil {
    55				// Defer of nil function. Args don't matter.
    56				frame.pc = 0
    57				frame.fn = funcInfo{}
    58				frame.argp = 0
    59				frame.arglen = 0
    60				frame.argmap = nil
    61			} else {
    62				frame.pc = fn.fn
    63				f := findfunc(frame.pc)
    64				if !f.valid() {
    65					print("runtime: unknown pc in defer ", hex(frame.pc), "\n")
    66					throw("unknown pc")
    67				}
    68				frame.fn = f
    69				frame.argp = uintptr(deferArgs(d))
    70				var ok bool
    71				frame.arglen, frame.argmap, ok = getArgInfoFast(f, true)
    72				if !ok {
    73					frame.arglen, frame.argmap = getArgInfo(&frame, f, true, fn)
    74				}
    75			}
    76			frame.continpc = frame.pc
    77			if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
    78				return
    79			}
    80		}
    81	}
    82	
    83	const sizeofSkipFunction = 256
    84	
    85	// This function is defined in asm.s to be sizeofSkipFunction bytes long.
    86	func skipPleaseUseCallersFrames()
    87	
    88	// Generic traceback. Handles runtime stack prints (pcbuf == nil),
    89	// the runtime.Callers function (pcbuf != nil), as well as the garbage
    90	// collector (callback != nil).  A little clunky to merge these, but avoids
    91	// duplicating the code and all its subtlety.
    92	//
    93	// The skip argument is only valid with pcbuf != nil and counts the number
    94	// of logical frames to skip rather than physical frames (with inlining, a
    95	// PC in pcbuf can represent multiple calls). If a PC is partially skipped
    96	// and max > 1, pcbuf[1] will be runtime.skipPleaseUseCallersFrames+N where
    97	// N indicates the number of logical frames to skip in pcbuf[0].
    98	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 {
    99		if skip > 0 && callback != nil {
   100			throw("gentraceback callback cannot be used with non-zero skip")
   101		}
   102	
   103		// Don't call this "g"; it's too easy get "g" and "gp" confused.
   104		if ourg := getg(); ourg == gp && ourg == ourg.m.curg {
   105			// The starting sp has been passed in as a uintptr, and the caller may
   106			// have other uintptr-typed stack references as well.
   107			// If during one of the calls that got us here or during one of the
   108			// callbacks below the stack must be grown, all these uintptr references
   109			// to the stack will not be updated, and gentraceback will continue
   110			// to inspect the old stack memory, which may no longer be valid.
   111			// Even if all the variables were updated correctly, it is not clear that
   112			// we want to expose a traceback that begins on one stack and ends
   113			// on another stack. That could confuse callers quite a bit.
   114			// Instead, we require that gentraceback and any other function that
   115			// accepts an sp for the current goroutine (typically obtained by
   116			// calling getcallersp) must not run on that goroutine's stack but
   117			// instead on the g0 stack.
   118			throw("gentraceback cannot trace user goroutine on its own stack")
   119		}
   120		level, _, _ := gotraceback()
   121	
   122		var ctxt *funcval // Context pointer for unstarted goroutines. See issue #25897.
   123	
   124		if pc0 == ^uintptr(0) && sp0 == ^uintptr(0) { // Signal to fetch saved values from gp.
   125			if gp.syscallsp != 0 {
   126				pc0 = gp.syscallpc
   127				sp0 = gp.syscallsp
   128				if usesLR {
   129					lr0 = 0
   130				}
   131			} else {
   132				pc0 = gp.sched.pc
   133				sp0 = gp.sched.sp
   134				if usesLR {
   135					lr0 = gp.sched.lr
   136				}
   137				ctxt = (*funcval)(gp.sched.ctxt)
   138			}
   139		}
   140	
   141		nprint := 0
   142		var frame stkframe
   143		frame.pc = pc0
   144		frame.sp = sp0
   145		if usesLR {
   146			frame.lr = lr0
   147		}
   148		waspanic := false
   149		cgoCtxt := gp.cgoCtxt
   150		printing := pcbuf == nil && callback == nil
   151	
   152		// If the PC is zero, it's likely a nil function call.
   153		// Start in the caller's frame.
   154		if frame.pc == 0 {
   155			if usesLR {
   156				frame.pc = *(*uintptr)(unsafe.Pointer(frame.sp))
   157				frame.lr = 0
   158			} else {
   159				frame.pc = uintptr(*(*sys.Uintreg)(unsafe.Pointer(frame.sp)))
   160				frame.sp += sys.RegSize
   161			}
   162		}
   163	
   164		f := findfunc(frame.pc)
   165		if !f.valid() {
   166			if callback != nil || printing {
   167				print("runtime: unknown pc ", hex(frame.pc), "\n")
   168				tracebackHexdump(gp.stack, &frame, 0)
   169			}
   170			if callback != nil {
   171				throw("unknown pc")
   172			}
   173			return 0
   174		}
   175		frame.fn = f
   176	
   177		var cache pcvalueCache
   178	
   179		lastFuncID := funcID_normal
   180		n := 0
   181		for n < max {
   182			// Typically:
   183			//	pc is the PC of the running function.
   184			//	sp is the stack pointer at that program counter.
   185			//	fp is the frame pointer (caller's stack pointer) at that program counter, or nil if unknown.
   186			//	stk is the stack containing sp.
   187			//	The caller's program counter is lr, unless lr is zero, in which case it is *(uintptr*)sp.
   188			f = frame.fn
   189			if f.pcsp == 0 {
   190				// No frame information, must be external function, like race support.
   191				// See golang.org/issue/13568.
   192				break
   193			}
   194	
   195			// Found an actual function.
   196			// Derive frame pointer and link register.
   197			if frame.fp == 0 {
   198				// Jump over system stack transitions. If we're on g0 and there's a user
   199				// goroutine, try to jump. Otherwise this is a regular call.
   200				if flags&_TraceJumpStack != 0 && gp == gp.m.g0 && gp.m.curg != nil {
   201					switch f.funcID {
   202					case funcID_morestack:
   203						// morestack does not return normally -- newstack()
   204						// gogo's to curg.sched. Match that.
   205						// This keeps morestack() from showing up in the backtrace,
   206						// but that makes some sense since it'll never be returned
   207						// to.
   208						frame.pc = gp.m.curg.sched.pc
   209						frame.fn = findfunc(frame.pc)
   210						f = frame.fn
   211						frame.sp = gp.m.curg.sched.sp
   212						cgoCtxt = gp.m.curg.cgoCtxt
   213					case funcID_systemstack:
   214						// systemstack returns normally, so just follow the
   215						// stack transition.
   216						frame.sp = gp.m.curg.sched.sp
   217						cgoCtxt = gp.m.curg.cgoCtxt
   218					}
   219				}
   220				frame.fp = frame.sp + uintptr(funcspdelta(f, frame.pc, &cache))
   221				if !usesLR {
   222					// On x86, call instruction pushes return PC before entering new function.
   223					frame.fp += sys.RegSize
   224				}
   225			}
   226			var flr funcInfo
   227			if topofstack(f, gp.m != nil && gp == gp.m.g0) {
   228				frame.lr = 0
   229				flr = funcInfo{}
   230			} else if usesLR && f.funcID == funcID_jmpdefer {
   231				// jmpdefer modifies SP/LR/PC non-atomically.
   232				// If a profiling interrupt arrives during jmpdefer,
   233				// the stack unwind may see a mismatched register set
   234				// and get confused. Stop if we see PC within jmpdefer
   235				// to avoid that confusion.
   236				// See golang.org/issue/8153.
   237				if callback != nil {
   238					throw("traceback_arm: found jmpdefer when tracing with callback")
   239				}
   240				frame.lr = 0
   241			} else {
   242				var lrPtr uintptr
   243				if usesLR {
   244					if n == 0 && frame.sp < frame.fp || frame.lr == 0 {
   245						lrPtr = frame.sp
   246						frame.lr = *(*uintptr)(unsafe.Pointer(lrPtr))
   247					}
   248				} else {
   249					if frame.lr == 0 {
   250						lrPtr = frame.fp - sys.RegSize
   251						frame.lr = uintptr(*(*sys.Uintreg)(unsafe.Pointer(lrPtr)))
   252					}
   253				}
   254				flr = findfunc(frame.lr)
   255				if !flr.valid() {
   256					// This happens if you get a profiling interrupt at just the wrong time.
   257					// In that context it is okay to stop early.
   258					// But if callback is set, we're doing a garbage collection and must
   259					// get everything, so crash loudly.
   260					doPrint := printing
   261					if doPrint && gp.m.incgo && f.funcID == funcID_sigpanic {
   262						// We can inject sigpanic
   263						// calls directly into C code,
   264						// in which case we'll see a C
   265						// return PC. Don't complain.
   266						doPrint = false
   267					}
   268					if callback != nil || doPrint {
   269						print("runtime: unexpected return pc for ", funcname(f), " called from ", hex(frame.lr), "\n")
   270						tracebackHexdump(gp.stack, &frame, lrPtr)
   271					}
   272					if callback != nil {
   273						throw("unknown caller pc")
   274					}
   275				}
   276			}
   277	
   278			frame.varp = frame.fp
   279			if !usesLR {
   280				// On x86, call instruction pushes return PC before entering new function.
   281				frame.varp -= sys.RegSize
   282			}
   283	
   284			// If framepointer_enabled and there's a frame, then
   285			// there's a saved bp here.
   286			if frame.varp > frame.sp && (framepointer_enabled && GOARCH == "amd64" || GOARCH == "arm64") {
   287				frame.varp -= sys.RegSize
   288			}
   289	
   290			// Derive size of arguments.
   291			// Most functions have a fixed-size argument block,
   292			// so we can use metadata about the function f.
   293			// Not all, though: there are some variadic functions
   294			// in package runtime and reflect, and for those we use call-specific
   295			// metadata recorded by f's caller.
   296			if callback != nil || printing {
   297				frame.argp = frame.fp + sys.MinFrameSize
   298				var ok bool
   299				frame.arglen, frame.argmap, ok = getArgInfoFast(f, callback != nil)
   300				if !ok {
   301					frame.arglen, frame.argmap = getArgInfo(&frame, f, callback != nil, ctxt)
   302				}
   303			}
   304			ctxt = nil // ctxt is only needed to get arg maps for the topmost frame
   305	
   306			// Determine frame's 'continuation PC', where it can continue.
   307			// Normally this is the return address on the stack, but if sigpanic
   308			// is immediately below this function on the stack, then the frame
   309			// stopped executing due to a trap, and frame.pc is probably not
   310			// a safe point for looking up liveness information. In this panicking case,
   311			// the function either doesn't return at all (if it has no defers or if the
   312			// defers do not recover) or it returns from one of the calls to
   313			// deferproc a second time (if the corresponding deferred func recovers).
   314			// In the latter case, use a deferreturn call site as the continuation pc.
   315			frame.continpc = frame.pc
   316			if waspanic {
   317				if frame.fn.deferreturn != 0 {
   318					frame.continpc = frame.fn.entry + uintptr(frame.fn.deferreturn) + 1
   319					// Note: this may perhaps keep return variables alive longer than
   320					// strictly necessary, as we are using "function has a defer statement"
   321					// as a proxy for "function actually deferred something". It seems
   322					// to be a minor drawback. (We used to actually look through the
   323					// gp._defer for a defer corresponding to this function, but that
   324					// is hard to do with defer records on the stack during a stack copy.)
   325					// Note: the +1 is to offset the -1 that
   326					// stack.go:getStackMap does to back up a return
   327					// address make sure the pc is in the CALL instruction.
   328				} else {
   329					frame.continpc = 0
   330				}
   331			}
   332	
   333			if callback != nil {
   334				if !callback((*stkframe)(noescape(unsafe.Pointer(&frame))), v) {
   335					return n
   336				}
   337			}
   338	
   339			if pcbuf != nil {
   340				pc := frame.pc
   341				// backup to CALL instruction to read inlining info (same logic as below)
   342				tracepc := pc
   343				if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
   344					tracepc--
   345				}
   346	
   347				// If there is inlining info, record the inner frames.
   348				if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
   349					inltree := (*[1 << 20]inlinedCall)(inldata)
   350					for {
   351						ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, &cache)
   352						if ix < 0 {
   353							break
   354						}
   355						if inltree[ix].funcID == funcID_wrapper && elideWrapperCalling(lastFuncID) {
   356							// ignore wrappers
   357						} else if skip > 0 {
   358							skip--
   359						} else if n < max {
   360							(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   361							n++
   362						}
   363						lastFuncID = inltree[ix].funcID
   364						// Back up to an instruction in the "caller".
   365						tracepc = frame.fn.entry + uintptr(inltree[ix].parentPc)
   366						pc = tracepc + 1
   367					}
   368				}
   369				// Record the main frame.
   370				if f.funcID == funcID_wrapper && elideWrapperCalling(lastFuncID) {
   371					// Ignore wrapper functions (except when they trigger panics).
   372				} else if skip > 0 {
   373					skip--
   374				} else if n < max {
   375					(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   376					n++
   377				}
   378				lastFuncID = f.funcID
   379				n-- // offset n++ below
   380			}
   381	
   382			if printing {
   383				// assume skip=0 for printing.
   384				//
   385				// Never elide wrappers if we haven't printed
   386				// any frames. And don't elide wrappers that
   387				// called panic rather than the wrapped
   388				// function. Otherwise, leave them out.
   389	
   390				// backup to CALL instruction to read inlining info (same logic as below)
   391				tracepc := frame.pc
   392				if (n > 0 || flags&_TraceTrap == 0) && frame.pc > f.entry && !waspanic {
   393					tracepc--
   394				}
   395				// If there is inlining info, print the inner frames.
   396				if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
   397					inltree := (*[1 << 20]inlinedCall)(inldata)
   398					for {
   399						ix := pcdatavalue(f, _PCDATA_InlTreeIndex, tracepc, nil)
   400						if ix < 0 {
   401							break
   402						}
   403						if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, inltree[ix].funcID, lastFuncID) {
   404							name := funcnameFromNameoff(f, inltree[ix].func_)
   405							file, line := funcline(f, tracepc)
   406							print(name, "(...)\n")
   407							print("\t", file, ":", line, "\n")
   408							nprint++
   409						}
   410						lastFuncID = inltree[ix].funcID
   411						// Back up to an instruction in the "caller".
   412						tracepc = frame.fn.entry + uintptr(inltree[ix].parentPc)
   413					}
   414				}
   415				if (flags&_TraceRuntimeFrames) != 0 || showframe(f, gp, nprint == 0, f.funcID, lastFuncID) {
   416					// Print during crash.
   417					//	main(0x1, 0x2, 0x3)
   418					//		/home/rsc/go/src/runtime/x.go:23 +0xf
   419					//
   420					name := funcname(f)
   421					file, line := funcline(f, tracepc)
   422					if name == "runtime.gopanic" {
   423						name = "panic"
   424					}
   425					print(name, "(")
   426					argp := (*[100]uintptr)(unsafe.Pointer(frame.argp))
   427					for i := uintptr(0); i < frame.arglen/sys.PtrSize; i++ {
   428						if i >= 10 {
   429							print(", ...")
   430							break
   431						}
   432						if i != 0 {
   433							print(", ")
   434						}
   435						print(hex(argp[i]))
   436					}
   437					print(")\n")
   438					print("\t", file, ":", line)
   439					if frame.pc > f.entry {
   440						print(" +", hex(frame.pc-f.entry))
   441					}
   442					if gp.m != nil && gp.m.throwing > 0 && gp == gp.m.curg || level >= 2 {
   443						print(" fp=", hex(frame.fp), " sp=", hex(frame.sp), " pc=", hex(frame.pc))
   444					}
   445					print("\n")
   446					nprint++
   447				}
   448				lastFuncID = f.funcID
   449			}
   450			n++
   451	
   452			if f.funcID == funcID_cgocallback_gofunc && len(cgoCtxt) > 0 {
   453				ctxt := cgoCtxt[len(cgoCtxt)-1]
   454				cgoCtxt = cgoCtxt[:len(cgoCtxt)-1]
   455	
   456				// skip only applies to Go frames.
   457				// callback != nil only used when we only care
   458				// about Go frames.
   459				if skip == 0 && callback == nil {
   460					n = tracebackCgoContext(pcbuf, printing, ctxt, n, max)
   461				}
   462			}
   463	
   464			waspanic = f.funcID == funcID_sigpanic
   465	
   466			// Do not unwind past the bottom of the stack.
   467			if !flr.valid() {
   468				break
   469			}
   470	
   471			// Unwind to next frame.
   472			frame.fn = flr
   473			frame.pc = frame.lr
   474			frame.lr = 0
   475			frame.sp = frame.fp
   476			frame.fp = 0
   477			frame.argmap = nil
   478	
   479			// On link register architectures, sighandler saves the LR on stack
   480			// before faking a call to sigpanic.
   481			if usesLR && waspanic {
   482				x := *(*uintptr)(unsafe.Pointer(frame.sp))
   483				frame.sp += sys.MinFrameSize
   484				if GOARCH == "arm64" {
   485					// arm64 needs 16-byte aligned SP, always
   486					frame.sp += sys.PtrSize
   487				}
   488				f = findfunc(frame.pc)
   489				frame.fn = f
   490				if !f.valid() {
   491					frame.pc = x
   492				} else if funcspdelta(f, frame.pc, &cache) == 0 {
   493					frame.lr = x
   494				}
   495			}
   496		}
   497	
   498		if printing {
   499			n = nprint
   500		}
   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		if callback != nil && n < max && frame.sp != gp.stktopsp {
   543			print("runtime: g", gp.goid, ": frame.sp=", hex(frame.sp), " top=", hex(gp.stktopsp), "\n")
   544			print("\tstack=[", hex(gp.stack.lo), "-", hex(gp.stack.hi), "] n=", n, " max=", max, "\n")
   545			throw("traceback did not unwind completely")
   546		}
   547	
   548		return n
   549	}
   550	
   551	// reflectMethodValue is a partial duplicate of reflect.makeFuncImpl
   552	// and reflect.methodValue.
   553	type reflectMethodValue struct {
   554		fn     uintptr
   555		stack  *bitvector // ptrmap for both args and results
   556		argLen uintptr    // just args
   557	}
   558	
   559	// getArgInfoFast returns the argument frame information for a call to f.
   560	// It is short and inlineable. However, it does not handle all functions.
   561	// If ok reports false, you must call getArgInfo instead.
   562	// TODO(josharian): once we do mid-stack inlining,
   563	// call getArgInfo directly from getArgInfoFast and stop returning an ok bool.
   564	func getArgInfoFast(f funcInfo, needArgMap bool) (arglen uintptr, argmap *bitvector, ok bool) {
   565		return uintptr(f.args), nil, !(needArgMap && f.args == _ArgsSizeUnknown)
   566	}
   567	
   568	// getArgInfo returns the argument frame information for a call to f
   569	// with call frame frame.
   570	//
   571	// This is used for both actual calls with active stack frames and for
   572	// deferred calls or goroutines that are not yet executing. If this is an actual
   573	// call, ctxt must be nil (getArgInfo will retrieve what it needs from
   574	// the active stack frame). If this is a deferred call or unstarted goroutine,
   575	// ctxt must be the function object that was deferred or go'd.
   576	func getArgInfo(frame *stkframe, f funcInfo, needArgMap bool, ctxt *funcval) (arglen uintptr, argmap *bitvector) {
   577		arglen = uintptr(f.args)
   578		if needArgMap && f.args == _ArgsSizeUnknown {
   579			// Extract argument bitmaps for reflect stubs from the calls they made to reflect.
   580			switch funcname(f) {
   581			case "reflect.makeFuncStub", "reflect.methodValueCall":
   582				// These take a *reflect.methodValue as their
   583				// context register.
   584				var mv *reflectMethodValue
   585				var retValid bool
   586				if ctxt != nil {
   587					// This is not an actual call, but a
   588					// deferred call or an unstarted goroutine.
   589					// The function value is itself the *reflect.methodValue.
   590					mv = (*reflectMethodValue)(unsafe.Pointer(ctxt))
   591				} else {
   592					// This is a real call that took the
   593					// *reflect.methodValue as its context
   594					// register and immediately saved it
   595					// to 0(SP). Get the methodValue from
   596					// 0(SP).
   597					arg0 := frame.sp + sys.MinFrameSize
   598					mv = *(**reflectMethodValue)(unsafe.Pointer(arg0))
   599					// Figure out whether the return values are valid.
   600					// Reflect will update this value after it copies
   601					// in the return values.
   602					retValid = *(*bool)(unsafe.Pointer(arg0 + 3*sys.PtrSize))
   603				}
   604				if mv.fn != f.entry {
   605					print("runtime: confused by ", funcname(f), "\n")
   606					throw("reflect mismatch")
   607				}
   608				bv := mv.stack
   609				arglen = uintptr(bv.n * sys.PtrSize)
   610				if !retValid {
   611					arglen = uintptr(mv.argLen) &^ (sys.PtrSize - 1)
   612				}
   613				argmap = bv
   614			}
   615		}
   616		return
   617	}
   618	
   619	// tracebackCgoContext handles tracing back a cgo context value, from
   620	// the context argument to setCgoTraceback, for the gentraceback
   621	// function. It returns the new value of n.
   622	func tracebackCgoContext(pcbuf *uintptr, printing bool, ctxt uintptr, n, max int) int {
   623		var cgoPCs [32]uintptr
   624		cgoContextPCs(ctxt, cgoPCs[:])
   625		var arg cgoSymbolizerArg
   626		anySymbolized := false
   627		for _, pc := range cgoPCs {
   628			if pc == 0 || n >= max {
   629				break
   630			}
   631			if pcbuf != nil {
   632				(*[1 << 20]uintptr)(unsafe.Pointer(pcbuf))[n] = pc
   633			}
   634			if printing {
   635				if cgoSymbolizer == nil {
   636					print("non-Go function at pc=", hex(pc), "\n")
   637				} else {
   638					c := printOneCgoTraceback(pc, max-n, &arg)
   639					n += c - 1 // +1 a few lines down
   640					anySymbolized = true
   641				}
   642			}
   643			n++
   644		}
   645		if anySymbolized {
   646			arg.pc = 0
   647			callCgoSymbolizer(&arg)
   648		}
   649		return n
   650	}
   651	
   652	func printcreatedby(gp *g) {
   653		// Show what created goroutine, except main goroutine (goid 1).
   654		pc := gp.gopc
   655		f := findfunc(pc)
   656		if f.valid() && showframe(f, gp, false, funcID_normal, funcID_normal) && gp.goid != 1 {
   657			printcreatedby1(f, pc)
   658		}
   659	}
   660	
   661	func printcreatedby1(f funcInfo, pc uintptr) {
   662		print("created by ", funcname(f), "\n")
   663		tracepc := pc // back up to CALL instruction for funcline.
   664		if pc > f.entry {
   665			tracepc -= sys.PCQuantum
   666		}
   667		file, line := funcline(f, tracepc)
   668		print("\t", file, ":", line)
   669		if pc > f.entry {
   670			print(" +", hex(pc-f.entry))
   671		}
   672		print("\n")
   673	}
   674	
   675	func traceback(pc, sp, lr uintptr, gp *g) {
   676		traceback1(pc, sp, lr, gp, 0)
   677	}
   678	
   679	// tracebacktrap is like traceback but expects that the PC and SP were obtained
   680	// from a trap, not from gp->sched or gp->syscallpc/gp->syscallsp or getcallerpc/getcallersp.
   681	// Because they are from a trap instead of from a saved pair,
   682	// the initial PC must not be rewound to the previous instruction.
   683	// (All the saved pairs record a PC that is a return address, so we
   684	// rewind it into the CALL instruction.)
   685	// If gp.m.libcall{g,pc,sp} information is available, it uses that information in preference to
   686	// the pc/sp/lr passed in.
   687	func tracebacktrap(pc, sp, lr uintptr, gp *g) {
   688		if gp.m.libcallsp != 0 {
   689			// We're in C code somewhere, traceback from the saved position.
   690			traceback1(gp.m.libcallpc, gp.m.libcallsp, 0, gp.m.libcallg.ptr(), 0)
   691			return
   692		}
   693		traceback1(pc, sp, lr, gp, _TraceTrap)
   694	}
   695	
   696	func traceback1(pc, sp, lr uintptr, gp *g, flags uint) {
   697		// If the goroutine is in cgo, and we have a cgo traceback, print that.
   698		if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 {
   699			// Lock cgoCallers so that a signal handler won't
   700			// change it, copy the array, reset it, unlock it.
   701			// We are locked to the thread and are not running
   702			// concurrently with a signal handler.
   703			// We just have to stop a signal handler from interrupting
   704			// in the middle of our copy.
   705			atomic.Store(&gp.m.cgoCallersUse, 1)
   706			cgoCallers := *gp.m.cgoCallers
   707			gp.m.cgoCallers[0] = 0
   708			atomic.Store(&gp.m.cgoCallersUse, 0)
   709	
   710			printCgoTraceback(&cgoCallers)
   711		}
   712	
   713		var n int
   714		if readgstatus(gp)&^_Gscan == _Gsyscall {
   715			// Override registers if blocked in system call.
   716			pc = gp.syscallpc
   717			sp = gp.syscallsp
   718			flags &^= _TraceTrap
   719		}
   720		// Print traceback. By default, omits runtime frames.
   721		// If that means we print nothing at all, repeat forcing all frames printed.
   722		n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags)
   723		if n == 0 && (flags&_TraceRuntimeFrames) == 0 {
   724			n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames)
   725		}
   726		if n == _TracebackMaxFrames {
   727			print("...additional frames elided...\n")
   728		}
   729		printcreatedby(gp)
   730	
   731		if gp.ancestors == nil {
   732			return
   733		}
   734		for _, ancestor := range *gp.ancestors {
   735			printAncestorTraceback(ancestor)
   736		}
   737	}
   738	
   739	// printAncestorTraceback prints the traceback of the given ancestor.
   740	// TODO: Unify this with gentraceback and CallersFrames.
   741	func printAncestorTraceback(ancestor ancestorInfo) {
   742		print("[originating from goroutine ", ancestor.goid, "]:\n")
   743		for fidx, pc := range ancestor.pcs {
   744			f := findfunc(pc) // f previously validated
   745			if showfuncinfo(f, fidx == 0, funcID_normal, funcID_normal) {
   746				printAncestorTracebackFuncInfo(f, pc)
   747			}
   748		}
   749		if len(ancestor.pcs) == _TracebackMaxFrames {
   750			print("...additional frames elided...\n")
   751		}
   752		// Show what created goroutine, except main goroutine (goid 1).
   753		f := findfunc(ancestor.gopc)
   754		if f.valid() && showfuncinfo(f, false, funcID_normal, funcID_normal) && ancestor.goid != 1 {
   755			printcreatedby1(f, ancestor.gopc)
   756		}
   757	}
   758	
   759	// printAncestorTraceback prints the given function info at a given pc
   760	// within an ancestor traceback. The precision of this info is reduced
   761	// due to only have access to the pcs at the time of the caller
   762	// goroutine being created.
   763	func printAncestorTracebackFuncInfo(f funcInfo, pc uintptr) {
   764		name := funcname(f)
   765		if inldata := funcdata(f, _FUNCDATA_InlTree); inldata != nil {
   766			inltree := (*[1 << 20]inlinedCall)(inldata)
   767			ix := pcdatavalue(f, _PCDATA_InlTreeIndex, pc, nil)
   768			if ix >= 0 {
   769				name = funcnameFromNameoff(f, inltree[ix].func_)
   770			}
   771		}
   772		file, line := funcline(f, pc)
   773		if name == "runtime.gopanic" {
   774			name = "panic"
   775		}
   776		print(name, "(...)\n")
   777		print("\t", file, ":", line)
   778		if pc > f.entry {
   779			print(" +", hex(pc-f.entry))
   780		}
   781		print("\n")
   782	}
   783	
   784	func callers(skip int, pcbuf []uintptr) int {
   785		sp := getcallersp()
   786		pc := getcallerpc()
   787		gp := getg()
   788		var n int
   789		systemstack(func() {
   790			n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   791		})
   792		return n
   793	}
   794	
   795	func gcallers(gp *g, skip int, pcbuf []uintptr) int {
   796		return gentraceback(^uintptr(0), ^uintptr(0), 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0)
   797	}
   798	
   799	// showframe reports whether the frame with the given characteristics should
   800	// be printed during a traceback.
   801	func showframe(f funcInfo, gp *g, firstFrame bool, funcID, childID funcID) bool {
   802		g := getg()
   803		if g.m.throwing > 0 && gp != nil && (gp == g.m.curg || gp == g.m.caughtsig.ptr()) {
   804			return true
   805		}
   806		return showfuncinfo(f, firstFrame, funcID, childID)
   807	}
   808	
   809	// showfuncinfo reports whether a function with the given characteristics should
   810	// be printed during a traceback.
   811	func showfuncinfo(f funcInfo, firstFrame bool, funcID, childID funcID) bool {
   812		level, _, _ := gotraceback()
   813		if level > 1 {
   814			// Show all frames.
   815			return true
   816		}
   817	
   818		if !f.valid() {
   819			return false
   820		}
   821	
   822		if funcID == funcID_wrapper && elideWrapperCalling(childID) {
   823			return false
   824		}
   825	
   826		name := funcname(f)
   827	
   828		// Special case: always show runtime.gopanic frame
   829		// in the middle of a stack trace, so that we can
   830		// see the boundary between ordinary code and
   831		// panic-induced deferred code.
   832		// See golang.org/issue/5832.
   833		if name == "runtime.gopanic" && !firstFrame {
   834			return true
   835		}
   836	
   837		return contains(name, ".") && (!hasPrefix(name, "runtime.") || isExportedRuntime(name))
   838	}
   839	
   840	// isExportedRuntime reports whether name is an exported runtime function.
   841	// It is only for runtime functions, so ASCII A-Z is fine.
   842	func isExportedRuntime(name string) bool {
   843		const n = len("runtime.")
   844		return len(name) > n && name[:n] == "runtime." && 'A' <= name[n] && name[n] <= 'Z'
   845	}
   846	
   847	// elideWrapperCalling reports whether a wrapper function that called
   848	// function id should be elided from stack traces.
   849	func elideWrapperCalling(id funcID) bool {
   850		// If the wrapper called a panic function instead of the
   851		// wrapped function, we want to include it in stacks.
   852		return !(id == funcID_gopanic || id == funcID_sigpanic || id == funcID_panicwrap)
   853	}
   854	
   855	var gStatusStrings = [...]string{
   856		_Gidle:      "idle",
   857		_Grunnable:  "runnable",
   858		_Grunning:   "running",
   859		_Gsyscall:   "syscall",
   860		_Gwaiting:   "waiting",
   861		_Gdead:      "dead",
   862		_Gcopystack: "copystack",
   863	}
   864	
   865	func goroutineheader(gp *g) {
   866		gpstatus := readgstatus(gp)
   867	
   868		isScan := gpstatus&_Gscan != 0
   869		gpstatus &^= _Gscan // drop the scan bit
   870	
   871		// Basic string status
   872		var status string
   873		if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) {
   874			status = gStatusStrings[gpstatus]
   875		} else {
   876			status = "???"
   877		}
   878	
   879		// Override.
   880		if gpstatus == _Gwaiting && gp.waitreason != waitReasonZero {
   881			status = gp.waitreason.String()
   882		}
   883	
   884		// approx time the G is blocked, in minutes
   885		var waitfor int64
   886		if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 {
   887			waitfor = (nanotime() - gp.waitsince) / 60e9
   888		}
   889		print("goroutine ", gp.goid, " [", status)
   890		if isScan {
   891			print(" (scan)")
   892		}
   893		if waitfor >= 1 {
   894			print(", ", waitfor, " minutes")
   895		}
   896		if gp.lockedm != 0 {
   897			print(", locked to thread")
   898		}
   899		print("]:\n")
   900	}
   901	
   902	func tracebackothers(me *g) {
   903		level, _, _ := gotraceback()
   904	
   905		// Show the current goroutine first, if we haven't already.
   906		g := getg()
   907		gp := g.m.curg
   908		if gp != nil && gp != me {
   909			print("\n")
   910			goroutineheader(gp)
   911			traceback(^uintptr(0), ^uintptr(0), 0, gp)
   912		}
   913	
   914		lock(&allglock)
   915		for _, gp := range allgs {
   916			if gp == me || gp == g.m.curg || readgstatus(gp) == _Gdead || isSystemGoroutine(gp, false) && level < 2 {
   917				continue
   918			}
   919			print("\n")
   920			goroutineheader(gp)
   921			// Note: gp.m == g.m occurs when tracebackothers is
   922			// called from a signal handler initiated during a
   923			// systemstack call. The original G is still in the
   924			// running state, and we want to print its stack.
   925			if gp.m != g.m && readgstatus(gp)&^_Gscan == _Grunning {
   926				print("\tgoroutine running on other thread; stack unavailable\n")
   927				printcreatedby(gp)
   928			} else {
   929				traceback(^uintptr(0), ^uintptr(0), 0, gp)
   930			}
   931		}
   932		unlock(&allglock)
   933	}
   934	
   935	// tracebackHexdump hexdumps part of stk around frame.sp and frame.fp
   936	// for debugging purposes. If the address bad is included in the
   937	// hexdumped range, it will mark it as well.
   938	func tracebackHexdump(stk stack, frame *stkframe, bad uintptr) {
   939		const expand = 32 * sys.PtrSize
   940		const maxExpand = 256 * sys.PtrSize
   941		// Start around frame.sp.
   942		lo, hi := frame.sp, frame.sp
   943		// Expand to include frame.fp.
   944		if frame.fp != 0 && frame.fp < lo {
   945			lo = frame.fp
   946		}
   947		if frame.fp != 0 && frame.fp > hi {
   948			hi = frame.fp
   949		}
   950		// Expand a bit more.
   951		lo, hi = lo-expand, hi+expand
   952		// But don't go too far from frame.sp.
   953		if lo < frame.sp-maxExpand {
   954			lo = frame.sp - maxExpand
   955		}
   956		if hi > frame.sp+maxExpand {
   957			hi = frame.sp + maxExpand
   958		}
   959		// And don't go outside the stack bounds.
   960		if lo < stk.lo {
   961			lo = stk.lo
   962		}
   963		if hi > stk.hi {
   964			hi = stk.hi
   965		}
   966	
   967		// Print the hex dump.
   968		print("stack: frame={sp:", hex(frame.sp), ", fp:", hex(frame.fp), "} stack=[", hex(stk.lo), ",", hex(stk.hi), ")\n")
   969		hexdumpWords(lo, hi, func(p uintptr) byte {
   970			switch p {
   971			case frame.fp:
   972				return '>'
   973			case frame.sp:
   974				return '<'
   975			case bad:
   976				return '!'
   977			}
   978			return 0
   979		})
   980	}
   981	
   982	// Does f mark the top of a goroutine stack?
   983	func topofstack(f funcInfo, g0 bool) bool {
   984		return f.funcID == funcID_goexit ||
   985			f.funcID == funcID_mstart ||
   986			f.funcID == funcID_mcall ||
   987			f.funcID == funcID_morestack ||
   988			f.funcID == funcID_rt0_go ||
   989			f.funcID == funcID_externalthreadhandler ||
   990			// asmcgocall is TOS on the system stack because it
   991			// switches to the system stack, but in this case we
   992			// can come back to the regular stack and still want
   993			// to be able to unwind through the call that appeared
   994			// on the regular stack.
   995			(g0 && f.funcID == funcID_asmcgocall)
   996	}
   997	
   998	// isSystemGoroutine reports whether the goroutine g must be omitted
   999	// in stack dumps and deadlock detector. This is any goroutine that
  1000	// starts at a runtime.* entry point, except for runtime.main and
  1001	// sometimes runtime.runfinq.
  1002	//
  1003	// If fixed is true, any goroutine that can vary between user and
  1004	// system (that is, the finalizer goroutine) is considered a user
  1005	// goroutine.
  1006	func isSystemGoroutine(gp *g, fixed bool) bool {
  1007		// Keep this in sync with cmd/trace/trace.go:isSystemGoroutine.
  1008		f := findfunc(gp.startpc)
  1009		if !f.valid() {
  1010			return false
  1011		}
  1012		if f.funcID == funcID_runtime_main {
  1013			return false
  1014		}
  1015		if f.funcID == funcID_runfinq {
  1016			// We include the finalizer goroutine if it's calling
  1017			// back into user code.
  1018			if fixed {
  1019				// This goroutine can vary. In fixed mode,
  1020				// always consider it a user goroutine.
  1021				return false
  1022			}
  1023			return !fingRunning
  1024		}
  1025		return hasPrefix(funcname(f), "runtime.")
  1026	}
  1027	
  1028	// SetCgoTraceback records three C functions to use to gather
  1029	// traceback information from C code and to convert that traceback
  1030	// information into symbolic information. These are used when printing
  1031	// stack traces for a program that uses cgo.
  1032	//
  1033	// The traceback and context functions may be called from a signal
  1034	// handler, and must therefore use only async-signal safe functions.
  1035	// The symbolizer function may be called while the program is
  1036	// crashing, and so must be cautious about using memory.  None of the
  1037	// functions may call back into Go.
  1038	//
  1039	// The context function will be called with a single argument, a
  1040	// pointer to a struct:
  1041	//
  1042	//	struct {
  1043	//		Context uintptr
  1044	//	}
  1045	//
  1046	// In C syntax, this struct will be
  1047	//
  1048	//	struct {
  1049	//		uintptr_t Context;
  1050	//	};
  1051	//
  1052	// If the Context field is 0, the context function is being called to
  1053	// record the current traceback context. It should record in the
  1054	// Context field whatever information is needed about the current
  1055	// point of execution to later produce a stack trace, probably the
  1056	// stack pointer and PC. In this case the context function will be
  1057	// called from C code.
  1058	//
  1059	// If the Context field is not 0, then it is a value returned by a
  1060	// previous call to the context function. This case is called when the
  1061	// context is no longer needed; that is, when the Go code is returning
  1062	// to its C code caller. This permits the context function to release
  1063	// any associated resources.
  1064	//
  1065	// While it would be correct for the context function to record a
  1066	// complete a stack trace whenever it is called, and simply copy that
  1067	// out in the traceback function, in a typical program the context
  1068	// function will be called many times without ever recording a
  1069	// traceback for that context. Recording a complete stack trace in a
  1070	// call to the context function is likely to be inefficient.
  1071	//
  1072	// The traceback function will be called with a single argument, a
  1073	// pointer to a struct:
  1074	//
  1075	//	struct {
  1076	//		Context    uintptr
  1077	//		SigContext uintptr
  1078	//		Buf        *uintptr
  1079	//		Max        uintptr
  1080	//	}
  1081	//
  1082	// In C syntax, this struct will be
  1083	//
  1084	//	struct {
  1085	//		uintptr_t  Context;
  1086	//		uintptr_t  SigContext;
  1087	//		uintptr_t* Buf;
  1088	//		uintptr_t  Max;
  1089	//	};
  1090	//
  1091	// The Context field will be zero to gather a traceback from the
  1092	// current program execution point. In this case, the traceback
  1093	// function will be called from C code.
  1094	//
  1095	// Otherwise Context will be a value previously returned by a call to
  1096	// the context function. The traceback function should gather a stack
  1097	// trace from that saved point in the program execution. The traceback
  1098	// function may be called from an execution thread other than the one
  1099	// that recorded the context, but only when the context is known to be
  1100	// valid and unchanging. The traceback function may also be called
  1101	// deeper in the call stack on the same thread that recorded the
  1102	// context. The traceback function may be called multiple times with
  1103	// the same Context value; it will usually be appropriate to cache the
  1104	// result, if possible, the first time this is called for a specific
  1105	// context value.
  1106	//
  1107	// If the traceback function is called from a signal handler on a Unix
  1108	// system, SigContext will be the signal context argument passed to
  1109	// the signal handler (a C ucontext_t* cast to uintptr_t). This may be
  1110	// used to start tracing at the point where the signal occurred. If
  1111	// the traceback function is not called from a signal handler,
  1112	// SigContext will be zero.
  1113	//
  1114	// Buf is where the traceback information should be stored. It should
  1115	// be PC values, such that Buf[0] is the PC of the caller, Buf[1] is
  1116	// the PC of that function's caller, and so on.  Max is the maximum
  1117	// number of entries to store.  The function should store a zero to
  1118	// indicate the top of the stack, or that the caller is on a different
  1119	// stack, presumably a Go stack.
  1120	//
  1121	// Unlike runtime.Callers, the PC values returned should, when passed
  1122	// to the symbolizer function, return the file/line of the call
  1123	// instruction.  No additional subtraction is required or appropriate.
  1124	//
  1125	// On all platforms, the traceback function is invoked when a call from
  1126	// Go to C to Go requests a stack trace. On linux/amd64, linux/ppc64le,
  1127	// and freebsd/amd64, the traceback function is also invoked when a
  1128	// signal is received by a thread that is executing a cgo call. The
  1129	// traceback function should not make assumptions about when it is
  1130	// called, as future versions of Go may make additional calls.
  1131	//
  1132	// The symbolizer function will be called with a single argument, a
  1133	// pointer to a struct:
  1134	//
  1135	//	struct {
  1136	//		PC      uintptr // program counter to fetch information for
  1137	//		File    *byte   // file name (NUL terminated)
  1138	//		Lineno  uintptr // line number
  1139	//		Func    *byte   // function name (NUL terminated)
  1140	//		Entry   uintptr // function entry point
  1141	//		More    uintptr // set non-zero if more info for this PC
  1142	//		Data    uintptr // unused by runtime, available for function
  1143	//	}
  1144	//
  1145	// In C syntax, this struct will be
  1146	//
  1147	//	struct {
  1148	//		uintptr_t PC;
  1149	//		char*     File;
  1150	//		uintptr_t Lineno;
  1151	//		char*     Func;
  1152	//		uintptr_t Entry;
  1153	//		uintptr_t More;
  1154	//		uintptr_t Data;
  1155	//	};
  1156	//
  1157	// The PC field will be a value returned by a call to the traceback
  1158	// function.
  1159	//
  1160	// The first time the function is called for a particular traceback,
  1161	// all the fields except PC will be 0. The function should fill in the
  1162	// other fields if possible, setting them to 0/nil if the information
  1163	// is not available. The Data field may be used to store any useful
  1164	// information across calls. The More field should be set to non-zero
  1165	// if there is more information for this PC, zero otherwise. If More
  1166	// is set non-zero, the function will be called again with the same
  1167	// PC, and may return different information (this is intended for use
  1168	// with inlined functions). If More is zero, the function will be
  1169	// called with the next PC value in the traceback. When the traceback
  1170	// is complete, the function will be called once more with PC set to
  1171	// zero; this may be used to free any information. Each call will
  1172	// leave the fields of the struct set to the same values they had upon
  1173	// return, except for the PC field when the More field is zero. The
  1174	// function must not keep a copy of the struct pointer between calls.
  1175	//
  1176	// When calling SetCgoTraceback, the version argument is the version
  1177	// number of the structs that the functions expect to receive.
  1178	// Currently this must be zero.
  1179	//
  1180	// The symbolizer function may be nil, in which case the results of
  1181	// the traceback function will be displayed as numbers. If the
  1182	// traceback function is nil, the symbolizer function will never be
  1183	// called. The context function may be nil, in which case the
  1184	// traceback function will only be called with the context field set
  1185	// to zero.  If the context function is nil, then calls from Go to C
  1186	// to Go will not show a traceback for the C portion of the call stack.
  1187	//
  1188	// SetCgoTraceback should be called only once, ideally from an init function.
  1189	func SetCgoTraceback(version int, traceback, context, symbolizer unsafe.Pointer) {
  1190		if version != 0 {
  1191			panic("unsupported version")
  1192		}
  1193	
  1194		if cgoTraceback != nil && cgoTraceback != traceback ||
  1195			cgoContext != nil && cgoContext != context ||
  1196			cgoSymbolizer != nil && cgoSymbolizer != symbolizer {
  1197			panic("call SetCgoTraceback only once")
  1198		}
  1199	
  1200		cgoTraceback = traceback
  1201		cgoContext = context
  1202		cgoSymbolizer = symbolizer
  1203	
  1204		// The context function is called when a C function calls a Go
  1205		// function. As such it is only called by C code in runtime/cgo.
  1206		if _cgo_set_context_function != nil {
  1207			cgocall(_cgo_set_context_function, context)
  1208		}
  1209	}
  1210	
  1211	var cgoTraceback unsafe.Pointer
  1212	var cgoContext unsafe.Pointer
  1213	var cgoSymbolizer unsafe.Pointer
  1214	
  1215	// cgoTracebackArg is the type passed to cgoTraceback.
  1216	type cgoTracebackArg struct {
  1217		context    uintptr
  1218		sigContext uintptr
  1219		buf        *uintptr
  1220		max        uintptr
  1221	}
  1222	
  1223	// cgoContextArg is the type passed to the context function.
  1224	type cgoContextArg struct {
  1225		context uintptr
  1226	}
  1227	
  1228	// cgoSymbolizerArg is the type passed to cgoSymbolizer.
  1229	type cgoSymbolizerArg struct {
  1230		pc       uintptr
  1231		file     *byte
  1232		lineno   uintptr
  1233		funcName *byte
  1234		entry    uintptr
  1235		more     uintptr
  1236		data     uintptr
  1237	}
  1238	
  1239	// cgoTraceback prints a traceback of callers.
  1240	func printCgoTraceback(callers *cgoCallers) {
  1241		if cgoSymbolizer == nil {
  1242			for _, c := range callers {
  1243				if c == 0 {
  1244					break
  1245				}
  1246				print("non-Go function at pc=", hex(c), "\n")
  1247			}
  1248			return
  1249		}
  1250	
  1251		var arg cgoSymbolizerArg
  1252		for _, c := range callers {
  1253			if c == 0 {
  1254				break
  1255			}
  1256			printOneCgoTraceback(c, 0x7fffffff, &arg)
  1257		}
  1258		arg.pc = 0
  1259		callCgoSymbolizer(&arg)
  1260	}
  1261	
  1262	// printOneCgoTraceback prints the traceback of a single cgo caller.
  1263	// This can print more than one line because of inlining.
  1264	// Returns the number of frames printed.
  1265	func printOneCgoTraceback(pc uintptr, max int, arg *cgoSymbolizerArg) int {
  1266		c := 0
  1267		arg.pc = pc
  1268		for c <= max {
  1269			callCgoSymbolizer(arg)
  1270			if arg.funcName != nil {
  1271				// Note that we don't print any argument
  1272				// information here, not even parentheses.
  1273				// The symbolizer must add that if appropriate.
  1274				println(gostringnocopy(arg.funcName))
  1275			} else {
  1276				println("non-Go function")
  1277			}
  1278			print("\t")
  1279			if arg.file != nil {
  1280				print(gostringnocopy(arg.file), ":", arg.lineno, " ")
  1281			}
  1282			print("pc=", hex(pc), "\n")
  1283			c++
  1284			if arg.more == 0 {
  1285				break
  1286			}
  1287		}
  1288		return c
  1289	}
  1290	
  1291	// callCgoSymbolizer calls the cgoSymbolizer function.
  1292	func callCgoSymbolizer(arg *cgoSymbolizerArg) {
  1293		call := cgocall
  1294		if panicking > 0 || getg().m.curg != getg() {
  1295			// We do not want to call into the scheduler when panicking
  1296			// or when on the system stack.
  1297			call = asmcgocall
  1298		}
  1299		if msanenabled {
  1300			msanwrite(unsafe.Pointer(arg), unsafe.Sizeof(cgoSymbolizerArg{}))
  1301		}
  1302		call(cgoSymbolizer, noescape(unsafe.Pointer(arg)))
  1303	}
  1304	
  1305	// cgoContextPCs gets the PC values from a cgo traceback.
  1306	func cgoContextPCs(ctxt uintptr, buf []uintptr) {
  1307		if cgoTraceback == nil {
  1308			return
  1309		}
  1310		call := cgocall
  1311		if panicking > 0 || getg().m.curg != getg() {
  1312			// We do not want to call into the scheduler when panicking
  1313			// or when on the system stack.
  1314			call = asmcgocall
  1315		}
  1316		arg := cgoTracebackArg{
  1317			context: ctxt,
  1318			buf:     (*uintptr)(noescape(unsafe.Pointer(&buf[0]))),
  1319			max:     uintptr(len(buf)),
  1320		}
  1321		if msanenabled {
  1322			msanwrite(unsafe.Pointer(&arg), unsafe.Sizeof(arg))
  1323		}
  1324		call(cgoTraceback, noescape(unsafe.Pointer(&arg)))
  1325	}
  1326	

View as plain text