...

Source file src/runtime/traceback.go

Documentation: runtime

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

View as plain text