Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/link/internal/ld/pcln.go

Documentation: cmd/link/internal/ld

     1  // Copyright 2013 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 ld
     6  
     7  import (
     8  	"cmd/internal/goobj"
     9  	"cmd/internal/objabi"
    10  	"cmd/internal/sys"
    11  	"cmd/link/internal/loader"
    12  	"cmd/link/internal/sym"
    13  	"fmt"
    14  	"os"
    15  	"path/filepath"
    16  )
    17  
    18  // pclntab holds the state needed for pclntab generation.
    19  type pclntab struct {
    20  	// The size of the func object in the runtime.
    21  	funcSize uint32
    22  
    23  	// The first and last functions found.
    24  	firstFunc, lastFunc loader.Sym
    25  
    26  	// Running total size of pclntab.
    27  	size int64
    28  
    29  	// runtime.pclntab's symbols
    30  	carrier     loader.Sym
    31  	pclntab     loader.Sym
    32  	pcheader    loader.Sym
    33  	funcnametab loader.Sym
    34  	findfunctab loader.Sym
    35  	cutab       loader.Sym
    36  	filetab     loader.Sym
    37  	pctab       loader.Sym
    38  
    39  	// The number of functions + number of TEXT sections - 1. This is such an
    40  	// unexpected value because platforms that have more than one TEXT section
    41  	// get a dummy function inserted between because the external linker can place
    42  	// functions in those areas. We mark those areas as not covered by the Go
    43  	// runtime.
    44  	//
    45  	// On most platforms this is the number of reachable functions.
    46  	nfunc int32
    47  
    48  	// The number of filenames in runtime.filetab.
    49  	nfiles uint32
    50  }
    51  
    52  // addGeneratedSym adds a generator symbol to pclntab, returning the new Sym.
    53  // It is the caller's responsibilty to save they symbol in state.
    54  func (state *pclntab) addGeneratedSym(ctxt *Link, name string, size int64, f generatorFunc) loader.Sym {
    55  	size = Rnd(size, int64(ctxt.Arch.PtrSize))
    56  	state.size += size
    57  	s := ctxt.createGeneratorSymbol(name, 0, sym.SPCLNTAB, size, f)
    58  	ctxt.loader.SetAttrReachable(s, true)
    59  	ctxt.loader.SetCarrierSym(s, state.carrier)
    60  	ctxt.loader.SetAttrNotInSymbolTable(s, true)
    61  	return s
    62  }
    63  
    64  // makePclntab makes a pclntab object, and assembles all the compilation units
    65  // we'll need to write pclntab. Returns the pclntab structure, a slice of the
    66  // CompilationUnits we need, and a slice of the function symbols we need to
    67  // generate pclntab.
    68  func makePclntab(ctxt *Link, container loader.Bitmap) (*pclntab, []*sym.CompilationUnit, []loader.Sym) {
    69  	ldr := ctxt.loader
    70  
    71  	state := &pclntab{
    72  		// This is the size of the _func object in runtime/runtime2.go.
    73  		funcSize: uint32(ctxt.Arch.PtrSize + 9*4),
    74  	}
    75  
    76  	// Gather some basic stats and info.
    77  	seenCUs := make(map[*sym.CompilationUnit]struct{})
    78  	prevSect := ldr.SymSect(ctxt.Textp[0])
    79  	compUnits := []*sym.CompilationUnit{}
    80  	funcs := []loader.Sym{}
    81  
    82  	for _, s := range ctxt.Textp {
    83  		if !emitPcln(ctxt, s, container) {
    84  			continue
    85  		}
    86  		funcs = append(funcs, s)
    87  		state.nfunc++
    88  		if state.firstFunc == 0 {
    89  			state.firstFunc = s
    90  		}
    91  		state.lastFunc = s
    92  		ss := ldr.SymSect(s)
    93  		if ss != prevSect {
    94  			// With multiple text sections, the external linker may
    95  			// insert functions between the sections, which are not
    96  			// known by Go. This leaves holes in the PC range covered
    97  			// by the func table. We need to generate an entry to mark
    98  			// the hole.
    99  			state.nfunc++
   100  			prevSect = ss
   101  		}
   102  
   103  		// We need to keep track of all compilation units we see. Some symbols
   104  		// (eg, go.buildid, _cgoexp_, etc) won't have a compilation unit.
   105  		cu := ldr.SymUnit(s)
   106  		if _, ok := seenCUs[cu]; cu != nil && !ok {
   107  			seenCUs[cu] = struct{}{}
   108  			cu.PclnIndex = len(compUnits)
   109  			compUnits = append(compUnits, cu)
   110  		}
   111  	}
   112  	return state, compUnits, funcs
   113  }
   114  
   115  func emitPcln(ctxt *Link, s loader.Sym, container loader.Bitmap) bool {
   116  	// We want to generate func table entries only for the "lowest
   117  	// level" symbols, not containers of subsymbols.
   118  	return !container.Has(s)
   119  }
   120  
   121  func computeDeferReturn(ctxt *Link, deferReturnSym, s loader.Sym) uint32 {
   122  	ldr := ctxt.loader
   123  	target := ctxt.Target
   124  	deferreturn := uint32(0)
   125  	lastWasmAddr := uint32(0)
   126  
   127  	relocs := ldr.Relocs(s)
   128  	for ri := 0; ri < relocs.Count(); ri++ {
   129  		r := relocs.At(ri)
   130  		if target.IsWasm() && r.Type() == objabi.R_ADDR {
   131  			// Wasm does not have a live variable set at the deferreturn
   132  			// call itself. Instead it has one identified by the
   133  			// resumption point immediately preceding the deferreturn.
   134  			// The wasm code has a R_ADDR relocation which is used to
   135  			// set the resumption point to PC_B.
   136  			lastWasmAddr = uint32(r.Add())
   137  		}
   138  		if r.Type().IsDirectCall() && (r.Sym() == deferReturnSym || ldr.IsDeferReturnTramp(r.Sym())) {
   139  			if target.IsWasm() {
   140  				deferreturn = lastWasmAddr - 1
   141  			} else {
   142  				// Note: the relocation target is in the call instruction, but
   143  				// is not necessarily the whole instruction (for instance, on
   144  				// x86 the relocation applies to bytes [1:5] of the 5 byte call
   145  				// instruction).
   146  				deferreturn = uint32(r.Off())
   147  				switch target.Arch.Family {
   148  				case sys.AMD64, sys.I386:
   149  					deferreturn--
   150  				case sys.PPC64, sys.ARM, sys.ARM64, sys.MIPS, sys.MIPS64:
   151  					// no change
   152  				case sys.RISCV64:
   153  					// TODO(jsing): The JALR instruction is marked with
   154  					// R_CALLRISCV, whereas the actual reloc is currently
   155  					// one instruction earlier starting with the AUIPC.
   156  					deferreturn -= 4
   157  				case sys.S390X:
   158  					deferreturn -= 2
   159  				default:
   160  					panic(fmt.Sprint("Unhandled architecture:", target.Arch.Family))
   161  				}
   162  			}
   163  			break // only need one
   164  		}
   165  	}
   166  	return deferreturn
   167  }
   168  
   169  // genInlTreeSym generates the InlTree sym for a function with the
   170  // specified FuncInfo.
   171  func genInlTreeSym(ctxt *Link, cu *sym.CompilationUnit, fi loader.FuncInfo, arch *sys.Arch, nameOffsets map[loader.Sym]uint32) loader.Sym {
   172  	ldr := ctxt.loader
   173  	its := ldr.CreateExtSym("", 0)
   174  	inlTreeSym := ldr.MakeSymbolUpdater(its)
   175  	// Note: the generated symbol is given a type of sym.SGOFUNC, as a
   176  	// signal to the symtab() phase that it needs to be grouped in with
   177  	// other similar symbols (gcdata, etc); the dodata() phase will
   178  	// eventually switch the type back to SRODATA.
   179  	inlTreeSym.SetType(sym.SGOFUNC)
   180  	ldr.SetAttrReachable(its, true)
   181  	ninl := fi.NumInlTree()
   182  	for i := 0; i < int(ninl); i++ {
   183  		call := fi.InlTree(i)
   184  		val := call.File
   185  		nameoff, ok := nameOffsets[call.Func]
   186  		if !ok {
   187  			panic("couldn't find function name offset")
   188  		}
   189  
   190  		inlTreeSym.SetUint16(arch, int64(i*20+0), uint16(call.Parent))
   191  		inlFunc := ldr.FuncInfo(call.Func)
   192  
   193  		var funcID objabi.FuncID
   194  		if inlFunc.Valid() {
   195  			funcID = inlFunc.FuncID()
   196  		}
   197  		inlTreeSym.SetUint8(arch, int64(i*20+2), uint8(funcID))
   198  
   199  		// byte 3 is unused
   200  		inlTreeSym.SetUint32(arch, int64(i*20+4), uint32(val))
   201  		inlTreeSym.SetUint32(arch, int64(i*20+8), uint32(call.Line))
   202  		inlTreeSym.SetUint32(arch, int64(i*20+12), uint32(nameoff))
   203  		inlTreeSym.SetUint32(arch, int64(i*20+16), uint32(call.ParentPC))
   204  	}
   205  	return its
   206  }
   207  
   208  // makeInlSyms returns a map of loader.Sym that are created inlSyms.
   209  func makeInlSyms(ctxt *Link, funcs []loader.Sym, nameOffsets map[loader.Sym]uint32) map[loader.Sym]loader.Sym {
   210  	ldr := ctxt.loader
   211  	// Create the inline symbols we need.
   212  	inlSyms := make(map[loader.Sym]loader.Sym)
   213  	for _, s := range funcs {
   214  		if fi := ldr.FuncInfo(s); fi.Valid() {
   215  			fi.Preload()
   216  			if fi.NumInlTree() > 0 {
   217  				inlSyms[s] = genInlTreeSym(ctxt, ldr.SymUnit(s), fi, ctxt.Arch, nameOffsets)
   218  			}
   219  		}
   220  	}
   221  	return inlSyms
   222  }
   223  
   224  // generatePCHeader creates the runtime.pcheader symbol, setting it up as a
   225  // generator to fill in its data later.
   226  func (state *pclntab) generatePCHeader(ctxt *Link) {
   227  	writeHeader := func(ctxt *Link, s loader.Sym) {
   228  		ldr := ctxt.loader
   229  		header := ctxt.loader.MakeSymbolUpdater(s)
   230  
   231  		writeSymOffset := func(off int64, ws loader.Sym) int64 {
   232  			diff := ldr.SymValue(ws) - ldr.SymValue(s)
   233  			if diff <= 0 {
   234  				name := ldr.SymName(ws)
   235  				panic(fmt.Sprintf("expected runtime.pcheader(%x) to be placed before %s(%x)", ldr.SymValue(s), name, ldr.SymValue(ws)))
   236  			}
   237  			return header.SetUintptr(ctxt.Arch, off, uintptr(diff))
   238  		}
   239  
   240  		// Write header.
   241  		// Keep in sync with runtime/symtab.go:pcHeader.
   242  		header.SetUint32(ctxt.Arch, 0, 0xfffffffa)
   243  		header.SetUint8(ctxt.Arch, 6, uint8(ctxt.Arch.MinLC))
   244  		header.SetUint8(ctxt.Arch, 7, uint8(ctxt.Arch.PtrSize))
   245  		off := header.SetUint(ctxt.Arch, 8, uint64(state.nfunc))
   246  		off = header.SetUint(ctxt.Arch, off, uint64(state.nfiles))
   247  		off = writeSymOffset(off, state.funcnametab)
   248  		off = writeSymOffset(off, state.cutab)
   249  		off = writeSymOffset(off, state.filetab)
   250  		off = writeSymOffset(off, state.pctab)
   251  		off = writeSymOffset(off, state.pclntab)
   252  	}
   253  
   254  	size := int64(8 + 7*ctxt.Arch.PtrSize)
   255  	state.pcheader = state.addGeneratedSym(ctxt, "runtime.pcheader", size, writeHeader)
   256  }
   257  
   258  // walkFuncs iterates over the funcs, calling a function for each unique
   259  // function and inlined function.
   260  func walkFuncs(ctxt *Link, funcs []loader.Sym, f func(loader.Sym)) {
   261  	ldr := ctxt.loader
   262  	seen := make(map[loader.Sym]struct{})
   263  	for _, s := range funcs {
   264  		if _, ok := seen[s]; !ok {
   265  			f(s)
   266  			seen[s] = struct{}{}
   267  		}
   268  
   269  		fi := ldr.FuncInfo(s)
   270  		if !fi.Valid() {
   271  			continue
   272  		}
   273  		fi.Preload()
   274  		for i, ni := 0, fi.NumInlTree(); i < int(ni); i++ {
   275  			call := fi.InlTree(i).Func
   276  			if _, ok := seen[call]; !ok {
   277  				f(call)
   278  				seen[call] = struct{}{}
   279  			}
   280  		}
   281  	}
   282  }
   283  
   284  // generateFuncnametab creates the function name table. Returns a map of
   285  // func symbol to the name offset in runtime.funcnamtab.
   286  func (state *pclntab) generateFuncnametab(ctxt *Link, funcs []loader.Sym) map[loader.Sym]uint32 {
   287  	nameOffsets := make(map[loader.Sym]uint32, state.nfunc)
   288  
   289  	// Write the null terminated strings.
   290  	writeFuncNameTab := func(ctxt *Link, s loader.Sym) {
   291  		symtab := ctxt.loader.MakeSymbolUpdater(s)
   292  		for s, off := range nameOffsets {
   293  			symtab.AddStringAt(int64(off), ctxt.loader.SymName(s))
   294  		}
   295  	}
   296  
   297  	// Loop through the CUs, and calculate the size needed.
   298  	var size int64
   299  	walkFuncs(ctxt, funcs, func(s loader.Sym) {
   300  		nameOffsets[s] = uint32(size)
   301  		size += int64(ctxt.loader.SymNameLen(s)) + 1 // NULL terminate
   302  	})
   303  
   304  	state.funcnametab = state.addGeneratedSym(ctxt, "runtime.funcnametab", size, writeFuncNameTab)
   305  	return nameOffsets
   306  }
   307  
   308  // walkFilenames walks funcs, calling a function for each filename used in each
   309  // function's line table.
   310  func walkFilenames(ctxt *Link, funcs []loader.Sym, f func(*sym.CompilationUnit, goobj.CUFileIndex)) {
   311  	ldr := ctxt.loader
   312  
   313  	// Loop through all functions, finding the filenames we need.
   314  	for _, s := range funcs {
   315  		fi := ldr.FuncInfo(s)
   316  		if !fi.Valid() {
   317  			continue
   318  		}
   319  		fi.Preload()
   320  
   321  		cu := ldr.SymUnit(s)
   322  		for i, nf := 0, int(fi.NumFile()); i < nf; i++ {
   323  			f(cu, fi.File(i))
   324  		}
   325  		for i, ninl := 0, int(fi.NumInlTree()); i < ninl; i++ {
   326  			call := fi.InlTree(i)
   327  			f(cu, call.File)
   328  		}
   329  	}
   330  }
   331  
   332  // generateFilenameTabs creates LUTs needed for filename lookup. Returns a slice
   333  // of the index at which each CU begins in runtime.cutab.
   334  //
   335  // Function objects keep track of the files they reference to print the stack.
   336  // This function creates a per-CU list of filenames if CU[M] references
   337  // files[1-N], the following is generated:
   338  //
   339  //  runtime.cutab:
   340  //    CU[M]
   341  //     offsetToFilename[0]
   342  //     offsetToFilename[1]
   343  //     ..
   344  //
   345  //  runtime.filetab
   346  //     filename[0]
   347  //     filename[1]
   348  //
   349  // Looking up a filename then becomes:
   350  //  0) Given a func, and filename index [K]
   351  //  1) Get Func.CUIndex:       M := func.cuOffset
   352  //  2) Find filename offset:   fileOffset := runtime.cutab[M+K]
   353  //  3) Get the filename:       getcstring(runtime.filetab[fileOffset])
   354  func (state *pclntab) generateFilenameTabs(ctxt *Link, compUnits []*sym.CompilationUnit, funcs []loader.Sym) []uint32 {
   355  	// On a per-CU basis, keep track of all the filenames we need.
   356  	//
   357  	// Note, that we store the filenames in a separate section in the object
   358  	// files, and deduplicate based on the actual value. It would be better to
   359  	// store the filenames as symbols, using content addressable symbols (and
   360  	// then not loading extra filenames), and just use the hash value of the
   361  	// symbol name to do this cataloging.
   362  	//
   363  	// TOOD: Store filenames as symbols. (Note this would be easiest if you
   364  	// also move strings to ALWAYS using the larger content addressable hash
   365  	// function, and use that hash value for uniqueness testing.)
   366  	cuEntries := make([]goobj.CUFileIndex, len(compUnits))
   367  	fileOffsets := make(map[string]uint32)
   368  
   369  	// Walk the filenames.
   370  	// We store the total filename string length we need to load, and the max
   371  	// file index we've seen per CU so we can calculate how large the
   372  	// CU->global table needs to be.
   373  	var fileSize int64
   374  	walkFilenames(ctxt, funcs, func(cu *sym.CompilationUnit, i goobj.CUFileIndex) {
   375  		// Note we use the raw filename for lookup, but use the expanded filename
   376  		// when we save the size.
   377  		filename := cu.FileTable[i]
   378  		if _, ok := fileOffsets[filename]; !ok {
   379  			fileOffsets[filename] = uint32(fileSize)
   380  			fileSize += int64(len(expandFile(filename)) + 1) // NULL terminate
   381  		}
   382  
   383  		// Find the maximum file index we've seen.
   384  		if cuEntries[cu.PclnIndex] < i+1 {
   385  			cuEntries[cu.PclnIndex] = i + 1 // Store max + 1
   386  		}
   387  	})
   388  
   389  	// Calculate the size of the runtime.cutab variable.
   390  	var totalEntries uint32
   391  	cuOffsets := make([]uint32, len(cuEntries))
   392  	for i, entries := range cuEntries {
   393  		// Note, cutab is a slice of uint32, so an offset to a cu's entry is just the
   394  		// running total of all cu indices we've needed to store so far, not the
   395  		// number of bytes we've stored so far.
   396  		cuOffsets[i] = totalEntries
   397  		totalEntries += uint32(entries)
   398  	}
   399  
   400  	// Write cutab.
   401  	writeCutab := func(ctxt *Link, s loader.Sym) {
   402  		sb := ctxt.loader.MakeSymbolUpdater(s)
   403  
   404  		var off int64
   405  		for i, max := range cuEntries {
   406  			// Write the per CU LUT.
   407  			cu := compUnits[i]
   408  			for j := goobj.CUFileIndex(0); j < max; j++ {
   409  				fileOffset, ok := fileOffsets[cu.FileTable[j]]
   410  				if !ok {
   411  					// We're looping through all possible file indices. It's possible a file's
   412  					// been deadcode eliminated, and although it's a valid file in the CU, it's
   413  					// not needed in this binary. When that happens, use an invalid offset.
   414  					fileOffset = ^uint32(0)
   415  				}
   416  				off = sb.SetUint32(ctxt.Arch, off, fileOffset)
   417  			}
   418  		}
   419  	}
   420  	state.cutab = state.addGeneratedSym(ctxt, "runtime.cutab", int64(totalEntries*4), writeCutab)
   421  
   422  	// Write filetab.
   423  	writeFiletab := func(ctxt *Link, s loader.Sym) {
   424  		sb := ctxt.loader.MakeSymbolUpdater(s)
   425  
   426  		// Write the strings.
   427  		for filename, loc := range fileOffsets {
   428  			sb.AddStringAt(int64(loc), expandFile(filename))
   429  		}
   430  	}
   431  	state.nfiles = uint32(len(fileOffsets))
   432  	state.filetab = state.addGeneratedSym(ctxt, "runtime.filetab", fileSize, writeFiletab)
   433  
   434  	return cuOffsets
   435  }
   436  
   437  // generatePctab creates the runtime.pctab variable, holding all the
   438  // deduplicated pcdata.
   439  func (state *pclntab) generatePctab(ctxt *Link, funcs []loader.Sym) {
   440  	ldr := ctxt.loader
   441  
   442  	// Pctab offsets of 0 are considered invalid in the runtime. We respect
   443  	// that by just padding a single byte at the beginning of runtime.pctab,
   444  	// that way no real offsets can be zero.
   445  	size := int64(1)
   446  
   447  	// Walk the functions, finding offset to store each pcdata.
   448  	seen := make(map[loader.Sym]struct{})
   449  	saveOffset := func(pcSym loader.Sym) {
   450  		if _, ok := seen[pcSym]; !ok {
   451  			datSize := ldr.SymSize(pcSym)
   452  			if datSize != 0 {
   453  				ldr.SetSymValue(pcSym, size)
   454  			} else {
   455  				// Invalid PC data, record as zero.
   456  				ldr.SetSymValue(pcSym, 0)
   457  			}
   458  			size += datSize
   459  			seen[pcSym] = struct{}{}
   460  		}
   461  	}
   462  	for _, s := range funcs {
   463  		fi := ldr.FuncInfo(s)
   464  		if !fi.Valid() {
   465  			continue
   466  		}
   467  		fi.Preload()
   468  
   469  		pcSyms := []loader.Sym{fi.Pcsp(), fi.Pcfile(), fi.Pcline()}
   470  		for _, pcSym := range pcSyms {
   471  			saveOffset(pcSym)
   472  		}
   473  		for _, pcSym := range fi.Pcdata() {
   474  			saveOffset(pcSym)
   475  		}
   476  		if fi.NumInlTree() > 0 {
   477  			saveOffset(fi.Pcinline())
   478  		}
   479  	}
   480  
   481  	// TODO: There is no reason we need a generator for this variable, and it
   482  	// could be moved to a carrier symbol. However, carrier symbols containing
   483  	// carrier symbols don't work yet (as of Aug 2020). Once this is fixed,
   484  	// runtime.pctab could just be a carrier sym.
   485  	writePctab := func(ctxt *Link, s loader.Sym) {
   486  		ldr := ctxt.loader
   487  		sb := ldr.MakeSymbolUpdater(s)
   488  		for sym := range seen {
   489  			sb.SetBytesAt(ldr.SymValue(sym), ldr.Data(sym))
   490  		}
   491  	}
   492  
   493  	state.pctab = state.addGeneratedSym(ctxt, "runtime.pctab", size, writePctab)
   494  }
   495  
   496  // numPCData returns the number of PCData syms for the FuncInfo.
   497  // NB: Preload must be called on valid FuncInfos before calling this function.
   498  func numPCData(fi loader.FuncInfo) uint32 {
   499  	if !fi.Valid() {
   500  		return 0
   501  	}
   502  	numPCData := uint32(len(fi.Pcdata()))
   503  	if fi.NumInlTree() > 0 {
   504  		if numPCData < objabi.PCDATA_InlTreeIndex+1 {
   505  			numPCData = objabi.PCDATA_InlTreeIndex + 1
   506  		}
   507  	}
   508  	return numPCData
   509  }
   510  
   511  // Helper types for iterating pclntab.
   512  type pclnSetAddr func(*loader.SymbolBuilder, *sys.Arch, int64, loader.Sym, int64) int64
   513  type pclnSetUint func(*loader.SymbolBuilder, *sys.Arch, int64, uint64) int64
   514  
   515  // generateFunctab creates the runtime.functab
   516  //
   517  // runtime.functab contains two things:
   518  //
   519  //   - pc->func look up table.
   520  //   - array of func objects, interleaved with pcdata and funcdata
   521  //
   522  // Because of timing in the linker, generating this table takes two passes.
   523  // The first pass is executed early in the link, and it creates any needed
   524  // relocations to layout the data. The pieces that need relocations are:
   525  //   1) the PC->func table.
   526  //   2) The entry points in the func objects.
   527  //   3) The funcdata.
   528  // (1) and (2) are handled in walkPCToFunc. (3) is handled in walkFuncdata.
   529  //
   530  // After relocations, once we know where to write things in the output buffer,
   531  // we execute the second pass, which is actually writing the data.
   532  func (state *pclntab) generateFunctab(ctxt *Link, funcs []loader.Sym, inlSyms map[loader.Sym]loader.Sym, cuOffsets []uint32, nameOffsets map[loader.Sym]uint32) {
   533  	// Calculate the size of the table.
   534  	size, startLocations := state.calculateFunctabSize(ctxt, funcs)
   535  
   536  	// If we are internally linking a static executable, the function addresses
   537  	// are known, so we can just use them instead of emitting relocations. For
   538  	// other cases we still need to emit relocations.
   539  	//
   540  	// This boolean just helps us figure out which callback to use.
   541  	useSymValue := ctxt.IsExe() && ctxt.IsInternal()
   542  
   543  	writePcln := func(ctxt *Link, s loader.Sym) {
   544  		ldr := ctxt.loader
   545  		sb := ldr.MakeSymbolUpdater(s)
   546  
   547  		// Create our callbacks.
   548  		var setAddr pclnSetAddr
   549  		if useSymValue {
   550  			// We need to write the offset.
   551  			setAddr = func(s *loader.SymbolBuilder, arch *sys.Arch, off int64, tgt loader.Sym, add int64) int64 {
   552  				if v := ldr.SymValue(tgt); v != 0 {
   553  					s.SetUint(arch, off, uint64(v+add))
   554  				}
   555  				return 0
   556  			}
   557  		} else {
   558  			// We already wrote relocations.
   559  			setAddr = func(s *loader.SymbolBuilder, arch *sys.Arch, off int64, tgt loader.Sym, add int64) int64 { return 0 }
   560  		}
   561  
   562  		// Write the data.
   563  		writePcToFunc(ctxt, sb, funcs, startLocations, setAddr, (*loader.SymbolBuilder).SetUint)
   564  		writeFuncs(ctxt, sb, funcs, inlSyms, startLocations, cuOffsets, nameOffsets)
   565  		state.writeFuncData(ctxt, sb, funcs, inlSyms, startLocations, setAddr, (*loader.SymbolBuilder).SetUint)
   566  	}
   567  
   568  	state.pclntab = state.addGeneratedSym(ctxt, "runtime.functab", size, writePcln)
   569  
   570  	// Create the relocations we need.
   571  	ldr := ctxt.loader
   572  	sb := ldr.MakeSymbolUpdater(state.pclntab)
   573  
   574  	var setAddr pclnSetAddr
   575  	if useSymValue {
   576  		// If we should use the symbol value, and we don't have one, write a relocation.
   577  		setAddr = func(sb *loader.SymbolBuilder, arch *sys.Arch, off int64, tgt loader.Sym, add int64) int64 {
   578  			if v := ldr.SymValue(tgt); v == 0 {
   579  				sb.SetAddrPlus(arch, off, tgt, add)
   580  			}
   581  			return 0
   582  		}
   583  	} else {
   584  		// If we're externally linking, write a relocation.
   585  		setAddr = (*loader.SymbolBuilder).SetAddrPlus
   586  	}
   587  	setUintNOP := func(*loader.SymbolBuilder, *sys.Arch, int64, uint64) int64 { return 0 }
   588  	writePcToFunc(ctxt, sb, funcs, startLocations, setAddr, setUintNOP)
   589  	if !useSymValue {
   590  		// Generate relocations for funcdata when externally linking.
   591  		state.writeFuncData(ctxt, sb, funcs, inlSyms, startLocations, setAddr, setUintNOP)
   592  	}
   593  }
   594  
   595  // funcData returns the funcdata and offsets for the FuncInfo.
   596  // The funcdata and offsets are written into runtime.functab after each func
   597  // object. This is a helper function to make querying the FuncInfo object
   598  // cleaner.
   599  //
   600  // Note, the majority of fdOffsets are 0, meaning there is no offset between
   601  // the compiler's generated symbol, and what the runtime needs. They are
   602  // plumbed through for no loss of generality.
   603  //
   604  // NB: Preload must be called on the FuncInfo before calling.
   605  // NB: fdSyms and fdOffs are used as scratch space.
   606  func funcData(fi loader.FuncInfo, inlSym loader.Sym, fdSyms []loader.Sym, fdOffs []int64) ([]loader.Sym, []int64) {
   607  	fdSyms, fdOffs = fdSyms[:0], fdOffs[:0]
   608  	if fi.Valid() {
   609  		numOffsets := int(fi.NumFuncdataoff())
   610  		for i := 0; i < numOffsets; i++ {
   611  			fdOffs = append(fdOffs, fi.Funcdataoff(i))
   612  		}
   613  		fdSyms = fi.Funcdata(fdSyms)
   614  		if fi.NumInlTree() > 0 {
   615  			if len(fdSyms) < objabi.FUNCDATA_InlTree+1 {
   616  				fdSyms = append(fdSyms, make([]loader.Sym, objabi.FUNCDATA_InlTree+1-len(fdSyms))...)
   617  				fdOffs = append(fdOffs, make([]int64, objabi.FUNCDATA_InlTree+1-len(fdOffs))...)
   618  			}
   619  			fdSyms[objabi.FUNCDATA_InlTree] = inlSym
   620  		}
   621  	}
   622  	return fdSyms, fdOffs
   623  }
   624  
   625  // calculateFunctabSize calculates the size of the pclntab, and the offsets in
   626  // the output buffer for individual func entries.
   627  func (state pclntab) calculateFunctabSize(ctxt *Link, funcs []loader.Sym) (int64, []uint32) {
   628  	ldr := ctxt.loader
   629  	startLocations := make([]uint32, len(funcs))
   630  
   631  	// Allocate space for the pc->func table. This structure consists of a pc
   632  	// and an offset to the func structure. After that, we have a single pc
   633  	// value that marks the end of the last function in the binary.
   634  	size := int64(int(state.nfunc)*2*ctxt.Arch.PtrSize + ctxt.Arch.PtrSize)
   635  
   636  	// Now find the space for the func objects. We do this in a running manner,
   637  	// so that we can find individual starting locations, and because funcdata
   638  	// requires alignment.
   639  	for i, s := range funcs {
   640  		size = Rnd(size, int64(ctxt.Arch.PtrSize))
   641  		startLocations[i] = uint32(size)
   642  		fi := ldr.FuncInfo(s)
   643  		size += int64(state.funcSize)
   644  		if fi.Valid() {
   645  			fi.Preload()
   646  			numFuncData := int(fi.NumFuncdataoff())
   647  			if fi.NumInlTree() > 0 {
   648  				if numFuncData < objabi.FUNCDATA_InlTree+1 {
   649  					numFuncData = objabi.FUNCDATA_InlTree + 1
   650  				}
   651  			}
   652  			size += int64(numPCData(fi) * 4)
   653  			if numFuncData > 0 { // Func data is aligned.
   654  				size = Rnd(size, int64(ctxt.Arch.PtrSize))
   655  			}
   656  			size += int64(numFuncData * ctxt.Arch.PtrSize)
   657  		}
   658  	}
   659  
   660  	return size, startLocations
   661  }
   662  
   663  // writePcToFunc writes the PC->func lookup table.
   664  // This function walks the pc->func lookup table, executing callbacks
   665  // to generate relocations and writing the values for the table.
   666  func writePcToFunc(ctxt *Link, sb *loader.SymbolBuilder, funcs []loader.Sym, startLocations []uint32, setAddr pclnSetAddr, setUint pclnSetUint) {
   667  	ldr := ctxt.loader
   668  	var prevFunc loader.Sym
   669  	prevSect := ldr.SymSect(funcs[0])
   670  	funcIndex := 0
   671  	for i, s := range funcs {
   672  		if thisSect := ldr.SymSect(s); thisSect != prevSect {
   673  			// With multiple text sections, there may be a hole here in the
   674  			// address space. We use an invalid funcoff value to mark the hole.
   675  			// See also runtime/symtab.go:findfunc
   676  			prevFuncSize := int64(ldr.SymSize(prevFunc))
   677  			setAddr(sb, ctxt.Arch, int64(funcIndex*2*ctxt.Arch.PtrSize), prevFunc, prevFuncSize)
   678  			setUint(sb, ctxt.Arch, int64((funcIndex*2+1)*ctxt.Arch.PtrSize), ^uint64(0))
   679  			funcIndex++
   680  			prevSect = thisSect
   681  		}
   682  		prevFunc = s
   683  		// TODO: We don't actually need these relocations, provided we go to a
   684  		// module->func look-up-table like we do for filenames. We could have a
   685  		// single relocation for the module, and have them all laid out as
   686  		// offsets from the beginning of that module.
   687  		setAddr(sb, ctxt.Arch, int64(funcIndex*2*ctxt.Arch.PtrSize), s, 0)
   688  		setUint(sb, ctxt.Arch, int64((funcIndex*2+1)*ctxt.Arch.PtrSize), uint64(startLocations[i]))
   689  		funcIndex++
   690  
   691  		// Write the entry location.
   692  		setAddr(sb, ctxt.Arch, int64(startLocations[i]), s, 0)
   693  	}
   694  
   695  	// Final entry of table is just end pc.
   696  	setAddr(sb, ctxt.Arch, int64(funcIndex)*2*int64(ctxt.Arch.PtrSize), prevFunc, ldr.SymSize(prevFunc))
   697  }
   698  
   699  // writeFuncData writes the funcdata tables.
   700  //
   701  // This function executes a callback for each funcdata needed in
   702  // runtime.functab. It should be called once for internally linked static
   703  // binaries, or twice (once to generate the needed relocations) for other
   704  // build modes.
   705  //
   706  // Note the output of this function is interwoven with writeFuncs, but this is
   707  // a separate function, because it's needed in different passes in
   708  // generateFunctab.
   709  func (state *pclntab) writeFuncData(ctxt *Link, sb *loader.SymbolBuilder, funcs []loader.Sym, inlSyms map[loader.Sym]loader.Sym, startLocations []uint32, setAddr pclnSetAddr, setUint pclnSetUint) {
   710  	ldr := ctxt.loader
   711  	funcdata, funcdataoff := []loader.Sym{}, []int64{}
   712  	for i, s := range funcs {
   713  		fi := ldr.FuncInfo(s)
   714  		if !fi.Valid() {
   715  			continue
   716  		}
   717  		fi.Preload()
   718  
   719  		// funcdata, must be pointer-aligned and we're only int32-aligned.
   720  		// Missing funcdata will be 0 (nil pointer).
   721  		funcdata, funcdataoff := funcData(fi, inlSyms[s], funcdata, funcdataoff)
   722  		if len(funcdata) > 0 {
   723  			off := int64(startLocations[i] + state.funcSize + numPCData(fi)*4)
   724  			off = Rnd(off, int64(ctxt.Arch.PtrSize))
   725  			for j := range funcdata {
   726  				dataoff := off + int64(ctxt.Arch.PtrSize*j)
   727  				if funcdata[j] == 0 {
   728  					setUint(sb, ctxt.Arch, dataoff, uint64(funcdataoff[j]))
   729  					continue
   730  				}
   731  				// TODO: Does this need deduping?
   732  				setAddr(sb, ctxt.Arch, dataoff, funcdata[j], funcdataoff[j])
   733  			}
   734  		}
   735  	}
   736  }
   737  
   738  // writeFuncs writes the func structures and pcdata to runtime.functab.
   739  func writeFuncs(ctxt *Link, sb *loader.SymbolBuilder, funcs []loader.Sym, inlSyms map[loader.Sym]loader.Sym, startLocations, cuOffsets []uint32, nameOffsets map[loader.Sym]uint32) {
   740  	ldr := ctxt.loader
   741  	deferReturnSym := ldr.Lookup("runtime.deferreturn", sym.SymVerABIInternal)
   742  	funcdata, funcdataoff := []loader.Sym{}, []int64{}
   743  
   744  	// Write the individual func objects.
   745  	for i, s := range funcs {
   746  		fi := ldr.FuncInfo(s)
   747  		if fi.Valid() {
   748  			fi.Preload()
   749  		}
   750  
   751  		// Note we skip the space for the entry value -- that's handled inn
   752  		// walkPCToFunc. We don't write it here, because it might require a
   753  		// relocation.
   754  		off := startLocations[i] + uint32(ctxt.Arch.PtrSize) // entry
   755  
   756  		// name int32
   757  		nameoff, ok := nameOffsets[s]
   758  		if !ok {
   759  			panic("couldn't find function name offset")
   760  		}
   761  		off = uint32(sb.SetUint32(ctxt.Arch, int64(off), uint32(nameoff)))
   762  
   763  		// args int32
   764  		// TODO: Move into funcinfo.
   765  		args := uint32(0)
   766  		if fi.Valid() {
   767  			args = uint32(fi.Args())
   768  		}
   769  		off = uint32(sb.SetUint32(ctxt.Arch, int64(off), args))
   770  
   771  		// deferreturn
   772  		deferreturn := computeDeferReturn(ctxt, deferReturnSym, s)
   773  		off = uint32(sb.SetUint32(ctxt.Arch, int64(off), deferreturn))
   774  
   775  		// pcdata
   776  		if fi.Valid() {
   777  			off = uint32(sb.SetUint32(ctxt.Arch, int64(off), uint32(ldr.SymValue(fi.Pcsp()))))
   778  			off = uint32(sb.SetUint32(ctxt.Arch, int64(off), uint32(ldr.SymValue(fi.Pcfile()))))
   779  			off = uint32(sb.SetUint32(ctxt.Arch, int64(off), uint32(ldr.SymValue(fi.Pcline()))))
   780  		} else {
   781  			off += 12
   782  		}
   783  		off = uint32(sb.SetUint32(ctxt.Arch, int64(off), uint32(numPCData(fi))))
   784  
   785  		// Store the offset to compilation unit's file table.
   786  		cuIdx := ^uint32(0)
   787  		if cu := ldr.SymUnit(s); cu != nil {
   788  			cuIdx = cuOffsets[cu.PclnIndex]
   789  		}
   790  		off = uint32(sb.SetUint32(ctxt.Arch, int64(off), cuIdx))
   791  
   792  		// funcID uint8
   793  		var funcID objabi.FuncID
   794  		if fi.Valid() {
   795  			funcID = fi.FuncID()
   796  		}
   797  		off = uint32(sb.SetUint8(ctxt.Arch, int64(off), uint8(funcID)))
   798  
   799  		off += 2 // pad
   800  
   801  		// nfuncdata must be the final entry.
   802  		funcdata, funcdataoff = funcData(fi, 0, funcdata, funcdataoff)
   803  		off = uint32(sb.SetUint8(ctxt.Arch, int64(off), uint8(len(funcdata))))
   804  
   805  		// Output the pcdata.
   806  		if fi.Valid() {
   807  			for j, pcSym := range fi.Pcdata() {
   808  				sb.SetUint32(ctxt.Arch, int64(off+uint32(j*4)), uint32(ldr.SymValue(pcSym)))
   809  			}
   810  			if fi.NumInlTree() > 0 {
   811  				sb.SetUint32(ctxt.Arch, int64(off+objabi.PCDATA_InlTreeIndex*4), uint32(ldr.SymValue(fi.Pcinline())))
   812  			}
   813  		}
   814  	}
   815  }
   816  
   817  // pclntab initializes the pclntab symbol with
   818  // runtime function and file name information.
   819  
   820  // pclntab generates the pcln table for the link output.
   821  func (ctxt *Link) pclntab(container loader.Bitmap) *pclntab {
   822  	// Go 1.2's symtab layout is documented in golang.org/s/go12symtab, but the
   823  	// layout and data has changed since that time.
   824  	//
   825  	// As of August 2020, here's the layout of pclntab:
   826  	//
   827  	//  .gopclntab/__gopclntab [elf/macho section]
   828  	//    runtime.pclntab
   829  	//      Carrier symbol for the entire pclntab section.
   830  	//
   831  	//      runtime.pcheader  (see: runtime/symtab.go:pcHeader)
   832  	//        8-byte magic
   833  	//        nfunc [thearch.ptrsize bytes]
   834  	//        offset to runtime.funcnametab from the beginning of runtime.pcheader
   835  	//        offset to runtime.pclntab_old from beginning of runtime.pcheader
   836  	//
   837  	//      runtime.funcnametab
   838  	//        []list of null terminated function names
   839  	//
   840  	//      runtime.cutab
   841  	//        for i=0..#CUs
   842  	//          for j=0..#max used file index in CU[i]
   843  	//            uint32 offset into runtime.filetab for the filename[j]
   844  	//
   845  	//      runtime.filetab
   846  	//        []null terminated filename strings
   847  	//
   848  	//      runtime.pctab
   849  	//        []byte of deduplicated pc data.
   850  	//
   851  	//      runtime.functab
   852  	//        function table, alternating PC and offset to func struct [each entry thearch.ptrsize bytes]
   853  	//        end PC [thearch.ptrsize bytes]
   854  	//        func structures, pcdata offsets, func data.
   855  
   856  	state, compUnits, funcs := makePclntab(ctxt, container)
   857  
   858  	ldr := ctxt.loader
   859  	state.carrier = ldr.LookupOrCreateSym("runtime.pclntab", 0)
   860  	ldr.MakeSymbolUpdater(state.carrier).SetType(sym.SPCLNTAB)
   861  	ldr.SetAttrReachable(state.carrier, true)
   862  	setCarrierSym(sym.SPCLNTAB, state.carrier)
   863  
   864  	state.generatePCHeader(ctxt)
   865  	nameOffsets := state.generateFuncnametab(ctxt, funcs)
   866  	cuOffsets := state.generateFilenameTabs(ctxt, compUnits, funcs)
   867  	state.generatePctab(ctxt, funcs)
   868  	inlSyms := makeInlSyms(ctxt, funcs, nameOffsets)
   869  	state.generateFunctab(ctxt, funcs, inlSyms, cuOffsets, nameOffsets)
   870  
   871  	return state
   872  }
   873  
   874  func gorootFinal() string {
   875  	root := objabi.GOROOT
   876  	if final := os.Getenv("GOROOT_FINAL"); final != "" {
   877  		root = final
   878  	}
   879  	return root
   880  }
   881  
   882  func expandGoroot(s string) string {
   883  	const n = len("$GOROOT")
   884  	if len(s) >= n+1 && s[:n] == "$GOROOT" && (s[n] == '/' || s[n] == '\\') {
   885  		return filepath.ToSlash(filepath.Join(gorootFinal(), s[n:]))
   886  	}
   887  	return s
   888  }
   889  
   890  const (
   891  	BUCKETSIZE    = 256 * MINFUNC
   892  	SUBBUCKETS    = 16
   893  	SUBBUCKETSIZE = BUCKETSIZE / SUBBUCKETS
   894  	NOIDX         = 0x7fffffff
   895  )
   896  
   897  // findfunctab generates a lookup table to quickly find the containing
   898  // function for a pc. See src/runtime/symtab.go:findfunc for details.
   899  func (ctxt *Link) findfunctab(state *pclntab, container loader.Bitmap) {
   900  	ldr := ctxt.loader
   901  
   902  	// find min and max address
   903  	min := ldr.SymValue(ctxt.Textp[0])
   904  	lastp := ctxt.Textp[len(ctxt.Textp)-1]
   905  	max := ldr.SymValue(lastp) + ldr.SymSize(lastp)
   906  
   907  	// for each subbucket, compute the minimum of all symbol indexes
   908  	// that map to that subbucket.
   909  	n := int32((max - min + SUBBUCKETSIZE - 1) / SUBBUCKETSIZE)
   910  
   911  	nbuckets := int32((max - min + BUCKETSIZE - 1) / BUCKETSIZE)
   912  
   913  	size := 4*int64(nbuckets) + int64(n)
   914  
   915  	writeFindFuncTab := func(_ *Link, s loader.Sym) {
   916  		t := ldr.MakeSymbolUpdater(s)
   917  
   918  		indexes := make([]int32, n)
   919  		for i := int32(0); i < n; i++ {
   920  			indexes[i] = NOIDX
   921  		}
   922  		idx := int32(0)
   923  		for i, s := range ctxt.Textp {
   924  			if !emitPcln(ctxt, s, container) {
   925  				continue
   926  			}
   927  			p := ldr.SymValue(s)
   928  			var e loader.Sym
   929  			i++
   930  			if i < len(ctxt.Textp) {
   931  				e = ctxt.Textp[i]
   932  			}
   933  			for e != 0 && !emitPcln(ctxt, e, container) && i < len(ctxt.Textp) {
   934  				e = ctxt.Textp[i]
   935  				i++
   936  			}
   937  			q := max
   938  			if e != 0 {
   939  				q = ldr.SymValue(e)
   940  			}
   941  
   942  			//print("%d: [%lld %lld] %s\n", idx, p, q, s->name);
   943  			for ; p < q; p += SUBBUCKETSIZE {
   944  				i = int((p - min) / SUBBUCKETSIZE)
   945  				if indexes[i] > idx {
   946  					indexes[i] = idx
   947  				}
   948  			}
   949  
   950  			i = int((q - 1 - min) / SUBBUCKETSIZE)
   951  			if indexes[i] > idx {
   952  				indexes[i] = idx
   953  			}
   954  			idx++
   955  		}
   956  
   957  		// fill in table
   958  		for i := int32(0); i < nbuckets; i++ {
   959  			base := indexes[i*SUBBUCKETS]
   960  			if base == NOIDX {
   961  				Errorf(nil, "hole in findfunctab")
   962  			}
   963  			t.SetUint32(ctxt.Arch, int64(i)*(4+SUBBUCKETS), uint32(base))
   964  			for j := int32(0); j < SUBBUCKETS && i*SUBBUCKETS+j < n; j++ {
   965  				idx = indexes[i*SUBBUCKETS+j]
   966  				if idx == NOIDX {
   967  					Errorf(nil, "hole in findfunctab")
   968  				}
   969  				if idx-base >= 256 {
   970  					Errorf(nil, "too many functions in a findfunc bucket! %d/%d %d %d", i, nbuckets, j, idx-base)
   971  				}
   972  
   973  				t.SetUint8(ctxt.Arch, int64(i)*(4+SUBBUCKETS)+4+int64(j), uint8(idx-base))
   974  			}
   975  		}
   976  	}
   977  
   978  	state.findfunctab = ctxt.createGeneratorSymbol("runtime.findfunctab", 0, sym.SRODATA, size, writeFindFuncTab)
   979  	ldr.SetAttrReachable(state.findfunctab, true)
   980  	ldr.SetAttrLocal(state.findfunctab, true)
   981  }
   982  
   983  // findContainerSyms returns a bitmap, indexed by symbol number, where there's
   984  // a 1 for every container symbol.
   985  func (ctxt *Link) findContainerSyms() loader.Bitmap {
   986  	ldr := ctxt.loader
   987  	container := loader.MakeBitmap(ldr.NSym())
   988  	// Find container symbols and mark them as such.
   989  	for _, s := range ctxt.Textp {
   990  		outer := ldr.OuterSym(s)
   991  		if outer != 0 {
   992  			container.Set(outer)
   993  		}
   994  	}
   995  	return container
   996  }
   997  

View as plain text