Source file src/runtime/symtab.go

     1  // Copyright 2014 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/abi"
     9  	"internal/goarch"
    10  	"internal/runtime/atomic"
    11  	"runtime/internal/sys"
    12  	"unsafe"
    13  )
    14  
    15  // Frames may be used to get function/file/line information for a
    16  // slice of PC values returned by [Callers].
    17  type Frames struct {
    18  	// callers is a slice of PCs that have not yet been expanded to frames.
    19  	callers []uintptr
    20  
    21  	// nextPC is a next PC to expand ahead of processing callers.
    22  	nextPC uintptr
    23  
    24  	// frames is a slice of Frames that have yet to be returned.
    25  	frames     []Frame
    26  	frameStore [2]Frame
    27  }
    28  
    29  // Frame is the information returned by [Frames] for each call frame.
    30  type Frame struct {
    31  	// PC is the program counter for the location in this frame.
    32  	// For a frame that calls another frame, this will be the
    33  	// program counter of a call instruction. Because of inlining,
    34  	// multiple frames may have the same PC value, but different
    35  	// symbolic information.
    36  	PC uintptr
    37  
    38  	// Func is the Func value of this call frame. This may be nil
    39  	// for non-Go code or fully inlined functions.
    40  	Func *Func
    41  
    42  	// Function is the package path-qualified function name of
    43  	// this call frame. If non-empty, this string uniquely
    44  	// identifies a single function in the program.
    45  	// This may be the empty string if not known.
    46  	// If Func is not nil then Function == Func.Name().
    47  	Function string
    48  
    49  	// File and Line are the file name and line number of the
    50  	// location in this frame. For non-leaf frames, this will be
    51  	// the location of a call. These may be the empty string and
    52  	// zero, respectively, if not known.
    53  	File string
    54  	Line int
    55  
    56  	// startLine is the line number of the beginning of the function in
    57  	// this frame. Specifically, it is the line number of the func keyword
    58  	// for Go functions. Note that //line directives can change the
    59  	// filename and/or line number arbitrarily within a function, meaning
    60  	// that the Line - startLine offset is not always meaningful.
    61  	//
    62  	// This may be zero if not known.
    63  	startLine int
    64  
    65  	// Entry point program counter for the function; may be zero
    66  	// if not known. If Func is not nil then Entry ==
    67  	// Func.Entry().
    68  	Entry uintptr
    69  
    70  	// The runtime's internal view of the function. This field
    71  	// is set (funcInfo.valid() returns true) only for Go functions,
    72  	// not for C functions.
    73  	funcInfo funcInfo
    74  }
    75  
    76  // CallersFrames takes a slice of PC values returned by [Callers] and
    77  // prepares to return function/file/line information.
    78  // Do not change the slice until you are done with the [Frames].
    79  func CallersFrames(callers []uintptr) *Frames {
    80  	f := &Frames{callers: callers}
    81  	f.frames = f.frameStore[:0]
    82  	return f
    83  }
    84  
    85  // Next returns a [Frame] representing the next call frame in the slice
    86  // of PC values. If it has already returned all call frames, Next
    87  // returns a zero [Frame].
    88  //
    89  // The more result indicates whether the next call to Next will return
    90  // a valid [Frame]. It does not necessarily indicate whether this call
    91  // returned one.
    92  //
    93  // See the [Frames] example for idiomatic usage.
    94  func (ci *Frames) Next() (frame Frame, more bool) {
    95  	for len(ci.frames) < 2 {
    96  		// Find the next frame.
    97  		// We need to look for 2 frames so we know what
    98  		// to return for the "more" result.
    99  		if len(ci.callers) == 0 {
   100  			break
   101  		}
   102  		var pc uintptr
   103  		if ci.nextPC != 0 {
   104  			pc, ci.nextPC = ci.nextPC, 0
   105  		} else {
   106  			pc, ci.callers = ci.callers[0], ci.callers[1:]
   107  		}
   108  		funcInfo := findfunc(pc)
   109  		if !funcInfo.valid() {
   110  			if cgoSymbolizer != nil {
   111  				// Pre-expand cgo frames. We could do this
   112  				// incrementally, too, but there's no way to
   113  				// avoid allocation in this case anyway.
   114  				ci.frames = append(ci.frames, expandCgoFrames(pc)...)
   115  			}
   116  			continue
   117  		}
   118  		f := funcInfo._Func()
   119  		entry := f.Entry()
   120  		if pc > entry {
   121  			// We store the pc of the start of the instruction following
   122  			// the instruction in question (the call or the inline mark).
   123  			// This is done for historical reasons, and to make FuncForPC
   124  			// work correctly for entries in the result of runtime.Callers.
   125  			pc--
   126  		}
   127  		// It's important that interpret pc non-strictly as cgoTraceback may
   128  		// have added bogus PCs with a valid funcInfo but invalid PCDATA.
   129  		u, uf := newInlineUnwinder(funcInfo, pc)
   130  		sf := u.srcFunc(uf)
   131  		if u.isInlined(uf) {
   132  			// Note: entry is not modified. It always refers to a real frame, not an inlined one.
   133  			// File/line from funcline1 below are already correct.
   134  			f = nil
   135  
   136  			// When CallersFrame is invoked using the PC list returned by Callers,
   137  			// the PC list includes virtual PCs corresponding to each outer frame
   138  			// around an innermost real inlined PC.
   139  			// We also want to support code passing in a PC list extracted from a
   140  			// stack trace, and there only the real PCs are printed, not the virtual ones.
   141  			// So check to see if the implied virtual PC for this PC (obtained from the
   142  			// unwinder itself) is the next PC in ci.callers. If not, insert it.
   143  			// The +1 here correspond to the pc-- above: the output of Callers
   144  			// and therefore the input to CallersFrames is return PCs from the stack;
   145  			// The pc-- backs up into the CALL instruction (not the first byte of the CALL
   146  			// instruction, but good enough to find it nonetheless).
   147  			// There are no cycles in implied virtual PCs (some number of frames were
   148  			// inlined, but that number is finite), so this unpacking cannot cause an infinite loop.
   149  			for unext := u.next(uf); unext.valid() && len(ci.callers) > 0 && ci.callers[0] != unext.pc+1; unext = u.next(unext) {
   150  				snext := u.srcFunc(unext)
   151  				if snext.funcID == abi.FuncIDWrapper && elideWrapperCalling(sf.funcID) {
   152  					// Skip, because tracebackPCs (inside runtime.Callers) would too.
   153  					continue
   154  				}
   155  				ci.nextPC = unext.pc + 1
   156  				break
   157  			}
   158  		}
   159  		ci.frames = append(ci.frames, Frame{
   160  			PC:        pc,
   161  			Func:      f,
   162  			Function:  funcNameForPrint(sf.name()),
   163  			Entry:     entry,
   164  			startLine: int(sf.startLine),
   165  			funcInfo:  funcInfo,
   166  			// Note: File,Line set below
   167  		})
   168  	}
   169  
   170  	// Pop one frame from the frame list. Keep the rest.
   171  	// Avoid allocation in the common case, which is 1 or 2 frames.
   172  	switch len(ci.frames) {
   173  	case 0: // In the rare case when there are no frames at all, we return Frame{}.
   174  		return
   175  	case 1:
   176  		frame = ci.frames[0]
   177  		ci.frames = ci.frameStore[:0]
   178  	case 2:
   179  		frame = ci.frames[0]
   180  		ci.frameStore[0] = ci.frames[1]
   181  		ci.frames = ci.frameStore[:1]
   182  	default:
   183  		frame = ci.frames[0]
   184  		ci.frames = ci.frames[1:]
   185  	}
   186  	more = len(ci.frames) > 0
   187  	if frame.funcInfo.valid() {
   188  		// Compute file/line just before we need to return it,
   189  		// as it can be expensive. This avoids computing file/line
   190  		// for the Frame we find but don't return. See issue 32093.
   191  		file, line := funcline1(frame.funcInfo, frame.PC, false)
   192  		frame.File, frame.Line = file, int(line)
   193  	}
   194  	return
   195  }
   196  
   197  // runtime_FrameStartLine returns the start line of the function in a Frame.
   198  //
   199  //go:linkname runtime_FrameStartLine runtime/pprof.runtime_FrameStartLine
   200  func runtime_FrameStartLine(f *Frame) int {
   201  	return f.startLine
   202  }
   203  
   204  // runtime_FrameSymbolName returns the full symbol name of the function in a Frame.
   205  // For generic functions this differs from f.Function in that this doesn't replace
   206  // the shape name to "...".
   207  //
   208  //go:linkname runtime_FrameSymbolName runtime/pprof.runtime_FrameSymbolName
   209  func runtime_FrameSymbolName(f *Frame) string {
   210  	if !f.funcInfo.valid() {
   211  		return f.Function
   212  	}
   213  	u, uf := newInlineUnwinder(f.funcInfo, f.PC)
   214  	sf := u.srcFunc(uf)
   215  	return sf.name()
   216  }
   217  
   218  // runtime_expandFinalInlineFrame expands the final pc in stk to include all
   219  // "callers" if pc is inline.
   220  //
   221  //go:linkname runtime_expandFinalInlineFrame runtime/pprof.runtime_expandFinalInlineFrame
   222  func runtime_expandFinalInlineFrame(stk []uintptr) []uintptr {
   223  	// TODO: It would be more efficient to report only physical PCs to pprof and
   224  	// just expand the whole stack.
   225  	if len(stk) == 0 {
   226  		return stk
   227  	}
   228  	pc := stk[len(stk)-1]
   229  	tracepc := pc - 1
   230  
   231  	f := findfunc(tracepc)
   232  	if !f.valid() {
   233  		// Not a Go function.
   234  		return stk
   235  	}
   236  
   237  	u, uf := newInlineUnwinder(f, tracepc)
   238  	if !u.isInlined(uf) {
   239  		// Nothing inline at tracepc.
   240  		return stk
   241  	}
   242  
   243  	// Treat the previous func as normal. We haven't actually checked, but
   244  	// since this pc was included in the stack, we know it shouldn't be
   245  	// elided.
   246  	calleeID := abi.FuncIDNormal
   247  
   248  	// Remove pc from stk; we'll re-add it below.
   249  	stk = stk[:len(stk)-1]
   250  
   251  	for ; uf.valid(); uf = u.next(uf) {
   252  		funcID := u.srcFunc(uf).funcID
   253  		if funcID == abi.FuncIDWrapper && elideWrapperCalling(calleeID) {
   254  			// ignore wrappers
   255  		} else {
   256  			stk = append(stk, uf.pc+1)
   257  		}
   258  		calleeID = funcID
   259  	}
   260  
   261  	return stk
   262  }
   263  
   264  // expandCgoFrames expands frame information for pc, known to be
   265  // a non-Go function, using the cgoSymbolizer hook. expandCgoFrames
   266  // returns nil if pc could not be expanded.
   267  func expandCgoFrames(pc uintptr) []Frame {
   268  	arg := cgoSymbolizerArg{pc: pc}
   269  	callCgoSymbolizer(&arg)
   270  
   271  	if arg.file == nil && arg.funcName == nil {
   272  		// No useful information from symbolizer.
   273  		return nil
   274  	}
   275  
   276  	var frames []Frame
   277  	for {
   278  		frames = append(frames, Frame{
   279  			PC:       pc,
   280  			Func:     nil,
   281  			Function: gostring(arg.funcName),
   282  			File:     gostring(arg.file),
   283  			Line:     int(arg.lineno),
   284  			Entry:    arg.entry,
   285  			// funcInfo is zero, which implies !funcInfo.valid().
   286  			// That ensures that we use the File/Line info given here.
   287  		})
   288  		if arg.more == 0 {
   289  			break
   290  		}
   291  		callCgoSymbolizer(&arg)
   292  	}
   293  
   294  	// No more frames for this PC. Tell the symbolizer we are done.
   295  	// We don't try to maintain a single cgoSymbolizerArg for the
   296  	// whole use of Frames, because there would be no good way to tell
   297  	// the symbolizer when we are done.
   298  	arg.pc = 0
   299  	callCgoSymbolizer(&arg)
   300  
   301  	return frames
   302  }
   303  
   304  // NOTE: Func does not expose the actual unexported fields, because we return *Func
   305  // values to users, and we want to keep them from being able to overwrite the data
   306  // with (say) *f = Func{}.
   307  // All code operating on a *Func must call raw() to get the *_func
   308  // or funcInfo() to get the funcInfo instead.
   309  
   310  // A Func represents a Go function in the running binary.
   311  type Func struct {
   312  	opaque struct{} // unexported field to disallow conversions
   313  }
   314  
   315  func (f *Func) raw() *_func {
   316  	return (*_func)(unsafe.Pointer(f))
   317  }
   318  
   319  func (f *Func) funcInfo() funcInfo {
   320  	return f.raw().funcInfo()
   321  }
   322  
   323  func (f *_func) funcInfo() funcInfo {
   324  	// Find the module containing fn. fn is located in the pclntable.
   325  	// The unsafe.Pointer to uintptr conversions and arithmetic
   326  	// are safe because we are working with module addresses.
   327  	ptr := uintptr(unsafe.Pointer(f))
   328  	var mod *moduledata
   329  	for datap := &firstmoduledata; datap != nil; datap = datap.next {
   330  		if len(datap.pclntable) == 0 {
   331  			continue
   332  		}
   333  		base := uintptr(unsafe.Pointer(&datap.pclntable[0]))
   334  		if base <= ptr && ptr < base+uintptr(len(datap.pclntable)) {
   335  			mod = datap
   336  			break
   337  		}
   338  	}
   339  	return funcInfo{f, mod}
   340  }
   341  
   342  // pcHeader holds data used by the pclntab lookups.
   343  type pcHeader struct {
   344  	magic          uint32  // 0xFFFFFFF1
   345  	pad1, pad2     uint8   // 0,0
   346  	minLC          uint8   // min instruction size
   347  	ptrSize        uint8   // size of a ptr in bytes
   348  	nfunc          int     // number of functions in the module
   349  	nfiles         uint    // number of entries in the file tab
   350  	textStart      uintptr // base for function entry PC offsets in this module, equal to moduledata.text
   351  	funcnameOffset uintptr // offset to the funcnametab variable from pcHeader
   352  	cuOffset       uintptr // offset to the cutab variable from pcHeader
   353  	filetabOffset  uintptr // offset to the filetab variable from pcHeader
   354  	pctabOffset    uintptr // offset to the pctab variable from pcHeader
   355  	pclnOffset     uintptr // offset to the pclntab variable from pcHeader
   356  }
   357  
   358  // moduledata records information about the layout of the executable
   359  // image. It is written by the linker. Any changes here must be
   360  // matched changes to the code in cmd/link/internal/ld/symtab.go:symtab.
   361  // moduledata is stored in statically allocated non-pointer memory;
   362  // none of the pointers here are visible to the garbage collector.
   363  type moduledata struct {
   364  	sys.NotInHeap // Only in static data
   365  
   366  	pcHeader     *pcHeader
   367  	funcnametab  []byte
   368  	cutab        []uint32
   369  	filetab      []byte
   370  	pctab        []byte
   371  	pclntable    []byte
   372  	ftab         []functab
   373  	findfunctab  uintptr
   374  	minpc, maxpc uintptr
   375  
   376  	text, etext           uintptr
   377  	noptrdata, enoptrdata uintptr
   378  	data, edata           uintptr
   379  	bss, ebss             uintptr
   380  	noptrbss, enoptrbss   uintptr
   381  	covctrs, ecovctrs     uintptr
   382  	end, gcdata, gcbss    uintptr
   383  	types, etypes         uintptr
   384  	rodata                uintptr
   385  	gofunc                uintptr // go.func.*
   386  
   387  	textsectmap []textsect
   388  	typelinks   []int32 // offsets from types
   389  	itablinks   []*itab
   390  
   391  	ptab []ptabEntry
   392  
   393  	pluginpath string
   394  	pkghashes  []modulehash
   395  
   396  	// This slice records the initializing tasks that need to be
   397  	// done to start up the program. It is built by the linker.
   398  	inittasks []*initTask
   399  
   400  	modulename   string
   401  	modulehashes []modulehash
   402  
   403  	hasmain uint8 // 1 if module contains the main function, 0 otherwise
   404  	bad     bool  // module failed to load and should be ignored
   405  
   406  	gcdatamask, gcbssmask bitvector
   407  
   408  	typemap map[typeOff]*_type // offset to *_rtype in previous module
   409  
   410  	next *moduledata
   411  }
   412  
   413  // A modulehash is used to compare the ABI of a new module or a
   414  // package in a new module with the loaded program.
   415  //
   416  // For each shared library a module links against, the linker creates an entry in the
   417  // moduledata.modulehashes slice containing the name of the module, the abi hash seen
   418  // at link time and a pointer to the runtime abi hash. These are checked in
   419  // moduledataverify1 below.
   420  //
   421  // For each loaded plugin, the pkghashes slice has a modulehash of the
   422  // newly loaded package that can be used to check the plugin's version of
   423  // a package against any previously loaded version of the package.
   424  // This is done in plugin.lastmoduleinit.
   425  type modulehash struct {
   426  	modulename   string
   427  	linktimehash string
   428  	runtimehash  *string
   429  }
   430  
   431  // pinnedTypemaps are the map[typeOff]*_type from the moduledata objects.
   432  //
   433  // These typemap objects are allocated at run time on the heap, but the
   434  // only direct reference to them is in the moduledata, created by the
   435  // linker and marked SNOPTRDATA so it is ignored by the GC.
   436  //
   437  // To make sure the map isn't collected, we keep a second reference here.
   438  var pinnedTypemaps []map[typeOff]*_type
   439  
   440  var firstmoduledata moduledata  // linker symbol
   441  var lastmoduledatap *moduledata // linker symbol
   442  var modulesSlice *[]*moduledata // see activeModules
   443  
   444  // activeModules returns a slice of active modules.
   445  //
   446  // A module is active once its gcdatamask and gcbssmask have been
   447  // assembled and it is usable by the GC.
   448  //
   449  // This is nosplit/nowritebarrier because it is called by the
   450  // cgo pointer checking code.
   451  //
   452  //go:nosplit
   453  //go:nowritebarrier
   454  func activeModules() []*moduledata {
   455  	p := (*[]*moduledata)(atomic.Loadp(unsafe.Pointer(&modulesSlice)))
   456  	if p == nil {
   457  		return nil
   458  	}
   459  	return *p
   460  }
   461  
   462  // modulesinit creates the active modules slice out of all loaded modules.
   463  //
   464  // When a module is first loaded by the dynamic linker, an .init_array
   465  // function (written by cmd/link) is invoked to call addmoduledata,
   466  // appending to the module to the linked list that starts with
   467  // firstmoduledata.
   468  //
   469  // There are two times this can happen in the lifecycle of a Go
   470  // program. First, if compiled with -linkshared, a number of modules
   471  // built with -buildmode=shared can be loaded at program initialization.
   472  // Second, a Go program can load a module while running that was built
   473  // with -buildmode=plugin.
   474  //
   475  // After loading, this function is called which initializes the
   476  // moduledata so it is usable by the GC and creates a new activeModules
   477  // list.
   478  //
   479  // Only one goroutine may call modulesinit at a time.
   480  func modulesinit() {
   481  	modules := new([]*moduledata)
   482  	for md := &firstmoduledata; md != nil; md = md.next {
   483  		if md.bad {
   484  			continue
   485  		}
   486  		*modules = append(*modules, md)
   487  		if md.gcdatamask == (bitvector{}) {
   488  			scanDataSize := md.edata - md.data
   489  			md.gcdatamask = progToPointerMask((*byte)(unsafe.Pointer(md.gcdata)), scanDataSize)
   490  			scanBSSSize := md.ebss - md.bss
   491  			md.gcbssmask = progToPointerMask((*byte)(unsafe.Pointer(md.gcbss)), scanBSSSize)
   492  			gcController.addGlobals(int64(scanDataSize + scanBSSSize))
   493  		}
   494  	}
   495  
   496  	// Modules appear in the moduledata linked list in the order they are
   497  	// loaded by the dynamic loader, with one exception: the
   498  	// firstmoduledata itself the module that contains the runtime. This
   499  	// is not always the first module (when using -buildmode=shared, it
   500  	// is typically libstd.so, the second module). The order matters for
   501  	// typelinksinit, so we swap the first module with whatever module
   502  	// contains the main function.
   503  	//
   504  	// See Issue #18729.
   505  	for i, md := range *modules {
   506  		if md.hasmain != 0 {
   507  			(*modules)[0] = md
   508  			(*modules)[i] = &firstmoduledata
   509  			break
   510  		}
   511  	}
   512  
   513  	atomicstorep(unsafe.Pointer(&modulesSlice), unsafe.Pointer(modules))
   514  }
   515  
   516  type functab struct {
   517  	entryoff uint32 // relative to runtime.text
   518  	funcoff  uint32
   519  }
   520  
   521  // Mapping information for secondary text sections
   522  
   523  type textsect struct {
   524  	vaddr    uintptr // prelinked section vaddr
   525  	end      uintptr // vaddr + section length
   526  	baseaddr uintptr // relocated section address
   527  }
   528  
   529  // findfuncbucket is an array of these structures.
   530  // Each bucket represents 4096 bytes of the text segment.
   531  // Each subbucket represents 256 bytes of the text segment.
   532  // To find a function given a pc, locate the bucket and subbucket for
   533  // that pc. Add together the idx and subbucket value to obtain a
   534  // function index. Then scan the functab array starting at that
   535  // index to find the target function.
   536  // This table uses 20 bytes for every 4096 bytes of code, or ~0.5% overhead.
   537  type findfuncbucket struct {
   538  	idx        uint32
   539  	subbuckets [16]byte
   540  }
   541  
   542  func moduledataverify() {
   543  	for datap := &firstmoduledata; datap != nil; datap = datap.next {
   544  		moduledataverify1(datap)
   545  	}
   546  }
   547  
   548  const debugPcln = false
   549  
   550  func moduledataverify1(datap *moduledata) {
   551  	// Check that the pclntab's format is valid.
   552  	hdr := datap.pcHeader
   553  	if hdr.magic != 0xfffffff1 || hdr.pad1 != 0 || hdr.pad2 != 0 ||
   554  		hdr.minLC != sys.PCQuantum || hdr.ptrSize != goarch.PtrSize || hdr.textStart != datap.text {
   555  		println("runtime: pcHeader: magic=", hex(hdr.magic), "pad1=", hdr.pad1, "pad2=", hdr.pad2,
   556  			"minLC=", hdr.minLC, "ptrSize=", hdr.ptrSize, "pcHeader.textStart=", hex(hdr.textStart),
   557  			"text=", hex(datap.text), "pluginpath=", datap.pluginpath)
   558  		throw("invalid function symbol table")
   559  	}
   560  
   561  	// ftab is lookup table for function by program counter.
   562  	nftab := len(datap.ftab) - 1
   563  	for i := 0; i < nftab; i++ {
   564  		// NOTE: ftab[nftab].entry is legal; it is the address beyond the final function.
   565  		if datap.ftab[i].entryoff > datap.ftab[i+1].entryoff {
   566  			f1 := funcInfo{(*_func)(unsafe.Pointer(&datap.pclntable[datap.ftab[i].funcoff])), datap}
   567  			f2 := funcInfo{(*_func)(unsafe.Pointer(&datap.pclntable[datap.ftab[i+1].funcoff])), datap}
   568  			f2name := "end"
   569  			if i+1 < nftab {
   570  				f2name = funcname(f2)
   571  			}
   572  			println("function symbol table not sorted by PC offset:", hex(datap.ftab[i].entryoff), funcname(f1), ">", hex(datap.ftab[i+1].entryoff), f2name, ", plugin:", datap.pluginpath)
   573  			for j := 0; j <= i; j++ {
   574  				println("\t", hex(datap.ftab[j].entryoff), funcname(funcInfo{(*_func)(unsafe.Pointer(&datap.pclntable[datap.ftab[j].funcoff])), datap}))
   575  			}
   576  			if GOOS == "aix" && isarchive {
   577  				println("-Wl,-bnoobjreorder is mandatory on aix/ppc64 with c-archive")
   578  			}
   579  			throw("invalid runtime symbol table")
   580  		}
   581  	}
   582  
   583  	min := datap.textAddr(datap.ftab[0].entryoff)
   584  	max := datap.textAddr(datap.ftab[nftab].entryoff)
   585  	if datap.minpc != min || datap.maxpc != max {
   586  		println("minpc=", hex(datap.minpc), "min=", hex(min), "maxpc=", hex(datap.maxpc), "max=", hex(max))
   587  		throw("minpc or maxpc invalid")
   588  	}
   589  
   590  	for _, modulehash := range datap.modulehashes {
   591  		if modulehash.linktimehash != *modulehash.runtimehash {
   592  			println("abi mismatch detected between", datap.modulename, "and", modulehash.modulename)
   593  			throw("abi mismatch")
   594  		}
   595  	}
   596  }
   597  
   598  // textAddr returns md.text + off, with special handling for multiple text sections.
   599  // off is a (virtual) offset computed at internal linking time,
   600  // before the external linker adjusts the sections' base addresses.
   601  //
   602  // The text, or instruction stream is generated as one large buffer.
   603  // The off (offset) for a function is its offset within this buffer.
   604  // If the total text size gets too large, there can be issues on platforms like ppc64
   605  // if the target of calls are too far for the call instruction.
   606  // To resolve the large text issue, the text is split into multiple text sections
   607  // to allow the linker to generate long calls when necessary.
   608  // When this happens, the vaddr for each text section is set to its offset within the text.
   609  // Each function's offset is compared against the section vaddrs and ends to determine the containing section.
   610  // Then the section relative offset is added to the section's
   611  // relocated baseaddr to compute the function address.
   612  //
   613  // It is nosplit because it is part of the findfunc implementation.
   614  //
   615  //go:nosplit
   616  func (md *moduledata) textAddr(off32 uint32) uintptr {
   617  	off := uintptr(off32)
   618  	res := md.text + off
   619  	if len(md.textsectmap) > 1 {
   620  		for i, sect := range md.textsectmap {
   621  			// For the last section, include the end address (etext), as it is included in the functab.
   622  			if off >= sect.vaddr && off < sect.end || (i == len(md.textsectmap)-1 && off == sect.end) {
   623  				res = sect.baseaddr + off - sect.vaddr
   624  				break
   625  			}
   626  		}
   627  		if res > md.etext && GOARCH != "wasm" { // on wasm, functions do not live in the same address space as the linear memory
   628  			println("runtime: textAddr", hex(res), "out of range", hex(md.text), "-", hex(md.etext))
   629  			throw("runtime: text offset out of range")
   630  		}
   631  	}
   632  	return res
   633  }
   634  
   635  // textOff is the opposite of textAddr. It converts a PC to a (virtual) offset
   636  // to md.text, and returns if the PC is in any Go text section.
   637  //
   638  // It is nosplit because it is part of the findfunc implementation.
   639  //
   640  //go:nosplit
   641  func (md *moduledata) textOff(pc uintptr) (uint32, bool) {
   642  	res := uint32(pc - md.text)
   643  	if len(md.textsectmap) > 1 {
   644  		for i, sect := range md.textsectmap {
   645  			if sect.baseaddr > pc {
   646  				// pc is not in any section.
   647  				return 0, false
   648  			}
   649  			end := sect.baseaddr + (sect.end - sect.vaddr)
   650  			// For the last section, include the end address (etext), as it is included in the functab.
   651  			if i == len(md.textsectmap)-1 {
   652  				end++
   653  			}
   654  			if pc < end {
   655  				res = uint32(pc - sect.baseaddr + sect.vaddr)
   656  				break
   657  			}
   658  		}
   659  	}
   660  	return res, true
   661  }
   662  
   663  // funcName returns the string at nameOff in the function name table.
   664  func (md *moduledata) funcName(nameOff int32) string {
   665  	if nameOff == 0 {
   666  		return ""
   667  	}
   668  	return gostringnocopy(&md.funcnametab[nameOff])
   669  }
   670  
   671  // FuncForPC returns a *[Func] describing the function that contains the
   672  // given program counter address, or else nil.
   673  //
   674  // If pc represents multiple functions because of inlining, it returns
   675  // the *Func describing the innermost function, but with an entry of
   676  // the outermost function.
   677  func FuncForPC(pc uintptr) *Func {
   678  	f := findfunc(pc)
   679  	if !f.valid() {
   680  		return nil
   681  	}
   682  	// This must interpret PC non-strictly so bad PCs (those between functions) don't crash the runtime.
   683  	// We just report the preceding function in that situation. See issue 29735.
   684  	// TODO: Perhaps we should report no function at all in that case.
   685  	// The runtime currently doesn't have function end info, alas.
   686  	u, uf := newInlineUnwinder(f, pc)
   687  	if !u.isInlined(uf) {
   688  		return f._Func()
   689  	}
   690  	sf := u.srcFunc(uf)
   691  	file, line := u.fileLine(uf)
   692  	fi := &funcinl{
   693  		ones:      ^uint32(0),
   694  		entry:     f.entry(), // entry of the real (the outermost) function.
   695  		name:      sf.name(),
   696  		file:      file,
   697  		line:      int32(line),
   698  		startLine: sf.startLine,
   699  	}
   700  	return (*Func)(unsafe.Pointer(fi))
   701  }
   702  
   703  // Name returns the name of the function.
   704  func (f *Func) Name() string {
   705  	if f == nil {
   706  		return ""
   707  	}
   708  	fn := f.raw()
   709  	if fn.isInlined() { // inlined version
   710  		fi := (*funcinl)(unsafe.Pointer(fn))
   711  		return funcNameForPrint(fi.name)
   712  	}
   713  	return funcNameForPrint(funcname(f.funcInfo()))
   714  }
   715  
   716  // Entry returns the entry address of the function.
   717  func (f *Func) Entry() uintptr {
   718  	fn := f.raw()
   719  	if fn.isInlined() { // inlined version
   720  		fi := (*funcinl)(unsafe.Pointer(fn))
   721  		return fi.entry
   722  	}
   723  	return fn.funcInfo().entry()
   724  }
   725  
   726  // FileLine returns the file name and line number of the
   727  // source code corresponding to the program counter pc.
   728  // The result will not be accurate if pc is not a program
   729  // counter within f.
   730  func (f *Func) FileLine(pc uintptr) (file string, line int) {
   731  	fn := f.raw()
   732  	if fn.isInlined() { // inlined version
   733  		fi := (*funcinl)(unsafe.Pointer(fn))
   734  		return fi.file, int(fi.line)
   735  	}
   736  	// Pass strict=false here, because anyone can call this function,
   737  	// and they might just be wrong about targetpc belonging to f.
   738  	file, line32 := funcline1(f.funcInfo(), pc, false)
   739  	return file, int(line32)
   740  }
   741  
   742  // startLine returns the starting line number of the function. i.e., the line
   743  // number of the func keyword.
   744  func (f *Func) startLine() int32 {
   745  	fn := f.raw()
   746  	if fn.isInlined() { // inlined version
   747  		fi := (*funcinl)(unsafe.Pointer(fn))
   748  		return fi.startLine
   749  	}
   750  	return fn.funcInfo().startLine
   751  }
   752  
   753  // findmoduledatap looks up the moduledata for a PC.
   754  //
   755  // It is nosplit because it's part of the isgoexception
   756  // implementation.
   757  //
   758  //go:nosplit
   759  func findmoduledatap(pc uintptr) *moduledata {
   760  	for datap := &firstmoduledata; datap != nil; datap = datap.next {
   761  		if datap.minpc <= pc && pc < datap.maxpc {
   762  			return datap
   763  		}
   764  	}
   765  	return nil
   766  }
   767  
   768  type funcInfo struct {
   769  	*_func
   770  	datap *moduledata
   771  }
   772  
   773  func (f funcInfo) valid() bool {
   774  	return f._func != nil
   775  }
   776  
   777  func (f funcInfo) _Func() *Func {
   778  	return (*Func)(unsafe.Pointer(f._func))
   779  }
   780  
   781  // isInlined reports whether f should be re-interpreted as a *funcinl.
   782  func (f *_func) isInlined() bool {
   783  	return f.entryOff == ^uint32(0) // see comment for funcinl.ones
   784  }
   785  
   786  // entry returns the entry PC for f.
   787  func (f funcInfo) entry() uintptr {
   788  	return f.datap.textAddr(f.entryOff)
   789  }
   790  
   791  // findfunc looks up function metadata for a PC.
   792  //
   793  // It is nosplit because it's part of the isgoexception
   794  // implementation.
   795  //
   796  //go:nosplit
   797  func findfunc(pc uintptr) funcInfo {
   798  	datap := findmoduledatap(pc)
   799  	if datap == nil {
   800  		return funcInfo{}
   801  	}
   802  	const nsub = uintptr(len(findfuncbucket{}.subbuckets))
   803  
   804  	pcOff, ok := datap.textOff(pc)
   805  	if !ok {
   806  		return funcInfo{}
   807  	}
   808  
   809  	x := uintptr(pcOff) + datap.text - datap.minpc // TODO: are datap.text and datap.minpc always equal?
   810  	b := x / abi.FuncTabBucketSize
   811  	i := x % abi.FuncTabBucketSize / (abi.FuncTabBucketSize / nsub)
   812  
   813  	ffb := (*findfuncbucket)(add(unsafe.Pointer(datap.findfunctab), b*unsafe.Sizeof(findfuncbucket{})))
   814  	idx := ffb.idx + uint32(ffb.subbuckets[i])
   815  
   816  	// Find the ftab entry.
   817  	for datap.ftab[idx+1].entryoff <= pcOff {
   818  		idx++
   819  	}
   820  
   821  	funcoff := datap.ftab[idx].funcoff
   822  	return funcInfo{(*_func)(unsafe.Pointer(&datap.pclntable[funcoff])), datap}
   823  }
   824  
   825  // A srcFunc represents a logical function in the source code. This may
   826  // correspond to an actual symbol in the binary text, or it may correspond to a
   827  // source function that has been inlined.
   828  type srcFunc struct {
   829  	datap     *moduledata
   830  	nameOff   int32
   831  	startLine int32
   832  	funcID    abi.FuncID
   833  }
   834  
   835  func (f funcInfo) srcFunc() srcFunc {
   836  	if !f.valid() {
   837  		return srcFunc{}
   838  	}
   839  	return srcFunc{f.datap, f.nameOff, f.startLine, f.funcID}
   840  }
   841  
   842  func (s srcFunc) name() string {
   843  	if s.datap == nil {
   844  		return ""
   845  	}
   846  	return s.datap.funcName(s.nameOff)
   847  }
   848  
   849  type pcvalueCache struct {
   850  	entries [2][8]pcvalueCacheEnt
   851  	inUse   int
   852  }
   853  
   854  type pcvalueCacheEnt struct {
   855  	// targetpc and off together are the key of this cache entry.
   856  	targetpc uintptr
   857  	off      uint32
   858  
   859  	val   int32   // The value of this entry.
   860  	valPC uintptr // The PC at which val starts
   861  }
   862  
   863  // pcvalueCacheKey returns the outermost index in a pcvalueCache to use for targetpc.
   864  // It must be very cheap to calculate.
   865  // For now, align to goarch.PtrSize and reduce mod the number of entries.
   866  // In practice, this appears to be fairly randomly and evenly distributed.
   867  func pcvalueCacheKey(targetpc uintptr) uintptr {
   868  	return (targetpc / goarch.PtrSize) % uintptr(len(pcvalueCache{}.entries))
   869  }
   870  
   871  // Returns the PCData value, and the PC where this value starts.
   872  func pcvalue(f funcInfo, off uint32, targetpc uintptr, strict bool) (int32, uintptr) {
   873  	// If true, when we get a cache hit, still look up the data and make sure it
   874  	// matches the cached contents.
   875  	const debugCheckCache = false
   876  
   877  	if off == 0 {
   878  		return -1, 0
   879  	}
   880  
   881  	// Check the cache. This speeds up walks of deep stacks, which
   882  	// tend to have the same recursive functions over and over,
   883  	// or repetitive stacks between goroutines.
   884  	var checkVal int32
   885  	var checkPC uintptr
   886  	ck := pcvalueCacheKey(targetpc)
   887  	{
   888  		mp := acquirem()
   889  		cache := &mp.pcvalueCache
   890  		// The cache can be used by the signal handler on this M. Avoid
   891  		// re-entrant use of the cache. The signal handler can also write inUse,
   892  		// but will always restore its value, so we can use a regular increment
   893  		// even if we get signaled in the middle of it.
   894  		cache.inUse++
   895  		if cache.inUse == 1 {
   896  			for i := range cache.entries[ck] {
   897  				// We check off first because we're more
   898  				// likely to have multiple entries with
   899  				// different offsets for the same targetpc
   900  				// than the other way around, so we'll usually
   901  				// fail in the first clause.
   902  				ent := &cache.entries[ck][i]
   903  				if ent.off == off && ent.targetpc == targetpc {
   904  					val, pc := ent.val, ent.valPC
   905  					if debugCheckCache {
   906  						checkVal, checkPC = ent.val, ent.valPC
   907  						break
   908  					} else {
   909  						cache.inUse--
   910  						releasem(mp)
   911  						return val, pc
   912  					}
   913  				}
   914  			}
   915  		} else if debugCheckCache && (cache.inUse < 1 || cache.inUse > 2) {
   916  			// Catch accounting errors or deeply reentrant use. In principle
   917  			// "inUse" should never exceed 2.
   918  			throw("cache.inUse out of range")
   919  		}
   920  		cache.inUse--
   921  		releasem(mp)
   922  	}
   923  
   924  	if !f.valid() {
   925  		if strict && panicking.Load() == 0 {
   926  			println("runtime: no module data for", hex(f.entry()))
   927  			throw("no module data")
   928  		}
   929  		return -1, 0
   930  	}
   931  	datap := f.datap
   932  	p := datap.pctab[off:]
   933  	pc := f.entry()
   934  	prevpc := pc
   935  	val := int32(-1)
   936  	for {
   937  		var ok bool
   938  		p, ok = step(p, &pc, &val, pc == f.entry())
   939  		if !ok {
   940  			break
   941  		}
   942  		if targetpc < pc {
   943  			// Replace a random entry in the cache. Random
   944  			// replacement prevents a performance cliff if
   945  			// a recursive stack's cycle is slightly
   946  			// larger than the cache.
   947  			// Put the new element at the beginning,
   948  			// since it is the most likely to be newly used.
   949  			if debugCheckCache && checkPC != 0 {
   950  				if checkVal != val || checkPC != prevpc {
   951  					print("runtime: table value ", val, "@", prevpc, " != cache value ", checkVal, "@", checkPC, " at PC ", targetpc, " off ", off, "\n")
   952  					throw("bad pcvalue cache")
   953  				}
   954  			} else {
   955  				mp := acquirem()
   956  				cache := &mp.pcvalueCache
   957  				cache.inUse++
   958  				if cache.inUse == 1 {
   959  					e := &cache.entries[ck]
   960  					ci := cheaprandn(uint32(len(cache.entries[ck])))
   961  					e[ci] = e[0]
   962  					e[0] = pcvalueCacheEnt{
   963  						targetpc: targetpc,
   964  						off:      off,
   965  						val:      val,
   966  						valPC:    prevpc,
   967  					}
   968  				}
   969  				cache.inUse--
   970  				releasem(mp)
   971  			}
   972  
   973  			return val, prevpc
   974  		}
   975  		prevpc = pc
   976  	}
   977  
   978  	// If there was a table, it should have covered all program counters.
   979  	// If not, something is wrong.
   980  	if panicking.Load() != 0 || !strict {
   981  		return -1, 0
   982  	}
   983  
   984  	print("runtime: invalid pc-encoded table f=", funcname(f), " pc=", hex(pc), " targetpc=", hex(targetpc), " tab=", p, "\n")
   985  
   986  	p = datap.pctab[off:]
   987  	pc = f.entry()
   988  	val = -1
   989  	for {
   990  		var ok bool
   991  		p, ok = step(p, &pc, &val, pc == f.entry())
   992  		if !ok {
   993  			break
   994  		}
   995  		print("\tvalue=", val, " until pc=", hex(pc), "\n")
   996  	}
   997  
   998  	throw("invalid runtime symbol table")
   999  	return -1, 0
  1000  }
  1001  
  1002  func funcname(f funcInfo) string {
  1003  	if !f.valid() {
  1004  		return ""
  1005  	}
  1006  	return f.datap.funcName(f.nameOff)
  1007  }
  1008  
  1009  func funcpkgpath(f funcInfo) string {
  1010  	name := funcNameForPrint(funcname(f))
  1011  	i := len(name) - 1
  1012  	for ; i > 0; i-- {
  1013  		if name[i] == '/' {
  1014  			break
  1015  		}
  1016  	}
  1017  	for ; i < len(name); i++ {
  1018  		if name[i] == '.' {
  1019  			break
  1020  		}
  1021  	}
  1022  	return name[:i]
  1023  }
  1024  
  1025  func funcfile(f funcInfo, fileno int32) string {
  1026  	datap := f.datap
  1027  	if !f.valid() {
  1028  		return "?"
  1029  	}
  1030  	// Make sure the cu index and file offset are valid
  1031  	if fileoff := datap.cutab[f.cuOffset+uint32(fileno)]; fileoff != ^uint32(0) {
  1032  		return gostringnocopy(&datap.filetab[fileoff])
  1033  	}
  1034  	// pcln section is corrupt.
  1035  	return "?"
  1036  }
  1037  
  1038  func funcline1(f funcInfo, targetpc uintptr, strict bool) (file string, line int32) {
  1039  	datap := f.datap
  1040  	if !f.valid() {
  1041  		return "?", 0
  1042  	}
  1043  	fileno, _ := pcvalue(f, f.pcfile, targetpc, strict)
  1044  	line, _ = pcvalue(f, f.pcln, targetpc, strict)
  1045  	if fileno == -1 || line == -1 || int(fileno) >= len(datap.filetab) {
  1046  		// print("looking for ", hex(targetpc), " in ", funcname(f), " got file=", fileno, " line=", lineno, "\n")
  1047  		return "?", 0
  1048  	}
  1049  	file = funcfile(f, fileno)
  1050  	return
  1051  }
  1052  
  1053  func funcline(f funcInfo, targetpc uintptr) (file string, line int32) {
  1054  	return funcline1(f, targetpc, true)
  1055  }
  1056  
  1057  func funcspdelta(f funcInfo, targetpc uintptr) int32 {
  1058  	x, _ := pcvalue(f, f.pcsp, targetpc, true)
  1059  	if debugPcln && x&(goarch.PtrSize-1) != 0 {
  1060  		print("invalid spdelta ", funcname(f), " ", hex(f.entry()), " ", hex(targetpc), " ", hex(f.pcsp), " ", x, "\n")
  1061  		throw("bad spdelta")
  1062  	}
  1063  	return x
  1064  }
  1065  
  1066  // funcMaxSPDelta returns the maximum spdelta at any point in f.
  1067  func funcMaxSPDelta(f funcInfo) int32 {
  1068  	datap := f.datap
  1069  	p := datap.pctab[f.pcsp:]
  1070  	pc := f.entry()
  1071  	val := int32(-1)
  1072  	most := int32(0)
  1073  	for {
  1074  		var ok bool
  1075  		p, ok = step(p, &pc, &val, pc == f.entry())
  1076  		if !ok {
  1077  			return most
  1078  		}
  1079  		most = max(most, val)
  1080  	}
  1081  }
  1082  
  1083  func pcdatastart(f funcInfo, table uint32) uint32 {
  1084  	return *(*uint32)(add(unsafe.Pointer(&f.nfuncdata), unsafe.Sizeof(f.nfuncdata)+uintptr(table)*4))
  1085  }
  1086  
  1087  func pcdatavalue(f funcInfo, table uint32, targetpc uintptr) int32 {
  1088  	if table >= f.npcdata {
  1089  		return -1
  1090  	}
  1091  	r, _ := pcvalue(f, pcdatastart(f, table), targetpc, true)
  1092  	return r
  1093  }
  1094  
  1095  func pcdatavalue1(f funcInfo, table uint32, targetpc uintptr, strict bool) int32 {
  1096  	if table >= f.npcdata {
  1097  		return -1
  1098  	}
  1099  	r, _ := pcvalue(f, pcdatastart(f, table), targetpc, strict)
  1100  	return r
  1101  }
  1102  
  1103  // Like pcdatavalue, but also return the start PC of this PCData value.
  1104  func pcdatavalue2(f funcInfo, table uint32, targetpc uintptr) (int32, uintptr) {
  1105  	if table >= f.npcdata {
  1106  		return -1, 0
  1107  	}
  1108  	return pcvalue(f, pcdatastart(f, table), targetpc, true)
  1109  }
  1110  
  1111  // funcdata returns a pointer to the ith funcdata for f.
  1112  // funcdata should be kept in sync with cmd/link:writeFuncs.
  1113  func funcdata(f funcInfo, i uint8) unsafe.Pointer {
  1114  	if i < 0 || i >= f.nfuncdata {
  1115  		return nil
  1116  	}
  1117  	base := f.datap.gofunc // load gofunc address early so that we calculate during cache misses
  1118  	p := uintptr(unsafe.Pointer(&f.nfuncdata)) + unsafe.Sizeof(f.nfuncdata) + uintptr(f.npcdata)*4 + uintptr(i)*4
  1119  	off := *(*uint32)(unsafe.Pointer(p))
  1120  	// Return off == ^uint32(0) ? 0 : f.datap.gofunc + uintptr(off), but without branches.
  1121  	// The compiler calculates mask on most architectures using conditional assignment.
  1122  	var mask uintptr
  1123  	if off == ^uint32(0) {
  1124  		mask = 1
  1125  	}
  1126  	mask--
  1127  	raw := base + uintptr(off)
  1128  	return unsafe.Pointer(raw & mask)
  1129  }
  1130  
  1131  // step advances to the next pc, value pair in the encoded table.
  1132  func step(p []byte, pc *uintptr, val *int32, first bool) (newp []byte, ok bool) {
  1133  	// For both uvdelta and pcdelta, the common case (~70%)
  1134  	// is that they are a single byte. If so, avoid calling readvarint.
  1135  	uvdelta := uint32(p[0])
  1136  	if uvdelta == 0 && !first {
  1137  		return nil, false
  1138  	}
  1139  	n := uint32(1)
  1140  	if uvdelta&0x80 != 0 {
  1141  		n, uvdelta = readvarint(p)
  1142  	}
  1143  	*val += int32(-(uvdelta & 1) ^ (uvdelta >> 1))
  1144  	p = p[n:]
  1145  
  1146  	pcdelta := uint32(p[0])
  1147  	n = 1
  1148  	if pcdelta&0x80 != 0 {
  1149  		n, pcdelta = readvarint(p)
  1150  	}
  1151  	p = p[n:]
  1152  	*pc += uintptr(pcdelta * sys.PCQuantum)
  1153  	return p, true
  1154  }
  1155  
  1156  // readvarint reads a varint from p.
  1157  func readvarint(p []byte) (read uint32, val uint32) {
  1158  	var v, shift, n uint32
  1159  	for {
  1160  		b := p[n]
  1161  		n++
  1162  		v |= uint32(b&0x7F) << (shift & 31)
  1163  		if b&0x80 == 0 {
  1164  			break
  1165  		}
  1166  		shift += 7
  1167  	}
  1168  	return n, v
  1169  }
  1170  
  1171  type stackmap struct {
  1172  	n        int32   // number of bitmaps
  1173  	nbit     int32   // number of bits in each bitmap
  1174  	bytedata [1]byte // bitmaps, each starting on a byte boundary
  1175  }
  1176  
  1177  //go:nowritebarrier
  1178  func stackmapdata(stkmap *stackmap, n int32) bitvector {
  1179  	// Check this invariant only when stackDebug is on at all.
  1180  	// The invariant is already checked by many of stackmapdata's callers,
  1181  	// and disabling it by default allows stackmapdata to be inlined.
  1182  	if stackDebug > 0 && (n < 0 || n >= stkmap.n) {
  1183  		throw("stackmapdata: index out of range")
  1184  	}
  1185  	return bitvector{stkmap.nbit, addb(&stkmap.bytedata[0], uintptr(n*((stkmap.nbit+7)>>3)))}
  1186  }
  1187  

View as plain text