Source file src/runtime/tracestack.go

     1  // Copyright 2023 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  // Trace stack table and acquisition.
     6  
     7  package runtime
     8  
     9  import (
    10  	"internal/abi"
    11  	"internal/goarch"
    12  	"internal/trace/tracev2"
    13  	"unsafe"
    14  )
    15  
    16  const (
    17  	// logicalStackSentinel is a sentinel value at pcBuf[0] signifying that
    18  	// pcBuf[1:] holds a logical stack requiring no further processing. Any other
    19  	// value at pcBuf[0] represents a skip value to apply to the physical stack in
    20  	// pcBuf[1:] after inline expansion.
    21  	logicalStackSentinel = ^uintptr(0)
    22  )
    23  
    24  // traceStack captures a stack trace from a goroutine and registers it in the trace
    25  // stack table. It then returns its unique ID. If gp == nil, then traceStack will
    26  // attempt to use the current execution context.
    27  //
    28  // skip controls the number of leaf frames to omit in order to hide tracer internals
    29  // from stack traces, see CL 5523.
    30  //
    31  // Avoid calling this function directly. gen needs to be the current generation
    32  // that this stack trace is being written out for, which needs to be synchronized with
    33  // generations moving forward. Prefer traceEventWriter.stack.
    34  func traceStack(skip int, gp *g, gen uintptr) uint64 {
    35  	var pcBuf [tracev2.MaxFramesPerStack]uintptr
    36  
    37  	// Figure out gp and mp for the backtrace.
    38  	var mp *m
    39  	if gp == nil {
    40  		mp = getg().m
    41  		gp = mp.curg
    42  	}
    43  
    44  	// Double-check that we own the stack we're about to trace.
    45  	if debug.traceCheckStackOwnership != 0 && gp != nil {
    46  		status := readgstatus(gp)
    47  		// If the scan bit is set, assume we're the ones that acquired it.
    48  		if status&_Gscan == 0 {
    49  			// Use the trace status to check this. There are a number of cases
    50  			// where a running goroutine might be in _Gwaiting, and these cases
    51  			// are totally fine for taking a stack trace. They're captured
    52  			// correctly in goStatusToTraceGoStatus.
    53  			switch goStatusToTraceGoStatus(status, gp.waitreason) {
    54  			case tracev2.GoRunning, tracev2.GoSyscall:
    55  				if getg() == gp || mp.curg == gp {
    56  					break
    57  				}
    58  				fallthrough
    59  			default:
    60  				print("runtime: gp=", unsafe.Pointer(gp), " gp.goid=", gp.goid, " status=", gStatusStrings[status], "\n")
    61  				throw("attempted to trace stack of a goroutine this thread does not own")
    62  			}
    63  		}
    64  	}
    65  
    66  	if gp != nil && mp == nil {
    67  		// We're getting the backtrace for a G that's not currently executing.
    68  		// It may still have an M, if it's locked to some M.
    69  		mp = gp.lockedm.ptr()
    70  	}
    71  	nstk := 1
    72  	if tracefpunwindoff() || (mp != nil && mp.hasCgoOnStack()) {
    73  		// Slow path: Unwind using default unwinder. Used when frame pointer
    74  		// unwinding is unavailable or disabled (tracefpunwindoff), or might
    75  		// produce incomplete results or crashes (hasCgoOnStack). Note that no
    76  		// cgo callback related crashes have been observed yet. The main
    77  		// motivation is to take advantage of a potentially registered cgo
    78  		// symbolizer.
    79  		pcBuf[0] = logicalStackSentinel
    80  		if getg() == gp {
    81  			nstk += callers(skip+1, pcBuf[1:])
    82  		} else if gp != nil {
    83  			nstk += gcallers(gp, skip, pcBuf[1:])
    84  		}
    85  	} else {
    86  		// Fast path: Unwind using frame pointers.
    87  		pcBuf[0] = uintptr(skip)
    88  		if getg() == gp {
    89  			nstk += fpTracebackPCs(unsafe.Pointer(getfp()), pcBuf[1:])
    90  		} else if gp != nil {
    91  			// Three cases:
    92  			//
    93  			// (1) We're called on the g0 stack through mcall(fn) or systemstack(fn). To
    94  			// behave like gcallers above, we start unwinding from sched.bp, which
    95  			// points to the caller frame of the leaf frame on g's stack. The return
    96  			// address of the leaf frame is stored in sched.pc, which we manually
    97  			// capture here.
    98  			//
    99  			// (2) We're called against a gp that we're not currently executing on, but that isn't
   100  			// in a syscall, in which case it's currently not executing. gp.sched contains the most
   101  			// up-to-date information about where it stopped, and like case (1), we match gcallers
   102  			// here.
   103  			//
   104  			// (3) We're called against a gp that we're not currently executing on, but that is in
   105  			// a syscall, in which case gp.syscallsp != 0. gp.syscall* contains the most up-to-date
   106  			// information about where it stopped, and like case (1), we match gcallers here.
   107  			if gp.syscallsp != 0 {
   108  				pcBuf[1] = gp.syscallpc
   109  				nstk += 1 + fpTracebackPCs(unsafe.Pointer(gp.syscallbp), pcBuf[2:])
   110  			} else {
   111  				pcBuf[1] = gp.sched.pc
   112  				if gp.syncSafePoint {
   113  					// We're stopped in morestack, which is an odd state because gp.sched.bp
   114  					// refers to our parent frame, since we haven't had the chance to push our
   115  					// frame pointer to the stack yet. If we just start walking from gp.sched.bp,
   116  					// we'll skip a frame as a result. Luckily, we can find the PC we want right
   117  					// at gp.sched.sp on non-LR platforms, and we have it directly on LR platforms.
   118  					// See issue go.dev/issue/68090.
   119  					if usesLR {
   120  						pcBuf[2] = gp.sched.lr
   121  					} else {
   122  						pcBuf[2] = *(*uintptr)(unsafe.Pointer(gp.sched.sp))
   123  					}
   124  					nstk += 2 + fpTracebackPCs(unsafe.Pointer(gp.sched.bp), pcBuf[3:])
   125  				} else {
   126  					nstk += 1 + fpTracebackPCs(unsafe.Pointer(gp.sched.bp), pcBuf[2:])
   127  				}
   128  			}
   129  		}
   130  	}
   131  	if nstk > 0 {
   132  		nstk-- // skip runtime.goexit
   133  	}
   134  	if nstk > 0 && gp.goid == 1 {
   135  		nstk-- // skip runtime.main
   136  	}
   137  	id := trace.stackTab[gen%2].put(pcBuf[:nstk])
   138  	return id
   139  }
   140  
   141  // traceStackTable maps stack traces (arrays of PC's) to unique uint32 ids.
   142  // It is lock-free for reading.
   143  type traceStackTable struct {
   144  	tab traceMap
   145  }
   146  
   147  // put returns a unique id for the stack trace pcs and caches it in the table,
   148  // if it sees the trace for the first time.
   149  func (t *traceStackTable) put(pcs []uintptr) uint64 {
   150  	if len(pcs) == 0 {
   151  		return 0
   152  	}
   153  	id, _ := t.tab.put(noescape(unsafe.Pointer(&pcs[0])), uintptr(len(pcs))*unsafe.Sizeof(uintptr(0)))
   154  	return id
   155  }
   156  
   157  // dump writes all previously cached stacks to trace buffers,
   158  // releases all memory and resets state. It must only be called once the caller
   159  // can guarantee that there are no more writers to the table.
   160  func (t *traceStackTable) dump(gen uintptr) {
   161  	stackBuf := make([]uintptr, tracev2.MaxFramesPerStack)
   162  	w := unsafeTraceWriter(gen, nil)
   163  	if root := (*traceMapNode)(t.tab.root.Load()); root != nil {
   164  		w = dumpStacksRec(root, w, stackBuf)
   165  	}
   166  	w.flush().end()
   167  	t.tab.reset()
   168  }
   169  
   170  func dumpStacksRec(node *traceMapNode, w traceWriter, stackBuf []uintptr) traceWriter {
   171  	stack := unsafe.Slice((*uintptr)(unsafe.Pointer(&node.data[0])), uintptr(len(node.data))/unsafe.Sizeof(uintptr(0)))
   172  
   173  	// N.B. This might allocate, but that's OK because we're not writing to the M's buffer,
   174  	// but one we're about to create (with ensure).
   175  	n := fpunwindExpand(stackBuf, stack)
   176  	frames := makeTraceFrames(w.gen, stackBuf[:n])
   177  
   178  	// The maximum number of bytes required to hold the encoded stack, given that
   179  	// it contains N frames.
   180  	maxBytes := 1 + (2+4*len(frames))*traceBytesPerNumber
   181  
   182  	// Estimate the size of this record. This
   183  	// bound is pretty loose, but avoids counting
   184  	// lots of varint sizes.
   185  	//
   186  	// Add 1 because we might also write tracev2.EvStacks.
   187  	var flushed bool
   188  	w, flushed = w.ensure(1 + maxBytes)
   189  	if flushed {
   190  		w.byte(byte(tracev2.EvStacks))
   191  	}
   192  
   193  	// Emit stack event.
   194  	w.byte(byte(tracev2.EvStack))
   195  	w.varint(uint64(node.id))
   196  	w.varint(uint64(len(frames)))
   197  	for _, frame := range frames {
   198  		w.varint(uint64(frame.PC))
   199  		w.varint(frame.funcID)
   200  		w.varint(frame.fileID)
   201  		w.varint(frame.line)
   202  	}
   203  
   204  	// Recursively walk all child nodes.
   205  	for i := range node.children {
   206  		child := node.children[i].Load()
   207  		if child == nil {
   208  			continue
   209  		}
   210  		w = dumpStacksRec((*traceMapNode)(child), w, stackBuf)
   211  	}
   212  	return w
   213  }
   214  
   215  // makeTraceFrames returns the frames corresponding to pcs. It may
   216  // allocate and may emit trace events.
   217  func makeTraceFrames(gen uintptr, pcs []uintptr) []traceFrame {
   218  	frames := make([]traceFrame, 0, len(pcs))
   219  	ci := CallersFrames(pcs)
   220  	for {
   221  		f, more := ci.Next()
   222  		frames = append(frames, makeTraceFrame(gen, f))
   223  		if !more {
   224  			return frames
   225  		}
   226  	}
   227  }
   228  
   229  type traceFrame struct {
   230  	PC     uintptr
   231  	funcID uint64
   232  	fileID uint64
   233  	line   uint64
   234  }
   235  
   236  // makeTraceFrame sets up a traceFrame for a frame.
   237  func makeTraceFrame(gen uintptr, f Frame) traceFrame {
   238  	var frame traceFrame
   239  	frame.PC = f.PC
   240  
   241  	fn := f.Function
   242  	const maxLen = 1 << 10
   243  	if len(fn) > maxLen {
   244  		fn = fn[len(fn)-maxLen:]
   245  	}
   246  	frame.funcID = trace.stringTab[gen%2].put(gen, fn)
   247  	frame.line = uint64(f.Line)
   248  	file := f.File
   249  	if len(file) > maxLen {
   250  		file = file[len(file)-maxLen:]
   251  	}
   252  	frame.fileID = trace.stringTab[gen%2].put(gen, file)
   253  	return frame
   254  }
   255  
   256  // tracefpunwindoff returns true if frame pointer unwinding for the tracer is
   257  // disabled via GODEBUG or not supported by the architecture.
   258  func tracefpunwindoff() bool {
   259  	return debug.tracefpunwindoff != 0 || (goarch.ArchFamily != goarch.AMD64 && goarch.ArchFamily != goarch.ARM64)
   260  }
   261  
   262  // fpTracebackPCs populates pcBuf with the return addresses for each frame and
   263  // returns the number of PCs written to pcBuf. The returned PCs correspond to
   264  // "physical frames" rather than "logical frames"; that is if A is inlined into
   265  // B, this will return a PC for only B.
   266  func fpTracebackPCs(fp unsafe.Pointer, pcBuf []uintptr) (i int) {
   267  	for i = 0; i < len(pcBuf) && fp != nil; i++ {
   268  		// return addr sits one word above the frame pointer
   269  		pcBuf[i] = *(*uintptr)(unsafe.Pointer(uintptr(fp) + goarch.PtrSize))
   270  		// follow the frame pointer to the next one
   271  		fp = unsafe.Pointer(*(*uintptr)(fp))
   272  	}
   273  	return i
   274  }
   275  
   276  //go:linkname pprof_fpunwindExpand
   277  func pprof_fpunwindExpand(dst, src []uintptr) int {
   278  	return fpunwindExpand(dst, src)
   279  }
   280  
   281  // fpunwindExpand expands a call stack from pcBuf into dst,
   282  // returning the number of PCs written to dst.
   283  // pcBuf and dst should not overlap.
   284  //
   285  // fpunwindExpand checks if pcBuf contains logical frames (which include inlined
   286  // frames) or physical frames (produced by frame pointer unwinding) using a
   287  // sentinel value in pcBuf[0]. Logical frames are simply returned without the
   288  // sentinel. Physical frames are turned into logical frames via inline unwinding
   289  // and by applying the skip value that's stored in pcBuf[0].
   290  func fpunwindExpand(dst, pcBuf []uintptr) int {
   291  	if len(pcBuf) == 0 {
   292  		return 0
   293  	} else if len(pcBuf) > 0 && pcBuf[0] == logicalStackSentinel {
   294  		// pcBuf contains logical rather than inlined frames, skip has already been
   295  		// applied, just return it without the sentinel value in pcBuf[0].
   296  		return copy(dst, pcBuf[1:])
   297  	}
   298  
   299  	var (
   300  		n          int
   301  		lastFuncID = abi.FuncIDNormal
   302  		skip       = pcBuf[0]
   303  		// skipOrAdd skips or appends retPC to newPCBuf and returns true if more
   304  		// pcs can be added.
   305  		skipOrAdd = func(retPC uintptr) bool {
   306  			if skip > 0 {
   307  				skip--
   308  			} else if n < len(dst) {
   309  				dst[n] = retPC
   310  				n++
   311  			}
   312  			return n < len(dst)
   313  		}
   314  	)
   315  
   316  outer:
   317  	for _, retPC := range pcBuf[1:] {
   318  		callPC := retPC - 1
   319  		fi := findfunc(callPC)
   320  		if !fi.valid() {
   321  			// There is no funcInfo if callPC belongs to a C function. In this case
   322  			// we still keep the pc, but don't attempt to expand inlined frames.
   323  			if more := skipOrAdd(retPC); !more {
   324  				break outer
   325  			}
   326  			continue
   327  		}
   328  
   329  		u, uf := newInlineUnwinder(fi, callPC)
   330  		for ; uf.valid(); uf = u.next(uf) {
   331  			sf := u.srcFunc(uf)
   332  			if sf.funcID == abi.FuncIDWrapper && elideWrapperCalling(lastFuncID) {
   333  				// ignore wrappers
   334  			} else if more := skipOrAdd(uf.pc + 1); !more {
   335  				break outer
   336  			}
   337  			lastFuncID = sf.funcID
   338  		}
   339  	}
   340  	return n
   341  }
   342  
   343  // startPCForTrace returns the start PC of a goroutine for tracing purposes.
   344  // If pc is a wrapper, it returns the PC of the wrapped function. Otherwise it
   345  // returns pc.
   346  func startPCForTrace(pc uintptr) uintptr {
   347  	f := findfunc(pc)
   348  	if !f.valid() {
   349  		return pc // may happen for locked g in extra M since its pc is 0.
   350  	}
   351  	w := funcdata(f, abi.FUNCDATA_WrapInfo)
   352  	if w == nil {
   353  		return pc // not a wrapper
   354  	}
   355  	return f.datap.textAddr(*(*uint32)(w))
   356  }
   357  

View as plain text