github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/link/loader/loader.go (about)

     1  // Copyright 2019 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 loader
     6  
     7  import (
     8  	"bytes"
     9  	"debug/elf"
    10  	"fmt"
    11  	"io"
    12  	"log"
    13  	"math/bits"
    14  	"os"
    15  	"sort"
    16  	"strings"
    17  
    18  	"github.com/go-asm/go/abi"
    19  	"github.com/go-asm/go/cmd/bio"
    20  	"github.com/go-asm/go/cmd/goobj"
    21  	"github.com/go-asm/go/cmd/link/sym"
    22  	"github.com/go-asm/go/cmd/obj"
    23  	"github.com/go-asm/go/cmd/objabi"
    24  	"github.com/go-asm/go/cmd/sys"
    25  )
    26  
    27  var _ = fmt.Print
    28  
    29  // Sym encapsulates a global symbol index, used to identify a specific
    30  // Go symbol. The 0-valued Sym is corresponds to an invalid symbol.
    31  type Sym = sym.LoaderSym
    32  
    33  // Relocs encapsulates the set of relocations on a given symbol; an
    34  // instance of this type is returned by the Loader Relocs() method.
    35  type Relocs struct {
    36  	rs []goobj.Reloc
    37  
    38  	li uint32   // local index of symbol whose relocs we're examining
    39  	r  *oReader // object reader for containing package
    40  	l  *Loader  // loader
    41  }
    42  
    43  // ExtReloc contains the payload for an external relocation.
    44  type ExtReloc struct {
    45  	Xsym Sym
    46  	Xadd int64
    47  	Type objabi.RelocType
    48  	Size uint8
    49  }
    50  
    51  // Reloc holds a "handle" to access a relocation record from an
    52  // object file.
    53  type Reloc struct {
    54  	*goobj.Reloc
    55  	r *oReader
    56  	l *Loader
    57  }
    58  
    59  func (rel Reloc) Type() objabi.RelocType     { return objabi.RelocType(rel.Reloc.Type()) &^ objabi.R_WEAK }
    60  func (rel Reloc) Weak() bool                 { return objabi.RelocType(rel.Reloc.Type())&objabi.R_WEAK != 0 }
    61  func (rel Reloc) SetType(t objabi.RelocType) { rel.Reloc.SetType(uint16(t)) }
    62  func (rel Reloc) Sym() Sym                   { return rel.l.resolve(rel.r, rel.Reloc.Sym()) }
    63  func (rel Reloc) SetSym(s Sym)               { rel.Reloc.SetSym(goobj.SymRef{PkgIdx: 0, SymIdx: uint32(s)}) }
    64  func (rel Reloc) IsMarker() bool             { return rel.Siz() == 0 }
    65  
    66  // Aux holds a "handle" to access an aux symbol record from an
    67  // object file.
    68  type Aux struct {
    69  	*goobj.Aux
    70  	r *oReader
    71  	l *Loader
    72  }
    73  
    74  func (a Aux) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
    75  
    76  // oReader is a wrapper type of obj.Reader, along with some
    77  // extra information.
    78  type oReader struct {
    79  	*goobj.Reader
    80  	unit         *sym.CompilationUnit
    81  	version      int // version of static symbol
    82  	pkgprefix    string
    83  	syms         []Sym    // Sym's global index, indexed by local index
    84  	pkg          []uint32 // indices of referenced package by PkgIdx (index into loader.objs array)
    85  	ndef         int      // cache goobj.Reader.NSym()
    86  	nhashed64def int      // cache goobj.Reader.NHashed64Def()
    87  	nhasheddef   int      // cache goobj.Reader.NHashedDef()
    88  	objidx       uint32   // index of this reader in the objs slice
    89  }
    90  
    91  // Total number of defined symbols (package symbols, hashed symbols, and
    92  // non-package symbols).
    93  func (r *oReader) NAlldef() int { return r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef() }
    94  
    95  type objIdx struct {
    96  	r *oReader
    97  	i Sym // start index
    98  }
    99  
   100  // objSym represents a symbol in an object file. It is a tuple of
   101  // the object and the symbol's local index.
   102  // For external symbols, objidx is the index of l.extReader (extObj),
   103  // s is its index into the payload array.
   104  // {0, 0} represents the nil symbol.
   105  type objSym struct {
   106  	objidx uint32 // index of the object (in l.objs array)
   107  	s      uint32 // local index
   108  }
   109  
   110  type nameVer struct {
   111  	name string
   112  	v    int
   113  }
   114  
   115  type Bitmap []uint32
   116  
   117  // set the i-th bit.
   118  func (bm Bitmap) Set(i Sym) {
   119  	n, r := uint(i)/32, uint(i)%32
   120  	bm[n] |= 1 << r
   121  }
   122  
   123  // unset the i-th bit.
   124  func (bm Bitmap) Unset(i Sym) {
   125  	n, r := uint(i)/32, uint(i)%32
   126  	bm[n] &^= (1 << r)
   127  }
   128  
   129  // whether the i-th bit is set.
   130  func (bm Bitmap) Has(i Sym) bool {
   131  	n, r := uint(i)/32, uint(i)%32
   132  	return bm[n]&(1<<r) != 0
   133  }
   134  
   135  // return current length of bitmap in bits.
   136  func (bm Bitmap) Len() int {
   137  	return len(bm) * 32
   138  }
   139  
   140  // return the number of bits set.
   141  func (bm Bitmap) Count() int {
   142  	s := 0
   143  	for _, x := range bm {
   144  		s += bits.OnesCount32(x)
   145  	}
   146  	return s
   147  }
   148  
   149  func MakeBitmap(n int) Bitmap {
   150  	return make(Bitmap, (n+31)/32)
   151  }
   152  
   153  // growBitmap insures that the specified bitmap has enough capacity,
   154  // reallocating (doubling the size) if needed.
   155  func growBitmap(reqLen int, b Bitmap) Bitmap {
   156  	curLen := b.Len()
   157  	if reqLen > curLen {
   158  		b = append(b, MakeBitmap(reqLen+1-curLen)...)
   159  	}
   160  	return b
   161  }
   162  
   163  type symAndSize struct {
   164  	sym  Sym
   165  	size uint32
   166  }
   167  
   168  // A Loader loads new object files and resolves indexed symbol references.
   169  //
   170  // Notes on the layout of global symbol index space:
   171  //
   172  //   - Go object files are read before host object files; each Go object
   173  //     read adds its defined package symbols to the global index space.
   174  //     Nonpackage symbols are not yet added.
   175  //
   176  //   - In loader.LoadNonpkgSyms, add non-package defined symbols and
   177  //     references in all object files to the global index space.
   178  //
   179  //   - Host object file loading happens; the host object loader does a
   180  //     name/version lookup for each symbol it finds; this can wind up
   181  //     extending the external symbol index space range. The host object
   182  //     loader stores symbol payloads in loader.payloads using SymbolBuilder.
   183  //
   184  //   - Each symbol gets a unique global index. For duplicated and
   185  //     overwriting/overwritten symbols, the second (or later) appearance
   186  //     of the symbol gets the same global index as the first appearance.
   187  type Loader struct {
   188  	start       map[*oReader]Sym // map from object file to its start index
   189  	objs        []objIdx         // sorted by start index (i.e. objIdx.i)
   190  	extStart    Sym              // from this index on, the symbols are externally defined
   191  	builtinSyms []Sym            // global index of builtin symbols
   192  
   193  	objSyms []objSym // global index mapping to local index
   194  
   195  	symsByName    [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
   196  	extStaticSyms map[nameVer]Sym   // externally defined static symbols, keyed by name
   197  
   198  	extReader    *oReader // a dummy oReader, for external symbols
   199  	payloadBatch []extSymPayload
   200  	payloads     []*extSymPayload // contents of linker-materialized external syms
   201  	values       []int64          // symbol values, indexed by global sym index
   202  
   203  	sects    []*sym.Section // sections
   204  	symSects []uint16       // symbol's section, index to sects array
   205  
   206  	align []uint8 // symbol 2^N alignment, indexed by global index
   207  
   208  	deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
   209  
   210  	objByPkg map[string]uint32 // map package path to the index of its Go object reader
   211  
   212  	anonVersion int // most recently assigned ext static sym pseudo-version
   213  
   214  	// Bitmaps and other side structures used to store data used to store
   215  	// symbol flags/attributes; these are to be accessed via the
   216  	// corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
   217  	// visit the comments on these methods for more details on the
   218  	// semantics / interpretation of the specific flags or attribute.
   219  	attrReachable        Bitmap // reachable symbols, indexed by global index
   220  	attrOnList           Bitmap // "on list" symbols, indexed by global index
   221  	attrLocal            Bitmap // "local" symbols, indexed by global index
   222  	attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by global idx
   223  	attrUsedInIface      Bitmap // "used in interface" symbols, indexed by global idx
   224  	attrSpecial          Bitmap // "special" frame symbols, indexed by global idx
   225  	attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
   226  	attrDuplicateOK      Bitmap // dupOK symbols, indexed by ext sym index
   227  	attrShared           Bitmap // shared symbols, indexed by ext sym index
   228  	attrExternal         Bitmap // external symbols, indexed by ext sym index
   229  	generatedSyms        Bitmap // symbols that generate their content, indexed by ext sym idx
   230  
   231  	attrReadOnly         map[Sym]bool     // readonly data for this sym
   232  	attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
   233  	attrCgoExportStatic  map[Sym]struct{} // "cgo_export_static" symbols
   234  
   235  	// Outer and Sub relations for symbols.
   236  	outer []Sym // indexed by global index
   237  	sub   map[Sym]Sym
   238  
   239  	dynimplib   map[Sym]string      // stores Dynimplib symbol attribute
   240  	dynimpvers  map[Sym]string      // stores Dynimpvers symbol attribute
   241  	localentry  map[Sym]uint8       // stores Localentry symbol attribute
   242  	extname     map[Sym]string      // stores Extname symbol attribute
   243  	elfType     map[Sym]elf.SymType // stores elf type symbol property
   244  	elfSym      map[Sym]int32       // stores elf sym symbol property
   245  	localElfSym map[Sym]int32       // stores "local" elf sym symbol property
   246  	symPkg      map[Sym]string      // stores package for symbol, or library for shlib-derived syms
   247  	plt         map[Sym]int32       // stores dynimport for pe objects
   248  	got         map[Sym]int32       // stores got for pe objects
   249  	dynid       map[Sym]int32       // stores Dynid for symbol
   250  
   251  	relocVariant map[relocId]sym.RelocVariant // stores variant relocs
   252  
   253  	// Used to implement field tracking; created during deadcode if
   254  	// field tracking is enabled. Reachparent[K] contains the index of
   255  	// the symbol that triggered the marking of symbol K as live.
   256  	Reachparent []Sym
   257  
   258  	// CgoExports records cgo-exported symbols by SymName.
   259  	CgoExports map[string]Sym
   260  
   261  	flags uint32
   262  
   263  	strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
   264  
   265  	errorReporter *ErrorReporter
   266  
   267  	npkgsyms    int // number of package symbols, for accounting
   268  	nhashedsyms int // number of hashed symbols, for accounting
   269  }
   270  
   271  const (
   272  	pkgDef = iota
   273  	hashed64Def
   274  	hashedDef
   275  	nonPkgDef
   276  	nonPkgRef
   277  )
   278  
   279  // objidx
   280  const (
   281  	nilObj = iota
   282  	extObj
   283  	goObjStart
   284  )
   285  
   286  // extSymPayload holds the payload (data + relocations) for linker-synthesized
   287  // external symbols (note that symbol value is stored in a separate slice).
   288  type extSymPayload struct {
   289  	name   string // TODO: would this be better as offset into str table?
   290  	size   int64
   291  	ver    int
   292  	kind   sym.SymKind
   293  	objidx uint32 // index of original object if sym made by cloneToExternal
   294  	relocs []goobj.Reloc
   295  	data   []byte
   296  	auxs   []goobj.Aux
   297  }
   298  
   299  const (
   300  	// Loader.flags
   301  	FlagStrictDups = 1 << iota
   302  )
   303  
   304  func NewLoader(flags uint32, reporter *ErrorReporter) *Loader {
   305  	nbuiltin := goobj.NBuiltin()
   306  	extReader := &oReader{objidx: extObj}
   307  	ldr := &Loader{
   308  		start:                make(map[*oReader]Sym),
   309  		objs:                 []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
   310  		objSyms:              make([]objSym, 1, 1),         // This will get overwritten later.
   311  		extReader:            extReader,
   312  		symsByName:           [2]map[string]Sym{make(map[string]Sym, 80000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
   313  		objByPkg:             make(map[string]uint32),
   314  		sub:                  make(map[Sym]Sym),
   315  		dynimplib:            make(map[Sym]string),
   316  		dynimpvers:           make(map[Sym]string),
   317  		localentry:           make(map[Sym]uint8),
   318  		extname:              make(map[Sym]string),
   319  		attrReadOnly:         make(map[Sym]bool),
   320  		elfType:              make(map[Sym]elf.SymType),
   321  		elfSym:               make(map[Sym]int32),
   322  		localElfSym:          make(map[Sym]int32),
   323  		symPkg:               make(map[Sym]string),
   324  		plt:                  make(map[Sym]int32),
   325  		got:                  make(map[Sym]int32),
   326  		dynid:                make(map[Sym]int32),
   327  		attrCgoExportDynamic: make(map[Sym]struct{}),
   328  		attrCgoExportStatic:  make(map[Sym]struct{}),
   329  		deferReturnTramp:     make(map[Sym]bool),
   330  		extStaticSyms:        make(map[nameVer]Sym),
   331  		builtinSyms:          make([]Sym, nbuiltin),
   332  		flags:                flags,
   333  		errorReporter:        reporter,
   334  		sects:                []*sym.Section{nil}, // reserve index 0 for nil section
   335  	}
   336  	reporter.ldr = ldr
   337  	return ldr
   338  }
   339  
   340  // Add object file r, return the start index.
   341  func (l *Loader) addObj(pkg string, r *oReader) Sym {
   342  	if _, ok := l.start[r]; ok {
   343  		panic("already added")
   344  	}
   345  	pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
   346  	if _, ok := l.objByPkg[pkg]; !ok {
   347  		l.objByPkg[pkg] = r.objidx
   348  	}
   349  	i := Sym(len(l.objSyms))
   350  	l.start[r] = i
   351  	l.objs = append(l.objs, objIdx{r, i})
   352  	return i
   353  }
   354  
   355  // Add a symbol from an object file, return the global index.
   356  // If the symbol already exist, it returns the index of that symbol.
   357  func (st *loadState) addSym(name string, ver int, r *oReader, li uint32, kind int, osym *goobj.Sym) Sym {
   358  	l := st.l
   359  	if l.extStart != 0 {
   360  		panic("addSym called after external symbol is created")
   361  	}
   362  	i := Sym(len(l.objSyms))
   363  	if int(i) != len(l.objSyms) { // overflow
   364  		panic("too many symbols")
   365  	}
   366  	addToGlobal := func() {
   367  		l.objSyms = append(l.objSyms, objSym{r.objidx, li})
   368  	}
   369  	if name == "" && kind != hashed64Def && kind != hashedDef {
   370  		addToGlobal()
   371  		return i // unnamed aux symbol
   372  	}
   373  	if ver == r.version {
   374  		// Static symbol. Add its global index but don't
   375  		// add to name lookup table, as it cannot be
   376  		// referenced by name.
   377  		addToGlobal()
   378  		return i
   379  	}
   380  	switch kind {
   381  	case pkgDef:
   382  		// Defined package symbols cannot be dup to each other.
   383  		// We load all the package symbols first, so we don't need
   384  		// to check dup here.
   385  		// We still add it to the lookup table, as it may still be
   386  		// referenced by name (e.g. through linkname).
   387  		l.symsByName[ver][name] = i
   388  		addToGlobal()
   389  		return i
   390  	case hashed64Def, hashedDef:
   391  		// Hashed (content-addressable) symbol. Check the hash
   392  		// but don't add to name lookup table, as they are not
   393  		// referenced by name. Also no need to do overwriting
   394  		// check, as same hash indicates same content.
   395  		var checkHash func() (symAndSize, bool)
   396  		var addToHashMap func(symAndSize)
   397  		var h64 uint64        // only used for hashed64Def
   398  		var h *goobj.HashType // only used for hashedDef
   399  		if kind == hashed64Def {
   400  			checkHash = func() (symAndSize, bool) {
   401  				h64 = r.Hash64(li - uint32(r.ndef))
   402  				s, existed := st.hashed64Syms[h64]
   403  				return s, existed
   404  			}
   405  			addToHashMap = func(ss symAndSize) { st.hashed64Syms[h64] = ss }
   406  		} else {
   407  			checkHash = func() (symAndSize, bool) {
   408  				h = r.Hash(li - uint32(r.ndef+r.nhashed64def))
   409  				s, existed := st.hashedSyms[*h]
   410  				return s, existed
   411  			}
   412  			addToHashMap = func(ss symAndSize) { st.hashedSyms[*h] = ss }
   413  		}
   414  		siz := osym.Siz()
   415  		if s, existed := checkHash(); existed {
   416  			// The content hash is built from symbol data and relocations. In the
   417  			// object file, the symbol data may not always contain trailing zeros,
   418  			// e.g. for [5]int{1,2,3} and [100]int{1,2,3}, the data is same
   419  			// (although the size is different).
   420  			// Also, for short symbols, the content hash is the identity function of
   421  			// the 8 bytes, and trailing zeros doesn't change the hash value, e.g.
   422  			// hash("A") == hash("A\0\0\0").
   423  			// So when two symbols have the same hash, we need to use the one with
   424  			// larger size.
   425  			if siz > s.size {
   426  				// New symbol has larger size, use the new one. Rewrite the index mapping.
   427  				l.objSyms[s.sym] = objSym{r.objidx, li}
   428  				addToHashMap(symAndSize{s.sym, siz})
   429  			}
   430  			return s.sym
   431  		}
   432  		addToHashMap(symAndSize{i, siz})
   433  		addToGlobal()
   434  		return i
   435  	}
   436  
   437  	// Non-package (named) symbol. Check if it already exists.
   438  	oldi, existed := l.symsByName[ver][name]
   439  	if !existed {
   440  		l.symsByName[ver][name] = i
   441  		addToGlobal()
   442  		return i
   443  	}
   444  	// symbol already exists
   445  	if osym.Dupok() {
   446  		if l.flags&FlagStrictDups != 0 {
   447  			l.checkdup(name, r, li, oldi)
   448  		}
   449  		// Fix for issue #47185 -- given two dupok symbols with
   450  		// different sizes, favor symbol with larger size. See
   451  		// also issue #46653.
   452  		szdup := l.SymSize(oldi)
   453  		sz := int64(r.Sym(li).Siz())
   454  		if szdup < sz {
   455  			// new symbol overwrites old symbol.
   456  			l.objSyms[oldi] = objSym{r.objidx, li}
   457  		}
   458  		return oldi
   459  	}
   460  	oldr, oldli := l.toLocal(oldi)
   461  	oldsym := oldr.Sym(oldli)
   462  	if oldsym.Dupok() {
   463  		return oldi
   464  	}
   465  	overwrite := r.DataSize(li) != 0
   466  	if overwrite {
   467  		// new symbol overwrites old symbol.
   468  		oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
   469  		if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
   470  			log.Fatalf("duplicated definition of symbol %s, from %s and %s", name, r.unit.Lib.Pkg, oldr.unit.Lib.Pkg)
   471  		}
   472  		l.objSyms[oldi] = objSym{r.objidx, li}
   473  	} else {
   474  		// old symbol overwrites new symbol.
   475  		typ := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
   476  		if !typ.IsData() { // only allow overwriting data symbol
   477  			log.Fatalf("duplicated definition of symbol %s, from %s and %s", name, r.unit.Lib.Pkg, oldr.unit.Lib.Pkg)
   478  		}
   479  	}
   480  	return oldi
   481  }
   482  
   483  // newExtSym creates a new external sym with the specified
   484  // name/version.
   485  func (l *Loader) newExtSym(name string, ver int) Sym {
   486  	i := Sym(len(l.objSyms))
   487  	if int(i) != len(l.objSyms) { // overflow
   488  		panic("too many symbols")
   489  	}
   490  	if l.extStart == 0 {
   491  		l.extStart = i
   492  	}
   493  	l.growValues(int(i) + 1)
   494  	l.growOuter(int(i) + 1)
   495  	l.growAttrBitmaps(int(i) + 1)
   496  	pi := l.newPayload(name, ver)
   497  	l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
   498  	l.extReader.syms = append(l.extReader.syms, i)
   499  	return i
   500  }
   501  
   502  // LookupOrCreateSym looks up the symbol with the specified name/version,
   503  // returning its Sym index if found. If the lookup fails, a new external
   504  // Sym will be created, entered into the lookup tables, and returned.
   505  func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
   506  	i := l.Lookup(name, ver)
   507  	if i != 0 {
   508  		return i
   509  	}
   510  	i = l.newExtSym(name, ver)
   511  	static := ver >= sym.SymVerStatic || ver < 0
   512  	if static {
   513  		l.extStaticSyms[nameVer{name, ver}] = i
   514  	} else {
   515  		l.symsByName[ver][name] = i
   516  	}
   517  	return i
   518  }
   519  
   520  // AddCgoExport records a cgo-exported symbol in l.CgoExports.
   521  // This table is used to identify the correct Go symbol ABI to use
   522  // to resolve references from host objects (which don't have ABIs).
   523  func (l *Loader) AddCgoExport(s Sym) {
   524  	if l.CgoExports == nil {
   525  		l.CgoExports = make(map[string]Sym)
   526  	}
   527  	l.CgoExports[l.SymName(s)] = s
   528  }
   529  
   530  // LookupOrCreateCgoExport is like LookupOrCreateSym, but if ver
   531  // indicates a global symbol, it uses the CgoExport table to determine
   532  // the appropriate symbol version (ABI) to use. ver must be either 0
   533  // or a static symbol version.
   534  func (l *Loader) LookupOrCreateCgoExport(name string, ver int) Sym {
   535  	if ver >= sym.SymVerStatic {
   536  		return l.LookupOrCreateSym(name, ver)
   537  	}
   538  	if ver != 0 {
   539  		panic("ver must be 0 or a static version")
   540  	}
   541  	// Look for a cgo-exported symbol from Go.
   542  	if s, ok := l.CgoExports[name]; ok {
   543  		return s
   544  	}
   545  	// Otherwise, this must just be a symbol in the host object.
   546  	// Create a version 0 symbol for it.
   547  	return l.LookupOrCreateSym(name, 0)
   548  }
   549  
   550  func (l *Loader) IsExternal(i Sym) bool {
   551  	r, _ := l.toLocal(i)
   552  	return l.isExtReader(r)
   553  }
   554  
   555  func (l *Loader) isExtReader(r *oReader) bool {
   556  	return r == l.extReader
   557  }
   558  
   559  // For external symbol, return its index in the payloads array.
   560  // XXX result is actually not a global index. We (ab)use the Sym type
   561  // so we don't need conversion for accessing bitmaps.
   562  func (l *Loader) extIndex(i Sym) Sym {
   563  	_, li := l.toLocal(i)
   564  	return Sym(li)
   565  }
   566  
   567  // Get a new payload for external symbol, return its index in
   568  // the payloads array.
   569  func (l *Loader) newPayload(name string, ver int) int {
   570  	pi := len(l.payloads)
   571  	pp := l.allocPayload()
   572  	pp.name = name
   573  	pp.ver = ver
   574  	l.payloads = append(l.payloads, pp)
   575  	l.growExtAttrBitmaps()
   576  	return pi
   577  }
   578  
   579  // getPayload returns a pointer to the extSymPayload struct for an
   580  // external symbol if the symbol has a payload. Will panic if the
   581  // symbol in question is bogus (zero or not an external sym).
   582  func (l *Loader) getPayload(i Sym) *extSymPayload {
   583  	if !l.IsExternal(i) {
   584  		panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
   585  	}
   586  	pi := l.extIndex(i)
   587  	return l.payloads[pi]
   588  }
   589  
   590  // allocPayload allocates a new payload.
   591  func (l *Loader) allocPayload() *extSymPayload {
   592  	batch := l.payloadBatch
   593  	if len(batch) == 0 {
   594  		batch = make([]extSymPayload, 1000)
   595  	}
   596  	p := &batch[0]
   597  	l.payloadBatch = batch[1:]
   598  	return p
   599  }
   600  
   601  func (ms *extSymPayload) Grow(siz int64) {
   602  	if int64(int(siz)) != siz {
   603  		log.Fatalf("symgrow size %d too long", siz)
   604  	}
   605  	if int64(len(ms.data)) >= siz {
   606  		return
   607  	}
   608  	if cap(ms.data) < int(siz) {
   609  		cl := len(ms.data)
   610  		ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
   611  		ms.data = ms.data[0:cl]
   612  	}
   613  	ms.data = ms.data[:siz]
   614  }
   615  
   616  // Convert a local index to a global index.
   617  func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
   618  	return r.syms[i]
   619  }
   620  
   621  // Convert a global index to a local index.
   622  func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
   623  	return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
   624  }
   625  
   626  // Resolve a local symbol reference. Return global index.
   627  func (l *Loader) resolve(r *oReader, s goobj.SymRef) Sym {
   628  	var rr *oReader
   629  	switch p := s.PkgIdx; p {
   630  	case goobj.PkgIdxInvalid:
   631  		// {0, X} with non-zero X is never a valid sym reference from a Go object.
   632  		// We steal this space for symbol references from external objects.
   633  		// In this case, X is just the global index.
   634  		if l.isExtReader(r) {
   635  			return Sym(s.SymIdx)
   636  		}
   637  		if s.SymIdx != 0 {
   638  			panic("bad sym ref")
   639  		}
   640  		return 0
   641  	case goobj.PkgIdxHashed64:
   642  		i := int(s.SymIdx) + r.ndef
   643  		return r.syms[i]
   644  	case goobj.PkgIdxHashed:
   645  		i := int(s.SymIdx) + r.ndef + r.nhashed64def
   646  		return r.syms[i]
   647  	case goobj.PkgIdxNone:
   648  		i := int(s.SymIdx) + r.ndef + r.nhashed64def + r.nhasheddef
   649  		return r.syms[i]
   650  	case goobj.PkgIdxBuiltin:
   651  		if bi := l.builtinSyms[s.SymIdx]; bi != 0 {
   652  			return bi
   653  		}
   654  		l.reportMissingBuiltin(int(s.SymIdx), r.unit.Lib.Pkg)
   655  		return 0
   656  	case goobj.PkgIdxSelf:
   657  		rr = r
   658  	default:
   659  		rr = l.objs[r.pkg[p]].r
   660  	}
   661  	return l.toGlobal(rr, s.SymIdx)
   662  }
   663  
   664  // reportMissingBuiltin issues an error in the case where we have a
   665  // relocation against a runtime builtin whose definition is not found
   666  // when the runtime package is built. The canonical example is
   667  // "runtime.racefuncenter" -- currently if you do something like
   668  //
   669  //	go build -gcflags=-race myprogram.go
   670  //
   671  // the compiler will insert calls to the builtin runtime.racefuncenter,
   672  // but the version of the runtime used for linkage won't actually contain
   673  // definitions of that symbol. See issue #42396 for details.
   674  //
   675  // As currently implemented, this is a fatal error. This has drawbacks
   676  // in that if there are multiple missing builtins, the error will only
   677  // cite the first one. On the plus side, terminating the link here has
   678  // advantages in that we won't run the risk of panics or crashes later
   679  // on in the linker due to R_CALL relocations with 0-valued target
   680  // symbols.
   681  func (l *Loader) reportMissingBuiltin(bsym int, reflib string) {
   682  	bname, _ := goobj.BuiltinName(bsym)
   683  	log.Fatalf("reference to undefined builtin %q from package %q",
   684  		bname, reflib)
   685  }
   686  
   687  // Look up a symbol by name, return global index, or 0 if not found.
   688  // This is more like Syms.ROLookup than Lookup -- it doesn't create
   689  // new symbol.
   690  func (l *Loader) Lookup(name string, ver int) Sym {
   691  	if ver >= sym.SymVerStatic || ver < 0 {
   692  		return l.extStaticSyms[nameVer{name, ver}]
   693  	}
   694  	return l.symsByName[ver][name]
   695  }
   696  
   697  // Check that duplicate symbols have same contents.
   698  func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
   699  	p := r.Data(li)
   700  	rdup, ldup := l.toLocal(dup)
   701  	pdup := rdup.Data(ldup)
   702  	reason := "same length but different contents"
   703  	if len(p) != len(pdup) {
   704  		reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
   705  	} else if bytes.Equal(p, pdup) {
   706  		// For BSS symbols, we need to check size as well, see issue 46653.
   707  		szdup := l.SymSize(dup)
   708  		sz := int64(r.Sym(li).Siz())
   709  		if szdup == sz {
   710  			return
   711  		}
   712  		reason = fmt.Sprintf("different sizes: new size %d != old size %d",
   713  			sz, szdup)
   714  	}
   715  	fmt.Fprintf(os.Stderr, "cmd/link: while reading object for '%v': duplicate symbol '%s', previous def at '%v', with mismatched payload: %s\n", r.unit.Lib, name, rdup.unit.Lib, reason)
   716  
   717  	// For the moment, allow DWARF subprogram DIEs for
   718  	// auto-generated wrapper functions. What seems to happen
   719  	// here is that we get different line numbers on formal
   720  	// params; I am guessing that the pos is being inherited
   721  	// from the spot where the wrapper is needed.
   722  	allowed := strings.HasPrefix(name, "go:info.go.interface") ||
   723  		strings.HasPrefix(name, "go:info.go.builtin") ||
   724  		strings.HasPrefix(name, "go:debuglines")
   725  	if !allowed {
   726  		l.strictDupMsgs++
   727  	}
   728  }
   729  
   730  func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
   731  
   732  // Number of total symbols.
   733  func (l *Loader) NSym() int {
   734  	return len(l.objSyms)
   735  }
   736  
   737  // Number of defined Go symbols.
   738  func (l *Loader) NDef() int {
   739  	return int(l.extStart)
   740  }
   741  
   742  // Number of reachable symbols.
   743  func (l *Loader) NReachableSym() int {
   744  	return l.attrReachable.Count()
   745  }
   746  
   747  // Returns the name of the i-th symbol.
   748  func (l *Loader) SymName(i Sym) string {
   749  	if l.IsExternal(i) {
   750  		pp := l.getPayload(i)
   751  		return pp.name
   752  	}
   753  	r, li := l.toLocal(i)
   754  	if r == nil {
   755  		return "?"
   756  	}
   757  	return r.Sym(li).Name(r.Reader)
   758  }
   759  
   760  // Returns the version of the i-th symbol.
   761  func (l *Loader) SymVersion(i Sym) int {
   762  	if l.IsExternal(i) {
   763  		pp := l.getPayload(i)
   764  		return pp.ver
   765  	}
   766  	r, li := l.toLocal(i)
   767  	return int(abiToVer(r.Sym(li).ABI(), r.version))
   768  }
   769  
   770  func (l *Loader) IsFileLocal(i Sym) bool {
   771  	return l.SymVersion(i) >= sym.SymVerStatic
   772  }
   773  
   774  // IsFromAssembly returns true if this symbol is derived from an
   775  // object file generated by the Go assembler.
   776  func (l *Loader) IsFromAssembly(i Sym) bool {
   777  	if l.IsExternal(i) {
   778  		return false
   779  	}
   780  	r, _ := l.toLocal(i)
   781  	return r.FromAssembly()
   782  }
   783  
   784  // Returns the type of the i-th symbol.
   785  func (l *Loader) SymType(i Sym) sym.SymKind {
   786  	if l.IsExternal(i) {
   787  		pp := l.getPayload(i)
   788  		if pp != nil {
   789  			return pp.kind
   790  		}
   791  		return 0
   792  	}
   793  	r, li := l.toLocal(i)
   794  	return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
   795  }
   796  
   797  // Returns the attributes of the i-th symbol.
   798  func (l *Loader) SymAttr(i Sym) uint8 {
   799  	if l.IsExternal(i) {
   800  		// TODO: do something? External symbols have different representation of attributes.
   801  		// For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
   802  		// set by external symbol.
   803  		return 0
   804  	}
   805  	r, li := l.toLocal(i)
   806  	return r.Sym(li).Flag()
   807  }
   808  
   809  // Returns the size of the i-th symbol.
   810  func (l *Loader) SymSize(i Sym) int64 {
   811  	if l.IsExternal(i) {
   812  		pp := l.getPayload(i)
   813  		return pp.size
   814  	}
   815  	r, li := l.toLocal(i)
   816  	return int64(r.Sym(li).Siz())
   817  }
   818  
   819  // AttrReachable returns true for symbols that are transitively
   820  // referenced from the entry points. Unreachable symbols are not
   821  // written to the output.
   822  func (l *Loader) AttrReachable(i Sym) bool {
   823  	return l.attrReachable.Has(i)
   824  }
   825  
   826  // SetAttrReachable sets the reachability property for a symbol (see
   827  // AttrReachable).
   828  func (l *Loader) SetAttrReachable(i Sym, v bool) {
   829  	if v {
   830  		l.attrReachable.Set(i)
   831  	} else {
   832  		l.attrReachable.Unset(i)
   833  	}
   834  }
   835  
   836  // AttrOnList returns true for symbols that are on some list (such as
   837  // the list of all text symbols, or one of the lists of data symbols)
   838  // and is consulted to avoid bugs where a symbol is put on a list
   839  // twice.
   840  func (l *Loader) AttrOnList(i Sym) bool {
   841  	return l.attrOnList.Has(i)
   842  }
   843  
   844  // SetAttrOnList sets the "on list" property for a symbol (see
   845  // AttrOnList).
   846  func (l *Loader) SetAttrOnList(i Sym, v bool) {
   847  	if v {
   848  		l.attrOnList.Set(i)
   849  	} else {
   850  		l.attrOnList.Unset(i)
   851  	}
   852  }
   853  
   854  // AttrLocal returns true for symbols that are only visible within the
   855  // module (executable or shared library) being linked. This attribute
   856  // is applied to thunks and certain other linker-generated symbols.
   857  func (l *Loader) AttrLocal(i Sym) bool {
   858  	return l.attrLocal.Has(i)
   859  }
   860  
   861  // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
   862  func (l *Loader) SetAttrLocal(i Sym, v bool) {
   863  	if v {
   864  		l.attrLocal.Set(i)
   865  	} else {
   866  		l.attrLocal.Unset(i)
   867  	}
   868  }
   869  
   870  // AttrUsedInIface returns true for a type symbol that is used in
   871  // an interface.
   872  func (l *Loader) AttrUsedInIface(i Sym) bool {
   873  	return l.attrUsedInIface.Has(i)
   874  }
   875  
   876  func (l *Loader) SetAttrUsedInIface(i Sym, v bool) {
   877  	if v {
   878  		l.attrUsedInIface.Set(i)
   879  	} else {
   880  		l.attrUsedInIface.Unset(i)
   881  	}
   882  }
   883  
   884  // SymAddr checks that a symbol is reachable, and returns its value.
   885  func (l *Loader) SymAddr(i Sym) int64 {
   886  	if !l.AttrReachable(i) {
   887  		panic("unreachable symbol in symaddr")
   888  	}
   889  	return l.values[i]
   890  }
   891  
   892  // AttrNotInSymbolTable returns true for symbols that should not be
   893  // added to the symbol table of the final generated load module.
   894  func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
   895  	return l.attrNotInSymbolTable.Has(i)
   896  }
   897  
   898  // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
   899  // (see AttrNotInSymbolTable above).
   900  func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
   901  	if v {
   902  		l.attrNotInSymbolTable.Set(i)
   903  	} else {
   904  		l.attrNotInSymbolTable.Unset(i)
   905  	}
   906  }
   907  
   908  // AttrVisibilityHidden symbols returns true for ELF symbols with
   909  // visibility set to STV_HIDDEN. They become local symbols in
   910  // the final executable. Only relevant when internally linking
   911  // on an ELF platform.
   912  func (l *Loader) AttrVisibilityHidden(i Sym) bool {
   913  	if !l.IsExternal(i) {
   914  		return false
   915  	}
   916  	return l.attrVisibilityHidden.Has(l.extIndex(i))
   917  }
   918  
   919  // SetAttrVisibilityHidden sets the "hidden visibility" property for a
   920  // symbol (see AttrVisibilityHidden).
   921  func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
   922  	if !l.IsExternal(i) {
   923  		panic("tried to set visibility attr on non-external symbol")
   924  	}
   925  	if v {
   926  		l.attrVisibilityHidden.Set(l.extIndex(i))
   927  	} else {
   928  		l.attrVisibilityHidden.Unset(l.extIndex(i))
   929  	}
   930  }
   931  
   932  // AttrDuplicateOK returns true for a symbol that can be present in
   933  // multiple object files.
   934  func (l *Loader) AttrDuplicateOK(i Sym) bool {
   935  	if !l.IsExternal(i) {
   936  		// TODO: if this path winds up being taken frequently, it
   937  		// might make more sense to copy the flag value out of the object
   938  		// into a larger bitmap during preload.
   939  		r, li := l.toLocal(i)
   940  		return r.Sym(li).Dupok()
   941  	}
   942  	return l.attrDuplicateOK.Has(l.extIndex(i))
   943  }
   944  
   945  // SetAttrDuplicateOK sets the "duplicate OK" property for an external
   946  // symbol (see AttrDuplicateOK).
   947  func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
   948  	if !l.IsExternal(i) {
   949  		panic("tried to set dupok attr on non-external symbol")
   950  	}
   951  	if v {
   952  		l.attrDuplicateOK.Set(l.extIndex(i))
   953  	} else {
   954  		l.attrDuplicateOK.Unset(l.extIndex(i))
   955  	}
   956  }
   957  
   958  // AttrShared returns true for symbols compiled with the -shared option.
   959  func (l *Loader) AttrShared(i Sym) bool {
   960  	if !l.IsExternal(i) {
   961  		// TODO: if this path winds up being taken frequently, it
   962  		// might make more sense to copy the flag value out of the
   963  		// object into a larger bitmap during preload.
   964  		r, _ := l.toLocal(i)
   965  		return r.Shared()
   966  	}
   967  	return l.attrShared.Has(l.extIndex(i))
   968  }
   969  
   970  // SetAttrShared sets the "shared" property for an external
   971  // symbol (see AttrShared).
   972  func (l *Loader) SetAttrShared(i Sym, v bool) {
   973  	if !l.IsExternal(i) {
   974  		panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
   975  	}
   976  	if v {
   977  		l.attrShared.Set(l.extIndex(i))
   978  	} else {
   979  		l.attrShared.Unset(l.extIndex(i))
   980  	}
   981  }
   982  
   983  // AttrExternal returns true for function symbols loaded from host
   984  // object files.
   985  func (l *Loader) AttrExternal(i Sym) bool {
   986  	if !l.IsExternal(i) {
   987  		return false
   988  	}
   989  	return l.attrExternal.Has(l.extIndex(i))
   990  }
   991  
   992  // SetAttrExternal sets the "external" property for a host object
   993  // symbol (see AttrExternal).
   994  func (l *Loader) SetAttrExternal(i Sym, v bool) {
   995  	if !l.IsExternal(i) {
   996  		panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.SymName(i)))
   997  	}
   998  	if v {
   999  		l.attrExternal.Set(l.extIndex(i))
  1000  	} else {
  1001  		l.attrExternal.Unset(l.extIndex(i))
  1002  	}
  1003  }
  1004  
  1005  // AttrSpecial returns true for a symbols that do not have their
  1006  // address (i.e. Value) computed by the usual mechanism of
  1007  // data.go:dodata() & data.go:address().
  1008  func (l *Loader) AttrSpecial(i Sym) bool {
  1009  	return l.attrSpecial.Has(i)
  1010  }
  1011  
  1012  // SetAttrSpecial sets the "special" property for a symbol (see
  1013  // AttrSpecial).
  1014  func (l *Loader) SetAttrSpecial(i Sym, v bool) {
  1015  	if v {
  1016  		l.attrSpecial.Set(i)
  1017  	} else {
  1018  		l.attrSpecial.Unset(i)
  1019  	}
  1020  }
  1021  
  1022  // AttrCgoExportDynamic returns true for a symbol that has been
  1023  // specially marked via the "cgo_export_dynamic" compiler directive
  1024  // written by cgo (in response to //export directives in the source).
  1025  func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
  1026  	_, ok := l.attrCgoExportDynamic[i]
  1027  	return ok
  1028  }
  1029  
  1030  // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
  1031  // (see AttrCgoExportDynamic).
  1032  func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
  1033  	if v {
  1034  		l.attrCgoExportDynamic[i] = struct{}{}
  1035  	} else {
  1036  		delete(l.attrCgoExportDynamic, i)
  1037  	}
  1038  }
  1039  
  1040  // ForAllCgoExportDynamic calls f for every symbol that has been
  1041  // marked with the "cgo_export_dynamic" compiler directive.
  1042  func (l *Loader) ForAllCgoExportDynamic(f func(Sym)) {
  1043  	for s := range l.attrCgoExportDynamic {
  1044  		f(s)
  1045  	}
  1046  }
  1047  
  1048  // AttrCgoExportStatic returns true for a symbol that has been
  1049  // specially marked via the "cgo_export_static" directive
  1050  // written by cgo.
  1051  func (l *Loader) AttrCgoExportStatic(i Sym) bool {
  1052  	_, ok := l.attrCgoExportStatic[i]
  1053  	return ok
  1054  }
  1055  
  1056  // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
  1057  // (see AttrCgoExportStatic).
  1058  func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
  1059  	if v {
  1060  		l.attrCgoExportStatic[i] = struct{}{}
  1061  	} else {
  1062  		delete(l.attrCgoExportStatic, i)
  1063  	}
  1064  }
  1065  
  1066  // IsGeneratedSym returns true if a symbol's been previously marked as a
  1067  // generator symbol through the SetIsGeneratedSym. The functions for generator
  1068  // symbols are kept in the Link context.
  1069  func (l *Loader) IsGeneratedSym(i Sym) bool {
  1070  	if !l.IsExternal(i) {
  1071  		return false
  1072  	}
  1073  	return l.generatedSyms.Has(l.extIndex(i))
  1074  }
  1075  
  1076  // SetIsGeneratedSym marks symbols as generated symbols. Data shouldn't be
  1077  // stored in generated symbols, and a function is registered and called for
  1078  // each of these symbols.
  1079  func (l *Loader) SetIsGeneratedSym(i Sym, v bool) {
  1080  	if !l.IsExternal(i) {
  1081  		panic("only external symbols can be generated")
  1082  	}
  1083  	if v {
  1084  		l.generatedSyms.Set(l.extIndex(i))
  1085  	} else {
  1086  		l.generatedSyms.Unset(l.extIndex(i))
  1087  	}
  1088  }
  1089  
  1090  func (l *Loader) AttrCgoExport(i Sym) bool {
  1091  	return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
  1092  }
  1093  
  1094  // AttrReadOnly returns true for a symbol whose underlying data
  1095  // is stored via a read-only mmap.
  1096  func (l *Loader) AttrReadOnly(i Sym) bool {
  1097  	if v, ok := l.attrReadOnly[i]; ok {
  1098  		return v
  1099  	}
  1100  	if l.IsExternal(i) {
  1101  		pp := l.getPayload(i)
  1102  		if pp.objidx != 0 {
  1103  			return l.objs[pp.objidx].r.ReadOnly()
  1104  		}
  1105  		return false
  1106  	}
  1107  	r, _ := l.toLocal(i)
  1108  	return r.ReadOnly()
  1109  }
  1110  
  1111  // SetAttrReadOnly sets the "data is read only" property for a symbol
  1112  // (see AttrReadOnly).
  1113  func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
  1114  	l.attrReadOnly[i] = v
  1115  }
  1116  
  1117  // AttrSubSymbol returns true for symbols that are listed as a
  1118  // sub-symbol of some other outer symbol. The sub/outer mechanism is
  1119  // used when loading host objects (sections from the host object
  1120  // become regular linker symbols and symbols go on the Sub list of
  1121  // their section) and for constructing the global offset table when
  1122  // internally linking a dynamic executable.
  1123  //
  1124  // Note that in later stages of the linker, we set Outer(S) to some
  1125  // container symbol C, but don't set Sub(C). Thus we have two
  1126  // distinct scenarios:
  1127  //
  1128  // - Outer symbol covers the address ranges of its sub-symbols.
  1129  //   Outer.Sub is set in this case.
  1130  // - Outer symbol doesn't cover the address ranges. It is zero-sized
  1131  //   and doesn't have sub-symbols. In the case, the inner symbol is
  1132  //   not actually a "SubSymbol". (Tricky!)
  1133  //
  1134  // This method returns TRUE only for sub-symbols in the first scenario.
  1135  //
  1136  // FIXME: would be better to do away with this and have a better way
  1137  // to represent container symbols.
  1138  
  1139  func (l *Loader) AttrSubSymbol(i Sym) bool {
  1140  	// we don't explicitly store this attribute any more -- return
  1141  	// a value based on the sub-symbol setting.
  1142  	o := l.OuterSym(i)
  1143  	if o == 0 {
  1144  		return false
  1145  	}
  1146  	return l.SubSym(o) != 0
  1147  }
  1148  
  1149  // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
  1150  // clients should instead use the AddInteriorSym method to establish
  1151  // containment relationships for host object symbols.
  1152  
  1153  // Returns whether the i-th symbol has ReflectMethod attribute set.
  1154  func (l *Loader) IsReflectMethod(i Sym) bool {
  1155  	return l.SymAttr(i)&goobj.SymFlagReflectMethod != 0
  1156  }
  1157  
  1158  // Returns whether the i-th symbol is nosplit.
  1159  func (l *Loader) IsNoSplit(i Sym) bool {
  1160  	return l.SymAttr(i)&goobj.SymFlagNoSplit != 0
  1161  }
  1162  
  1163  // Returns whether this is a Go type symbol.
  1164  func (l *Loader) IsGoType(i Sym) bool {
  1165  	return l.SymAttr(i)&goobj.SymFlagGoType != 0
  1166  }
  1167  
  1168  // Returns whether this symbol should be included in typelink.
  1169  func (l *Loader) IsTypelink(i Sym) bool {
  1170  	return l.SymAttr(i)&goobj.SymFlagTypelink != 0
  1171  }
  1172  
  1173  // Returns whether this symbol is an itab symbol.
  1174  func (l *Loader) IsItab(i Sym) bool {
  1175  	if l.IsExternal(i) {
  1176  		return false
  1177  	}
  1178  	r, li := l.toLocal(i)
  1179  	return r.Sym(li).IsItab()
  1180  }
  1181  
  1182  // Returns whether this symbol is a dictionary symbol.
  1183  func (l *Loader) IsDict(i Sym) bool {
  1184  	if l.IsExternal(i) {
  1185  		return false
  1186  	}
  1187  	r, li := l.toLocal(i)
  1188  	return r.Sym(li).IsDict()
  1189  }
  1190  
  1191  // Returns whether this symbol is a compiler-generated package init func.
  1192  func (l *Loader) IsPkgInit(i Sym) bool {
  1193  	if l.IsExternal(i) {
  1194  		return false
  1195  	}
  1196  	r, li := l.toLocal(i)
  1197  	return r.Sym(li).IsPkgInit()
  1198  }
  1199  
  1200  // Return whether this is a trampoline of a deferreturn call.
  1201  func (l *Loader) IsDeferReturnTramp(i Sym) bool {
  1202  	return l.deferReturnTramp[i]
  1203  }
  1204  
  1205  // Set that i is a trampoline of a deferreturn call.
  1206  func (l *Loader) SetIsDeferReturnTramp(i Sym, v bool) {
  1207  	l.deferReturnTramp[i] = v
  1208  }
  1209  
  1210  // growValues grows the slice used to store symbol values.
  1211  func (l *Loader) growValues(reqLen int) {
  1212  	curLen := len(l.values)
  1213  	if reqLen > curLen {
  1214  		l.values = append(l.values, make([]int64, reqLen+1-curLen)...)
  1215  	}
  1216  }
  1217  
  1218  // SymValue returns the value of the i-th symbol. i is global index.
  1219  func (l *Loader) SymValue(i Sym) int64 {
  1220  	return l.values[i]
  1221  }
  1222  
  1223  // SetSymValue sets the value of the i-th symbol. i is global index.
  1224  func (l *Loader) SetSymValue(i Sym, val int64) {
  1225  	l.values[i] = val
  1226  }
  1227  
  1228  // AddToSymValue adds to the value of the i-th symbol. i is the global index.
  1229  func (l *Loader) AddToSymValue(i Sym, val int64) {
  1230  	l.values[i] += val
  1231  }
  1232  
  1233  // Returns the symbol content of the i-th symbol. i is global index.
  1234  func (l *Loader) Data(i Sym) []byte {
  1235  	if l.IsExternal(i) {
  1236  		pp := l.getPayload(i)
  1237  		if pp != nil {
  1238  			return pp.data
  1239  		}
  1240  		return nil
  1241  	}
  1242  	r, li := l.toLocal(i)
  1243  	return r.Data(li)
  1244  }
  1245  
  1246  // Returns the symbol content of the i-th symbol as a string. i is global index.
  1247  func (l *Loader) DataString(i Sym) string {
  1248  	if l.IsExternal(i) {
  1249  		pp := l.getPayload(i)
  1250  		return string(pp.data)
  1251  	}
  1252  	r, li := l.toLocal(i)
  1253  	return r.DataString(li)
  1254  }
  1255  
  1256  // FreeData clears the symbol data of an external symbol, allowing the memory
  1257  // to be freed earlier. No-op for non-external symbols.
  1258  // i is global index.
  1259  func (l *Loader) FreeData(i Sym) {
  1260  	if l.IsExternal(i) {
  1261  		pp := l.getPayload(i)
  1262  		if pp != nil {
  1263  			pp.data = nil
  1264  		}
  1265  	}
  1266  }
  1267  
  1268  // SymAlign returns the alignment for a symbol.
  1269  func (l *Loader) SymAlign(i Sym) int32 {
  1270  	if int(i) >= len(l.align) {
  1271  		// align is extended lazily -- it the sym in question is
  1272  		// outside the range of the existing slice, then we assume its
  1273  		// alignment has not yet been set.
  1274  		return 0
  1275  	}
  1276  	// TODO: would it make sense to return an arch-specific
  1277  	// alignment depending on section type? E.g. STEXT => 32,
  1278  	// SDATA => 1, etc?
  1279  	abits := l.align[i]
  1280  	if abits == 0 {
  1281  		return 0
  1282  	}
  1283  	return int32(1 << (abits - 1))
  1284  }
  1285  
  1286  // SetSymAlign sets the alignment for a symbol.
  1287  func (l *Loader) SetSymAlign(i Sym, align int32) {
  1288  	// Reject nonsense alignments.
  1289  	if align < 0 || align&(align-1) != 0 {
  1290  		panic("bad alignment value")
  1291  	}
  1292  	if int(i) >= len(l.align) {
  1293  		l.align = append(l.align, make([]uint8, l.NSym()-len(l.align))...)
  1294  	}
  1295  	if align == 0 {
  1296  		l.align[i] = 0
  1297  	}
  1298  	l.align[i] = uint8(bits.Len32(uint32(align)))
  1299  }
  1300  
  1301  // SymSect returns the section of the i-th symbol. i is global index.
  1302  func (l *Loader) SymSect(i Sym) *sym.Section {
  1303  	if int(i) >= len(l.symSects) {
  1304  		// symSects is extended lazily -- it the sym in question is
  1305  		// outside the range of the existing slice, then we assume its
  1306  		// section has not yet been set.
  1307  		return nil
  1308  	}
  1309  	return l.sects[l.symSects[i]]
  1310  }
  1311  
  1312  // SetSymSect sets the section of the i-th symbol. i is global index.
  1313  func (l *Loader) SetSymSect(i Sym, sect *sym.Section) {
  1314  	if int(i) >= len(l.symSects) {
  1315  		l.symSects = append(l.symSects, make([]uint16, l.NSym()-len(l.symSects))...)
  1316  	}
  1317  	l.symSects[i] = sect.Index
  1318  }
  1319  
  1320  // NewSection creates a new (output) section.
  1321  func (l *Loader) NewSection() *sym.Section {
  1322  	sect := new(sym.Section)
  1323  	idx := len(l.sects)
  1324  	if idx != int(uint16(idx)) {
  1325  		panic("too many sections created")
  1326  	}
  1327  	sect.Index = uint16(idx)
  1328  	l.sects = append(l.sects, sect)
  1329  	return sect
  1330  }
  1331  
  1332  // SymDynimplib returns the "dynimplib" attribute for the specified
  1333  // symbol, making up a portion of the info for a symbol specified
  1334  // on a "cgo_import_dynamic" compiler directive.
  1335  func (l *Loader) SymDynimplib(i Sym) string {
  1336  	return l.dynimplib[i]
  1337  }
  1338  
  1339  // SetSymDynimplib sets the "dynimplib" attribute for a symbol.
  1340  func (l *Loader) SetSymDynimplib(i Sym, value string) {
  1341  	// reject bad symbols
  1342  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1343  		panic("bad symbol index in SetDynimplib")
  1344  	}
  1345  	if value == "" {
  1346  		delete(l.dynimplib, i)
  1347  	} else {
  1348  		l.dynimplib[i] = value
  1349  	}
  1350  }
  1351  
  1352  // SymDynimpvers returns the "dynimpvers" attribute for the specified
  1353  // symbol, making up a portion of the info for a symbol specified
  1354  // on a "cgo_import_dynamic" compiler directive.
  1355  func (l *Loader) SymDynimpvers(i Sym) string {
  1356  	return l.dynimpvers[i]
  1357  }
  1358  
  1359  // SetSymDynimpvers sets the "dynimpvers" attribute for a symbol.
  1360  func (l *Loader) SetSymDynimpvers(i Sym, value string) {
  1361  	// reject bad symbols
  1362  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1363  		panic("bad symbol index in SetDynimpvers")
  1364  	}
  1365  	if value == "" {
  1366  		delete(l.dynimpvers, i)
  1367  	} else {
  1368  		l.dynimpvers[i] = value
  1369  	}
  1370  }
  1371  
  1372  // SymExtname returns the "extname" value for the specified
  1373  // symbol.
  1374  func (l *Loader) SymExtname(i Sym) string {
  1375  	if s, ok := l.extname[i]; ok {
  1376  		return s
  1377  	}
  1378  	return l.SymName(i)
  1379  }
  1380  
  1381  // SetSymExtname sets the  "extname" attribute for a symbol.
  1382  func (l *Loader) SetSymExtname(i Sym, value string) {
  1383  	// reject bad symbols
  1384  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1385  		panic("bad symbol index in SetExtname")
  1386  	}
  1387  	if value == "" {
  1388  		delete(l.extname, i)
  1389  	} else {
  1390  		l.extname[i] = value
  1391  	}
  1392  }
  1393  
  1394  // SymElfType returns the previously recorded ELF type for a symbol
  1395  // (used only for symbols read from shared libraries by ldshlibsyms).
  1396  // It is not set for symbols defined by the packages being linked or
  1397  // by symbols read by ldelf (and so is left as elf.STT_NOTYPE).
  1398  func (l *Loader) SymElfType(i Sym) elf.SymType {
  1399  	if et, ok := l.elfType[i]; ok {
  1400  		return et
  1401  	}
  1402  	return elf.STT_NOTYPE
  1403  }
  1404  
  1405  // SetSymElfType sets the elf type attribute for a symbol.
  1406  func (l *Loader) SetSymElfType(i Sym, et elf.SymType) {
  1407  	// reject bad symbols
  1408  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1409  		panic("bad symbol index in SetSymElfType")
  1410  	}
  1411  	if et == elf.STT_NOTYPE {
  1412  		delete(l.elfType, i)
  1413  	} else {
  1414  		l.elfType[i] = et
  1415  	}
  1416  }
  1417  
  1418  // SymElfSym returns the ELF symbol index for a given loader
  1419  // symbol, assigned during ELF symtab generation.
  1420  func (l *Loader) SymElfSym(i Sym) int32 {
  1421  	return l.elfSym[i]
  1422  }
  1423  
  1424  // SetSymElfSym sets the elf symbol index for a symbol.
  1425  func (l *Loader) SetSymElfSym(i Sym, es int32) {
  1426  	if i == 0 {
  1427  		panic("bad sym index")
  1428  	}
  1429  	if es == 0 {
  1430  		delete(l.elfSym, i)
  1431  	} else {
  1432  		l.elfSym[i] = es
  1433  	}
  1434  }
  1435  
  1436  // SymLocalElfSym returns the "local" ELF symbol index for a given loader
  1437  // symbol, assigned during ELF symtab generation.
  1438  func (l *Loader) SymLocalElfSym(i Sym) int32 {
  1439  	return l.localElfSym[i]
  1440  }
  1441  
  1442  // SetSymLocalElfSym sets the "local" elf symbol index for a symbol.
  1443  func (l *Loader) SetSymLocalElfSym(i Sym, es int32) {
  1444  	if i == 0 {
  1445  		panic("bad sym index")
  1446  	}
  1447  	if es == 0 {
  1448  		delete(l.localElfSym, i)
  1449  	} else {
  1450  		l.localElfSym[i] = es
  1451  	}
  1452  }
  1453  
  1454  // SymPlt returns the PLT offset of symbol s.
  1455  func (l *Loader) SymPlt(s Sym) int32 {
  1456  	if v, ok := l.plt[s]; ok {
  1457  		return v
  1458  	}
  1459  	return -1
  1460  }
  1461  
  1462  // SetPlt sets the PLT offset of symbol i.
  1463  func (l *Loader) SetPlt(i Sym, v int32) {
  1464  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1465  		panic("bad symbol for SetPlt")
  1466  	}
  1467  	if v == -1 {
  1468  		delete(l.plt, i)
  1469  	} else {
  1470  		l.plt[i] = v
  1471  	}
  1472  }
  1473  
  1474  // SymGot returns the GOT offset of symbol s.
  1475  func (l *Loader) SymGot(s Sym) int32 {
  1476  	if v, ok := l.got[s]; ok {
  1477  		return v
  1478  	}
  1479  	return -1
  1480  }
  1481  
  1482  // SetGot sets the GOT offset of symbol i.
  1483  func (l *Loader) SetGot(i Sym, v int32) {
  1484  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1485  		panic("bad symbol for SetGot")
  1486  	}
  1487  	if v == -1 {
  1488  		delete(l.got, i)
  1489  	} else {
  1490  		l.got[i] = v
  1491  	}
  1492  }
  1493  
  1494  // SymDynid returns the "dynid" property for the specified symbol.
  1495  func (l *Loader) SymDynid(i Sym) int32 {
  1496  	if s, ok := l.dynid[i]; ok {
  1497  		return s
  1498  	}
  1499  	return -1
  1500  }
  1501  
  1502  // SetSymDynid sets the "dynid" property for a symbol.
  1503  func (l *Loader) SetSymDynid(i Sym, val int32) {
  1504  	// reject bad symbols
  1505  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1506  		panic("bad symbol index in SetSymDynid")
  1507  	}
  1508  	if val == -1 {
  1509  		delete(l.dynid, i)
  1510  	} else {
  1511  		l.dynid[i] = val
  1512  	}
  1513  }
  1514  
  1515  // DynidSyms returns the set of symbols for which dynID is set to an
  1516  // interesting (non-default) value. This is expected to be a fairly
  1517  // small set.
  1518  func (l *Loader) DynidSyms() []Sym {
  1519  	sl := make([]Sym, 0, len(l.dynid))
  1520  	for s := range l.dynid {
  1521  		sl = append(sl, s)
  1522  	}
  1523  	sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
  1524  	return sl
  1525  }
  1526  
  1527  // SymGoType returns the 'Gotype' property for a given symbol (set by
  1528  // the Go compiler for variable symbols). This version relies on
  1529  // reading aux symbols for the target sym -- it could be that a faster
  1530  // approach would be to check for gotype during preload and copy the
  1531  // results in to a map (might want to try this at some point and see
  1532  // if it helps speed things up).
  1533  func (l *Loader) SymGoType(i Sym) Sym { return l.aux1(i, goobj.AuxGotype) }
  1534  
  1535  // SymUnit returns the compilation unit for a given symbol (which will
  1536  // typically be nil for external or linker-manufactured symbols).
  1537  func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
  1538  	if l.IsExternal(i) {
  1539  		pp := l.getPayload(i)
  1540  		if pp.objidx != 0 {
  1541  			r := l.objs[pp.objidx].r
  1542  			return r.unit
  1543  		}
  1544  		return nil
  1545  	}
  1546  	r, _ := l.toLocal(i)
  1547  	return r.unit
  1548  }
  1549  
  1550  // SymPkg returns the package where the symbol came from (for
  1551  // regular compiler-generated Go symbols), but in the case of
  1552  // building with "-linkshared" (when a symbol is read from a
  1553  // shared library), will hold the library name.
  1554  // NOTE: this corresponds to sym.Symbol.File field.
  1555  func (l *Loader) SymPkg(i Sym) string {
  1556  	if f, ok := l.symPkg[i]; ok {
  1557  		return f
  1558  	}
  1559  	if l.IsExternal(i) {
  1560  		pp := l.getPayload(i)
  1561  		if pp.objidx != 0 {
  1562  			r := l.objs[pp.objidx].r
  1563  			return r.unit.Lib.Pkg
  1564  		}
  1565  		return ""
  1566  	}
  1567  	r, _ := l.toLocal(i)
  1568  	return r.unit.Lib.Pkg
  1569  }
  1570  
  1571  // SetSymPkg sets the package/library for a symbol. This is
  1572  // needed mainly for external symbols, specifically those imported
  1573  // from shared libraries.
  1574  func (l *Loader) SetSymPkg(i Sym, pkg string) {
  1575  	// reject bad symbols
  1576  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1577  		panic("bad symbol index in SetSymPkg")
  1578  	}
  1579  	l.symPkg[i] = pkg
  1580  }
  1581  
  1582  // SymLocalentry returns an offset in bytes of the "local entry" of a symbol.
  1583  //
  1584  // On PPC64, a value of 1 indicates the symbol does not use or preserve a TOC
  1585  // pointer in R2, nor does it have a distinct local entry.
  1586  func (l *Loader) SymLocalentry(i Sym) uint8 {
  1587  	return l.localentry[i]
  1588  }
  1589  
  1590  // SetSymLocalentry sets the "local entry" offset attribute for a symbol.
  1591  func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
  1592  	// reject bad symbols
  1593  	if i >= Sym(len(l.objSyms)) || i == 0 {
  1594  		panic("bad symbol index in SetSymLocalentry")
  1595  	}
  1596  	if value == 0 {
  1597  		delete(l.localentry, i)
  1598  	} else {
  1599  		l.localentry[i] = value
  1600  	}
  1601  }
  1602  
  1603  // Returns the number of aux symbols given a global index.
  1604  func (l *Loader) NAux(i Sym) int {
  1605  	if l.IsExternal(i) {
  1606  		return 0
  1607  	}
  1608  	r, li := l.toLocal(i)
  1609  	return r.NAux(li)
  1610  }
  1611  
  1612  // Returns the "handle" to the j-th aux symbol of the i-th symbol.
  1613  func (l *Loader) Aux(i Sym, j int) Aux {
  1614  	if l.IsExternal(i) {
  1615  		return Aux{}
  1616  	}
  1617  	r, li := l.toLocal(i)
  1618  	if j >= r.NAux(li) {
  1619  		return Aux{}
  1620  	}
  1621  	return Aux{r.Aux(li, j), r, l}
  1622  }
  1623  
  1624  // WasmImportSym returns the auxiliary WebAssembly import symbol associated with
  1625  // a given function symbol. The aux sym only exists for Go function stubs that
  1626  // have been annotated with the //go:wasmimport directive.  The aux sym
  1627  // contains the information necessary for the linker to add a WebAssembly
  1628  // import statement.
  1629  // (https://webassembly.github.io/spec/core/syntax/modules.html#imports)
  1630  func (l *Loader) WasmImportSym(fnSymIdx Sym) (Sym, bool) {
  1631  	if l.SymType(fnSymIdx) != sym.STEXT {
  1632  		log.Fatalf("error: non-function sym %d/%s t=%s passed to WasmImportSym", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
  1633  	}
  1634  	r, li := l.toLocal(fnSymIdx)
  1635  	auxs := r.Auxs(li)
  1636  	for i := range auxs {
  1637  		a := &auxs[i]
  1638  		switch a.Type() {
  1639  		case goobj.AuxWasmImport:
  1640  			return l.resolve(r, a.Sym()), true
  1641  		}
  1642  	}
  1643  
  1644  	return 0, false
  1645  }
  1646  
  1647  // SEHUnwindSym returns the auxiliary SEH unwind symbol associated with
  1648  // a given function symbol.
  1649  func (l *Loader) SEHUnwindSym(fnSymIdx Sym) Sym {
  1650  	if l.SymType(fnSymIdx) != sym.STEXT {
  1651  		log.Fatalf("error: non-function sym %d/%s t=%s passed to SEHUnwindSym", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
  1652  	}
  1653  
  1654  	return l.aux1(fnSymIdx, goobj.AuxSehUnwindInfo)
  1655  }
  1656  
  1657  // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
  1658  // symbols associated with a given function symbol.  Prior to the
  1659  // introduction of the loader, this was done purely using name
  1660  // lookups, e.f. for function with name XYZ we would then look up
  1661  // go.info.XYZ, etc.
  1662  func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
  1663  	if l.SymType(fnSymIdx) != sym.STEXT {
  1664  		log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
  1665  	}
  1666  	r, auxs := l.auxs(fnSymIdx)
  1667  
  1668  	for i := range auxs {
  1669  		a := &auxs[i]
  1670  		switch a.Type() {
  1671  		case goobj.AuxDwarfInfo:
  1672  			auxDwarfInfo = l.resolve(r, a.Sym())
  1673  			if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
  1674  				panic("aux dwarf info sym with wrong type")
  1675  			}
  1676  		case goobj.AuxDwarfLoc:
  1677  			auxDwarfLoc = l.resolve(r, a.Sym())
  1678  			if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
  1679  				panic("aux dwarf loc sym with wrong type")
  1680  			}
  1681  		case goobj.AuxDwarfRanges:
  1682  			auxDwarfRanges = l.resolve(r, a.Sym())
  1683  			if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
  1684  				panic("aux dwarf ranges sym with wrong type")
  1685  			}
  1686  		case goobj.AuxDwarfLines:
  1687  			auxDwarfLines = l.resolve(r, a.Sym())
  1688  			if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
  1689  				panic("aux dwarf lines sym with wrong type")
  1690  			}
  1691  		}
  1692  	}
  1693  	return
  1694  }
  1695  
  1696  func (l *Loader) GetVarDwarfAuxSym(i Sym) Sym {
  1697  	aux := l.aux1(i, goobj.AuxDwarfInfo)
  1698  	if aux != 0 && l.SymType(aux) != sym.SDWARFVAR {
  1699  		fmt.Println(l.SymName(i), l.SymType(i), l.SymType(aux), sym.SDWARFVAR)
  1700  		panic("aux dwarf info sym with wrong type")
  1701  	}
  1702  	return aux
  1703  }
  1704  
  1705  // AddInteriorSym sets up 'interior' as an interior symbol of
  1706  // container/payload symbol 'container'. An interior symbol does not
  1707  // itself have data, but gives a name to a subrange of the data in its
  1708  // container symbol. The container itself may or may not have a name.
  1709  // This method is intended primarily for use in the host object
  1710  // loaders, to capture the semantics of symbols and sections in an
  1711  // object file. When reading a host object file, we'll typically
  1712  // encounter a static section symbol (ex: ".text") containing content
  1713  // for a collection of functions, then a series of ELF (or macho, etc)
  1714  // symbol table entries each of which points into a sub-section
  1715  // (offset and length) of its corresponding container symbol. Within
  1716  // the go linker we create a loader.Sym for the container (which is
  1717  // expected to have the actual content/payload) and then a set of
  1718  // interior loader.Sym's that point into a portion of the container.
  1719  func (l *Loader) AddInteriorSym(container Sym, interior Sym) {
  1720  	// Container symbols are expected to have content/data.
  1721  	// NB: this restriction may turn out to be too strict (it's possible
  1722  	// to imagine a zero-sized container with an interior symbol pointing
  1723  	// into it); it's ok to relax or remove it if we counter an
  1724  	// oddball host object that triggers this.
  1725  	if l.SymSize(container) == 0 && len(l.Data(container)) == 0 {
  1726  		panic("unexpected empty container symbol")
  1727  	}
  1728  	// The interior symbols for a container are not expected to have
  1729  	// content/data or relocations.
  1730  	if len(l.Data(interior)) != 0 {
  1731  		panic("unexpected non-empty interior symbol")
  1732  	}
  1733  	// Interior symbol is expected to be in the symbol table.
  1734  	if l.AttrNotInSymbolTable(interior) {
  1735  		panic("interior symbol must be in symtab")
  1736  	}
  1737  	// Only a single level of containment is allowed.
  1738  	if l.OuterSym(container) != 0 {
  1739  		panic("outer has outer itself")
  1740  	}
  1741  	// Interior sym should not already have a sibling.
  1742  	if l.SubSym(interior) != 0 {
  1743  		panic("sub set for subsym")
  1744  	}
  1745  	// Interior sym should not already point at a container.
  1746  	if l.OuterSym(interior) != 0 {
  1747  		panic("outer already set for subsym")
  1748  	}
  1749  	l.sub[interior] = l.sub[container]
  1750  	l.sub[container] = interior
  1751  	l.outer[interior] = container
  1752  }
  1753  
  1754  // OuterSym gets the outer/container symbol.
  1755  func (l *Loader) OuterSym(i Sym) Sym {
  1756  	return l.outer[i]
  1757  }
  1758  
  1759  // SubSym gets the subsymbol for host object loaded symbols.
  1760  func (l *Loader) SubSym(i Sym) Sym {
  1761  	return l.sub[i]
  1762  }
  1763  
  1764  // growOuter grows the slice used to store outer symbol.
  1765  func (l *Loader) growOuter(reqLen int) {
  1766  	curLen := len(l.outer)
  1767  	if reqLen > curLen {
  1768  		l.outer = append(l.outer, make([]Sym, reqLen-curLen)...)
  1769  	}
  1770  }
  1771  
  1772  // SetCarrierSym declares that 'c' is the carrier or container symbol
  1773  // for 's'. Carrier symbols are used in the linker to as a container
  1774  // for a collection of sub-symbols where the content of the
  1775  // sub-symbols is effectively concatenated to form the content of the
  1776  // carrier. The carrier is given a name in the output symbol table
  1777  // while the sub-symbol names are not. For example, the Go compiler
  1778  // emits named string symbols (type SGOSTRING) when compiling a
  1779  // package; after being deduplicated, these symbols are collected into
  1780  // a single unit by assigning them a new carrier symbol named
  1781  // "go:string.*" (which appears in the final symbol table for the
  1782  // output load module).
  1783  func (l *Loader) SetCarrierSym(s Sym, c Sym) {
  1784  	if c == 0 {
  1785  		panic("invalid carrier in SetCarrierSym")
  1786  	}
  1787  	if s == 0 {
  1788  		panic("invalid sub-symbol in SetCarrierSym")
  1789  	}
  1790  	// Carrier symbols are not expected to have content/data. It is
  1791  	// ok for them to have non-zero size (to allow for use of generator
  1792  	// symbols).
  1793  	if len(l.Data(c)) != 0 {
  1794  		panic("unexpected non-empty carrier symbol")
  1795  	}
  1796  	l.outer[s] = c
  1797  	// relocsym's foldSubSymbolOffset requires that we only
  1798  	// have a single level of containment-- enforce here.
  1799  	if l.outer[c] != 0 {
  1800  		panic("invalid nested carrier sym")
  1801  	}
  1802  }
  1803  
  1804  // Initialize Reachable bitmap and its siblings for running deadcode pass.
  1805  func (l *Loader) InitReachable() {
  1806  	l.growAttrBitmaps(l.NSym() + 1)
  1807  }
  1808  
  1809  type symWithVal struct {
  1810  	s Sym
  1811  	v int64
  1812  }
  1813  type bySymValue []symWithVal
  1814  
  1815  func (s bySymValue) Len() int           { return len(s) }
  1816  func (s bySymValue) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
  1817  func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
  1818  
  1819  // SortSub walks through the sub-symbols for 's' and sorts them
  1820  // in place by increasing value. Return value is the new
  1821  // sub symbol for the specified outer symbol.
  1822  func (l *Loader) SortSub(s Sym) Sym {
  1823  
  1824  	if s == 0 || l.sub[s] == 0 {
  1825  		return s
  1826  	}
  1827  
  1828  	// Sort symbols using a slice first. Use a stable sort on the off
  1829  	// chance that there's more than once symbol with the same value,
  1830  	// so as to preserve reproducible builds.
  1831  	sl := []symWithVal{}
  1832  	for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
  1833  		sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
  1834  	}
  1835  	sort.Stable(bySymValue(sl))
  1836  
  1837  	// Then apply any changes needed to the sub map.
  1838  	ns := Sym(0)
  1839  	for i := len(sl) - 1; i >= 0; i-- {
  1840  		s := sl[i].s
  1841  		l.sub[s] = ns
  1842  		ns = s
  1843  	}
  1844  
  1845  	// Update sub for outer symbol, then return
  1846  	l.sub[s] = sl[0].s
  1847  	return sl[0].s
  1848  }
  1849  
  1850  // SortSyms sorts a list of symbols by their value.
  1851  func (l *Loader) SortSyms(ss []Sym) {
  1852  	sort.SliceStable(ss, func(i, j int) bool { return l.SymValue(ss[i]) < l.SymValue(ss[j]) })
  1853  }
  1854  
  1855  // Insure that reachable bitmap and its siblings have enough size.
  1856  func (l *Loader) growAttrBitmaps(reqLen int) {
  1857  	if reqLen > l.attrReachable.Len() {
  1858  		// These are indexed by global symbol
  1859  		l.attrReachable = growBitmap(reqLen, l.attrReachable)
  1860  		l.attrOnList = growBitmap(reqLen, l.attrOnList)
  1861  		l.attrLocal = growBitmap(reqLen, l.attrLocal)
  1862  		l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
  1863  		l.attrUsedInIface = growBitmap(reqLen, l.attrUsedInIface)
  1864  		l.attrSpecial = growBitmap(reqLen, l.attrSpecial)
  1865  	}
  1866  	l.growExtAttrBitmaps()
  1867  }
  1868  
  1869  func (l *Loader) growExtAttrBitmaps() {
  1870  	// These are indexed by external symbol index (e.g. l.extIndex(i))
  1871  	extReqLen := len(l.payloads)
  1872  	if extReqLen > l.attrVisibilityHidden.Len() {
  1873  		l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
  1874  		l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
  1875  		l.attrShared = growBitmap(extReqLen, l.attrShared)
  1876  		l.attrExternal = growBitmap(extReqLen, l.attrExternal)
  1877  		l.generatedSyms = growBitmap(extReqLen, l.generatedSyms)
  1878  	}
  1879  }
  1880  
  1881  func (relocs *Relocs) Count() int { return len(relocs.rs) }
  1882  
  1883  // At returns the j-th reloc for a global symbol.
  1884  func (relocs *Relocs) At(j int) Reloc {
  1885  	if relocs.l.isExtReader(relocs.r) {
  1886  		return Reloc{&relocs.rs[j], relocs.r, relocs.l}
  1887  	}
  1888  	return Reloc{&relocs.rs[j], relocs.r, relocs.l}
  1889  }
  1890  
  1891  // Relocs returns a Relocs object for the given global sym.
  1892  func (l *Loader) Relocs(i Sym) Relocs {
  1893  	r, li := l.toLocal(i)
  1894  	if r == nil {
  1895  		panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
  1896  	}
  1897  	return l.relocs(r, li)
  1898  }
  1899  
  1900  // relocs returns a Relocs object given a local sym index and reader.
  1901  func (l *Loader) relocs(r *oReader, li uint32) Relocs {
  1902  	var rs []goobj.Reloc
  1903  	if l.isExtReader(r) {
  1904  		pp := l.payloads[li]
  1905  		rs = pp.relocs
  1906  	} else {
  1907  		rs = r.Relocs(li)
  1908  	}
  1909  	return Relocs{
  1910  		rs: rs,
  1911  		li: li,
  1912  		r:  r,
  1913  		l:  l,
  1914  	}
  1915  }
  1916  
  1917  func (l *Loader) auxs(i Sym) (*oReader, []goobj.Aux) {
  1918  	if l.IsExternal(i) {
  1919  		pp := l.getPayload(i)
  1920  		return l.objs[pp.objidx].r, pp.auxs
  1921  	} else {
  1922  		r, li := l.toLocal(i)
  1923  		return r, r.Auxs(li)
  1924  	}
  1925  }
  1926  
  1927  // Returns a specific aux symbol of type t for symbol i.
  1928  func (l *Loader) aux1(i Sym, t uint8) Sym {
  1929  	r, auxs := l.auxs(i)
  1930  	for j := range auxs {
  1931  		a := &auxs[j]
  1932  		if a.Type() == t {
  1933  			return l.resolve(r, a.Sym())
  1934  		}
  1935  	}
  1936  	return 0
  1937  }
  1938  
  1939  func (l *Loader) Pcsp(i Sym) Sym { return l.aux1(i, goobj.AuxPcsp) }
  1940  
  1941  // Returns all aux symbols of per-PC data for symbol i.
  1942  // tmp is a scratch space for the pcdata slice.
  1943  func (l *Loader) PcdataAuxs(i Sym, tmp []Sym) (pcsp, pcfile, pcline, pcinline Sym, pcdata []Sym) {
  1944  	pcdata = tmp[:0]
  1945  	r, auxs := l.auxs(i)
  1946  	for j := range auxs {
  1947  		a := &auxs[j]
  1948  		switch a.Type() {
  1949  		case goobj.AuxPcsp:
  1950  			pcsp = l.resolve(r, a.Sym())
  1951  		case goobj.AuxPcline:
  1952  			pcline = l.resolve(r, a.Sym())
  1953  		case goobj.AuxPcfile:
  1954  			pcfile = l.resolve(r, a.Sym())
  1955  		case goobj.AuxPcinline:
  1956  			pcinline = l.resolve(r, a.Sym())
  1957  		case goobj.AuxPcdata:
  1958  			pcdata = append(pcdata, l.resolve(r, a.Sym()))
  1959  		}
  1960  	}
  1961  	return
  1962  }
  1963  
  1964  // Returns the number of pcdata for symbol i.
  1965  func (l *Loader) NumPcdata(i Sym) int {
  1966  	n := 0
  1967  	_, auxs := l.auxs(i)
  1968  	for j := range auxs {
  1969  		a := &auxs[j]
  1970  		if a.Type() == goobj.AuxPcdata {
  1971  			n++
  1972  		}
  1973  	}
  1974  	return n
  1975  }
  1976  
  1977  // Returns all funcdata symbols of symbol i.
  1978  // tmp is a scratch space.
  1979  func (l *Loader) Funcdata(i Sym, tmp []Sym) []Sym {
  1980  	fd := tmp[:0]
  1981  	r, auxs := l.auxs(i)
  1982  	for j := range auxs {
  1983  		a := &auxs[j]
  1984  		if a.Type() == goobj.AuxFuncdata {
  1985  			fd = append(fd, l.resolve(r, a.Sym()))
  1986  		}
  1987  	}
  1988  	return fd
  1989  }
  1990  
  1991  // Returns the number of funcdata for symbol i.
  1992  func (l *Loader) NumFuncdata(i Sym) int {
  1993  	n := 0
  1994  	_, auxs := l.auxs(i)
  1995  	for j := range auxs {
  1996  		a := &auxs[j]
  1997  		if a.Type() == goobj.AuxFuncdata {
  1998  			n++
  1999  		}
  2000  	}
  2001  	return n
  2002  }
  2003  
  2004  // FuncInfo provides hooks to access goobj.FuncInfo in the objects.
  2005  type FuncInfo struct {
  2006  	l       *Loader
  2007  	r       *oReader
  2008  	data    []byte
  2009  	lengths goobj.FuncInfoLengths
  2010  }
  2011  
  2012  func (fi *FuncInfo) Valid() bool { return fi.r != nil }
  2013  
  2014  func (fi *FuncInfo) Args() int {
  2015  	return int((*goobj.FuncInfo)(nil).ReadArgs(fi.data))
  2016  }
  2017  
  2018  func (fi *FuncInfo) Locals() int {
  2019  	return int((*goobj.FuncInfo)(nil).ReadLocals(fi.data))
  2020  }
  2021  
  2022  func (fi *FuncInfo) FuncID() abi.FuncID {
  2023  	return (*goobj.FuncInfo)(nil).ReadFuncID(fi.data)
  2024  }
  2025  
  2026  func (fi *FuncInfo) FuncFlag() abi.FuncFlag {
  2027  	return (*goobj.FuncInfo)(nil).ReadFuncFlag(fi.data)
  2028  }
  2029  
  2030  func (fi *FuncInfo) StartLine() int32 {
  2031  	return (*goobj.FuncInfo)(nil).ReadStartLine(fi.data)
  2032  }
  2033  
  2034  // Preload has to be called prior to invoking the various methods
  2035  // below related to pcdata, funcdataoff, files, and inltree nodes.
  2036  func (fi *FuncInfo) Preload() {
  2037  	fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
  2038  }
  2039  
  2040  func (fi *FuncInfo) NumFile() uint32 {
  2041  	if !fi.lengths.Initialized {
  2042  		panic("need to call Preload first")
  2043  	}
  2044  	return fi.lengths.NumFile
  2045  }
  2046  
  2047  func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
  2048  	if !fi.lengths.Initialized {
  2049  		panic("need to call Preload first")
  2050  	}
  2051  	return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
  2052  }
  2053  
  2054  // TopFrame returns true if the function associated with this FuncInfo
  2055  // is an entry point, meaning that unwinders should stop when they hit
  2056  // this function.
  2057  func (fi *FuncInfo) TopFrame() bool {
  2058  	return (fi.FuncFlag() & abi.FuncFlagTopFrame) != 0
  2059  }
  2060  
  2061  type InlTreeNode struct {
  2062  	Parent   int32
  2063  	File     goobj.CUFileIndex
  2064  	Line     int32
  2065  	Func     Sym
  2066  	ParentPC int32
  2067  }
  2068  
  2069  func (fi *FuncInfo) NumInlTree() uint32 {
  2070  	if !fi.lengths.Initialized {
  2071  		panic("need to call Preload first")
  2072  	}
  2073  	return fi.lengths.NumInlTree
  2074  }
  2075  
  2076  func (fi *FuncInfo) InlTree(k int) InlTreeNode {
  2077  	if !fi.lengths.Initialized {
  2078  		panic("need to call Preload first")
  2079  	}
  2080  	node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
  2081  	return InlTreeNode{
  2082  		Parent:   node.Parent,
  2083  		File:     node.File,
  2084  		Line:     node.Line,
  2085  		Func:     fi.l.resolve(fi.r, node.Func),
  2086  		ParentPC: node.ParentPC,
  2087  	}
  2088  }
  2089  
  2090  func (l *Loader) FuncInfo(i Sym) FuncInfo {
  2091  	r, auxs := l.auxs(i)
  2092  	for j := range auxs {
  2093  		a := &auxs[j]
  2094  		if a.Type() == goobj.AuxFuncInfo {
  2095  			b := r.Data(a.Sym().SymIdx)
  2096  			return FuncInfo{l, r, b, goobj.FuncInfoLengths{}}
  2097  		}
  2098  	}
  2099  	return FuncInfo{}
  2100  }
  2101  
  2102  // Preload a package: adds autolib.
  2103  // Does not add defined package or non-packaged symbols to the symbol table.
  2104  // These are done in LoadSyms.
  2105  // Does not read symbol data.
  2106  // Returns the fingerprint of the object.
  2107  func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
  2108  	roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
  2109  	if err != nil {
  2110  		log.Fatal("cannot read object file:", err)
  2111  	}
  2112  	r := goobj.NewReaderFromBytes(roObject, readonly)
  2113  	if r == nil {
  2114  		if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
  2115  			log.Fatalf("found object file %s in old format", f.File().Name())
  2116  		}
  2117  		panic("cannot read object file")
  2118  	}
  2119  	pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
  2120  	ndef := r.NSym()
  2121  	nhashed64def := r.NHashed64def()
  2122  	nhasheddef := r.NHasheddef()
  2123  	or := &oReader{
  2124  		Reader:       r,
  2125  		unit:         unit,
  2126  		version:      localSymVersion,
  2127  		pkgprefix:    pkgprefix,
  2128  		syms:         make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
  2129  		ndef:         ndef,
  2130  		nhasheddef:   nhasheddef,
  2131  		nhashed64def: nhashed64def,
  2132  		objidx:       uint32(len(l.objs)),
  2133  	}
  2134  
  2135  	if r.Unlinkable() {
  2136  		log.Fatalf("link: unlinkable object (from package %s) - compiler requires -p flag", lib.Pkg)
  2137  	}
  2138  
  2139  	// Autolib
  2140  	lib.Autolib = append(lib.Autolib, r.Autolib()...)
  2141  
  2142  	// DWARF file table
  2143  	nfile := r.NFile()
  2144  	unit.FileTable = make([]string, nfile)
  2145  	for i := range unit.FileTable {
  2146  		unit.FileTable[i] = r.File(i)
  2147  	}
  2148  
  2149  	l.addObj(lib.Pkg, or)
  2150  
  2151  	// The caller expects us consuming all the data
  2152  	f.MustSeek(length, io.SeekCurrent)
  2153  
  2154  	return r.Fingerprint()
  2155  }
  2156  
  2157  // Holds the loader along with temporary states for loading symbols.
  2158  type loadState struct {
  2159  	l            *Loader
  2160  	hashed64Syms map[uint64]symAndSize         // short hashed (content-addressable) symbols, keyed by content hash
  2161  	hashedSyms   map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
  2162  }
  2163  
  2164  // Preload symbols of given kind from an object.
  2165  func (st *loadState) preloadSyms(r *oReader, kind int) {
  2166  	l := st.l
  2167  	var start, end uint32
  2168  	switch kind {
  2169  	case pkgDef:
  2170  		start = 0
  2171  		end = uint32(r.ndef)
  2172  	case hashed64Def:
  2173  		start = uint32(r.ndef)
  2174  		end = uint32(r.ndef + r.nhashed64def)
  2175  	case hashedDef:
  2176  		start = uint32(r.ndef + r.nhashed64def)
  2177  		end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
  2178  	case nonPkgDef:
  2179  		start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
  2180  		end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
  2181  	default:
  2182  		panic("preloadSyms: bad kind")
  2183  	}
  2184  	l.growAttrBitmaps(len(l.objSyms) + int(end-start))
  2185  	loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
  2186  	for i := start; i < end; i++ {
  2187  		osym := r.Sym(i)
  2188  		var name string
  2189  		var v int
  2190  		if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
  2191  			name = osym.Name(r.Reader)
  2192  			v = abiToVer(osym.ABI(), r.version)
  2193  		}
  2194  		gi := st.addSym(name, v, r, i, kind, osym)
  2195  		r.syms[i] = gi
  2196  		if osym.Local() {
  2197  			l.SetAttrLocal(gi, true)
  2198  		}
  2199  		if osym.UsedInIface() {
  2200  			l.SetAttrUsedInIface(gi, true)
  2201  		}
  2202  		if strings.HasPrefix(name, "runtime.") ||
  2203  			(loadingRuntimePkg && strings.HasPrefix(name, "type:")) {
  2204  			if bi := goobj.BuiltinIdx(name, int(osym.ABI())); bi != -1 {
  2205  				// This is a definition of a builtin symbol. Record where it is.
  2206  				l.builtinSyms[bi] = gi
  2207  			}
  2208  		}
  2209  		if a := int32(osym.Align()); a != 0 && a > l.SymAlign(gi) {
  2210  			l.SetSymAlign(gi, a)
  2211  		}
  2212  	}
  2213  }
  2214  
  2215  // Add syms, hashed (content-addressable) symbols, non-package symbols, and
  2216  // references to external symbols (which are always named).
  2217  func (l *Loader) LoadSyms(arch *sys.Arch) {
  2218  	// Allocate space for symbols, making a guess as to how much space we need.
  2219  	// This function was determined empirically by looking at the cmd/compile on
  2220  	// Darwin, and picking factors for hashed and hashed64 syms.
  2221  	var symSize, hashedSize, hashed64Size int
  2222  	for _, o := range l.objs[goObjStart:] {
  2223  		symSize += o.r.ndef + o.r.nhasheddef/2 + o.r.nhashed64def/2 + o.r.NNonpkgdef()
  2224  		hashedSize += o.r.nhasheddef / 2
  2225  		hashed64Size += o.r.nhashed64def / 2
  2226  	}
  2227  	// Index 0 is invalid for symbols.
  2228  	l.objSyms = make([]objSym, 1, symSize)
  2229  
  2230  	st := loadState{
  2231  		l:            l,
  2232  		hashed64Syms: make(map[uint64]symAndSize, hashed64Size),
  2233  		hashedSyms:   make(map[goobj.HashType]symAndSize, hashedSize),
  2234  	}
  2235  
  2236  	for _, o := range l.objs[goObjStart:] {
  2237  		st.preloadSyms(o.r, pkgDef)
  2238  	}
  2239  	l.npkgsyms = l.NSym()
  2240  	for _, o := range l.objs[goObjStart:] {
  2241  		st.preloadSyms(o.r, hashed64Def)
  2242  		st.preloadSyms(o.r, hashedDef)
  2243  		st.preloadSyms(o.r, nonPkgDef)
  2244  	}
  2245  	l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
  2246  	for _, o := range l.objs[goObjStart:] {
  2247  		loadObjRefs(l, o.r, arch)
  2248  	}
  2249  	l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
  2250  	l.outer = make([]Sym, l.NSym(), l.NSym()+1000)
  2251  }
  2252  
  2253  func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
  2254  	// load non-package refs
  2255  	ndef := uint32(r.NAlldef())
  2256  	for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
  2257  		osym := r.Sym(ndef + i)
  2258  		name := osym.Name(r.Reader)
  2259  		v := abiToVer(osym.ABI(), r.version)
  2260  		r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
  2261  		gi := r.syms[ndef+i]
  2262  		if osym.Local() {
  2263  			l.SetAttrLocal(gi, true)
  2264  		}
  2265  		if osym.UsedInIface() {
  2266  			l.SetAttrUsedInIface(gi, true)
  2267  		}
  2268  	}
  2269  
  2270  	// referenced packages
  2271  	npkg := r.NPkg()
  2272  	r.pkg = make([]uint32, npkg)
  2273  	for i := 1; i < npkg; i++ { // PkgIdx 0 is a dummy invalid package
  2274  		pkg := r.Pkg(i)
  2275  		objidx, ok := l.objByPkg[pkg]
  2276  		if !ok {
  2277  			log.Fatalf("%v: reference to nonexistent package %s", r.unit.Lib, pkg)
  2278  		}
  2279  		r.pkg[i] = objidx
  2280  	}
  2281  
  2282  	// load flags of package refs
  2283  	for i, n := 0, r.NRefFlags(); i < n; i++ {
  2284  		rf := r.RefFlags(i)
  2285  		gi := l.resolve(r, rf.Sym())
  2286  		if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
  2287  			l.SetAttrUsedInIface(gi, true)
  2288  		}
  2289  	}
  2290  }
  2291  
  2292  func abiToVer(abi uint16, localSymVersion int) int {
  2293  	var v int
  2294  	if abi == goobj.SymABIstatic {
  2295  		// Static
  2296  		v = localSymVersion
  2297  	} else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
  2298  		// Note that data symbols are "ABI0", which maps to version 0.
  2299  		v = abiver
  2300  	} else {
  2301  		log.Fatalf("invalid symbol ABI: %d", abi)
  2302  	}
  2303  	return v
  2304  }
  2305  
  2306  // TopLevelSym tests a symbol (by name and kind) to determine whether
  2307  // the symbol first class sym (participating in the link) or is an
  2308  // anonymous aux or sub-symbol containing some sub-part or payload of
  2309  // another symbol.
  2310  func (l *Loader) TopLevelSym(s Sym) bool {
  2311  	return topLevelSym(l.SymName(s), l.SymType(s))
  2312  }
  2313  
  2314  // topLevelSym tests a symbol name and kind to determine whether
  2315  // the symbol first class sym (participating in the link) or is an
  2316  // anonymous aux or sub-symbol containing some sub-part or payload of
  2317  // another symbol.
  2318  func topLevelSym(sname string, skind sym.SymKind) bool {
  2319  	if sname != "" {
  2320  		return true
  2321  	}
  2322  	switch skind {
  2323  	case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
  2324  		return true
  2325  	default:
  2326  		return false
  2327  	}
  2328  }
  2329  
  2330  // cloneToExternal takes the existing object file symbol (symIdx)
  2331  // and creates a new external symbol payload that is a clone with
  2332  // respect to name, version, type, relocations, etc. The idea here
  2333  // is that if the linker decides it wants to update the contents of
  2334  // a symbol originally discovered as part of an object file, it's
  2335  // easier to do this if we make the updates to an external symbol
  2336  // payload.
  2337  func (l *Loader) cloneToExternal(symIdx Sym) {
  2338  	if l.IsExternal(symIdx) {
  2339  		panic("sym is already external, no need for clone")
  2340  	}
  2341  
  2342  	// Read the particulars from object.
  2343  	r, li := l.toLocal(symIdx)
  2344  	osym := r.Sym(li)
  2345  	sname := osym.Name(r.Reader)
  2346  	sver := abiToVer(osym.ABI(), r.version)
  2347  	skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
  2348  
  2349  	// Create new symbol, update version and kind.
  2350  	pi := l.newPayload(sname, sver)
  2351  	pp := l.payloads[pi]
  2352  	pp.kind = skind
  2353  	pp.ver = sver
  2354  	pp.size = int64(osym.Siz())
  2355  	pp.objidx = r.objidx
  2356  
  2357  	// If this is a def, then copy the guts. We expect this case
  2358  	// to be very rare (one case it may come up is with -X).
  2359  	if li < uint32(r.NAlldef()) {
  2360  
  2361  		// Copy relocations
  2362  		relocs := l.Relocs(symIdx)
  2363  		pp.relocs = make([]goobj.Reloc, relocs.Count())
  2364  		for i := range pp.relocs {
  2365  			// Copy the relocs slice.
  2366  			// Convert local reference to global reference.
  2367  			rel := relocs.At(i)
  2368  			pp.relocs[i].Set(rel.Off(), rel.Siz(), uint16(rel.Type()), rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
  2369  		}
  2370  
  2371  		// Copy data
  2372  		pp.data = r.Data(li)
  2373  	}
  2374  
  2375  	// If we're overriding a data symbol, collect the associated
  2376  	// Gotype, so as to propagate it to the new symbol.
  2377  	auxs := r.Auxs(li)
  2378  	pp.auxs = auxs
  2379  
  2380  	// Install new payload to global index space.
  2381  	// (This needs to happen at the end, as the accessors above
  2382  	// need to access the old symbol content.)
  2383  	l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
  2384  	l.extReader.syms = append(l.extReader.syms, symIdx)
  2385  
  2386  	// Some attributes were encoded in the object file. Copy them over.
  2387  	l.SetAttrDuplicateOK(symIdx, r.Sym(li).Dupok())
  2388  	l.SetAttrShared(symIdx, r.Shared())
  2389  }
  2390  
  2391  // Copy the payload of symbol src to dst. Both src and dst must be external
  2392  // symbols.
  2393  // The intended use case is that when building/linking against a shared library,
  2394  // where we do symbol name mangling, the Go object file may have reference to
  2395  // the original symbol name whereas the shared library provides a symbol with
  2396  // the mangled name. When we do mangling, we copy payload of mangled to original.
  2397  func (l *Loader) CopySym(src, dst Sym) {
  2398  	if !l.IsExternal(dst) {
  2399  		panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
  2400  	}
  2401  	if !l.IsExternal(src) {
  2402  		panic("src is not external") //l.cloneToExternal(src)
  2403  	}
  2404  	l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
  2405  	l.SetSymPkg(dst, l.SymPkg(src))
  2406  	// TODO: other attributes?
  2407  }
  2408  
  2409  // CreateExtSym creates a new external symbol with the specified name
  2410  // without adding it to any lookup tables, returning a Sym index for it.
  2411  func (l *Loader) CreateExtSym(name string, ver int) Sym {
  2412  	return l.newExtSym(name, ver)
  2413  }
  2414  
  2415  // CreateStaticSym creates a new static symbol with the specified name
  2416  // without adding it to any lookup tables, returning a Sym index for it.
  2417  func (l *Loader) CreateStaticSym(name string) Sym {
  2418  	// Assign a new unique negative version -- this is to mark the
  2419  	// symbol so that it is not included in the name lookup table.
  2420  	l.anonVersion--
  2421  	return l.newExtSym(name, l.anonVersion)
  2422  }
  2423  
  2424  func (l *Loader) FreeSym(i Sym) {
  2425  	if l.IsExternal(i) {
  2426  		pp := l.getPayload(i)
  2427  		*pp = extSymPayload{}
  2428  	}
  2429  }
  2430  
  2431  // relocId is essentially a <S,R> tuple identifying the Rth
  2432  // relocation of symbol S.
  2433  type relocId struct {
  2434  	sym  Sym
  2435  	ridx int
  2436  }
  2437  
  2438  // SetRelocVariant sets the 'variant' property of a relocation on
  2439  // some specific symbol.
  2440  func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
  2441  	// sanity check
  2442  	if relocs := l.Relocs(s); ri >= relocs.Count() {
  2443  		panic("invalid relocation ID")
  2444  	}
  2445  	if l.relocVariant == nil {
  2446  		l.relocVariant = make(map[relocId]sym.RelocVariant)
  2447  	}
  2448  	if v != 0 {
  2449  		l.relocVariant[relocId{s, ri}] = v
  2450  	} else {
  2451  		delete(l.relocVariant, relocId{s, ri})
  2452  	}
  2453  }
  2454  
  2455  // RelocVariant returns the 'variant' property of a relocation on
  2456  // some specific symbol.
  2457  func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
  2458  	return l.relocVariant[relocId{s, ri}]
  2459  }
  2460  
  2461  // UndefinedRelocTargets iterates through the global symbol index
  2462  // space, looking for symbols with relocations targeting undefined
  2463  // references. The linker's loadlib method uses this to determine if
  2464  // there are unresolved references to functions in system libraries
  2465  // (for example, libgcc.a), presumably due to CGO code. Return value
  2466  // is a pair of lists of loader.Sym's. First list corresponds to the
  2467  // corresponding to the undefined symbols themselves, the second list
  2468  // is the symbol that is making a reference to the undef. The "limit"
  2469  // param controls the maximum number of results returned; if "limit"
  2470  // is -1, then all undefs are returned.
  2471  func (l *Loader) UndefinedRelocTargets(limit int) ([]Sym, []Sym) {
  2472  	result, fromr := []Sym{}, []Sym{}
  2473  outerloop:
  2474  	for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
  2475  		relocs := l.Relocs(si)
  2476  		for ri := 0; ri < relocs.Count(); ri++ {
  2477  			r := relocs.At(ri)
  2478  			rs := r.Sym()
  2479  			if rs != 0 && l.SymType(rs) == sym.SXREF && l.SymName(rs) != ".got" {
  2480  				result = append(result, rs)
  2481  				fromr = append(fromr, si)
  2482  				if limit != -1 && len(result) >= limit {
  2483  					break outerloop
  2484  				}
  2485  			}
  2486  		}
  2487  	}
  2488  	return result, fromr
  2489  }
  2490  
  2491  // AssignTextSymbolOrder populates the Textp slices within each
  2492  // library and compilation unit, insuring that packages are laid down
  2493  // in dependency order (internal first, then everything else). Return value
  2494  // is a slice of all text syms.
  2495  func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
  2496  
  2497  	// Library Textp lists should be empty at this point.
  2498  	for _, lib := range libs {
  2499  		if len(lib.Textp) != 0 {
  2500  			panic("expected empty Textp slice for library")
  2501  		}
  2502  		if len(lib.DupTextSyms) != 0 {
  2503  			panic("expected empty DupTextSyms slice for library")
  2504  		}
  2505  	}
  2506  
  2507  	// Used to record which dupok symbol we've assigned to a unit.
  2508  	// Can't use the onlist attribute here because it will need to
  2509  	// clear for the later assignment of the sym.Symbol to a unit.
  2510  	// NB: we can convert to using onList once we no longer have to
  2511  	// call the regular addToTextp.
  2512  	assignedToUnit := MakeBitmap(l.NSym() + 1)
  2513  
  2514  	// Start off textp with reachable external syms.
  2515  	textp := []Sym{}
  2516  	for _, sym := range extsyms {
  2517  		if !l.attrReachable.Has(sym) {
  2518  			continue
  2519  		}
  2520  		textp = append(textp, sym)
  2521  	}
  2522  
  2523  	// Walk through all text symbols from Go object files and append
  2524  	// them to their corresponding library's textp list.
  2525  	for _, o := range l.objs[goObjStart:] {
  2526  		r := o.r
  2527  		lib := r.unit.Lib
  2528  		for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
  2529  			gi := l.toGlobal(r, i)
  2530  			if !l.attrReachable.Has(gi) {
  2531  				continue
  2532  			}
  2533  			osym := r.Sym(i)
  2534  			st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
  2535  			if st != sym.STEXT {
  2536  				continue
  2537  			}
  2538  			dupok := osym.Dupok()
  2539  			if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
  2540  				// A dupok text symbol is resolved to another package.
  2541  				// We still need to record its presence in the current
  2542  				// package, as the trampoline pass expects packages
  2543  				// are laid out in dependency order.
  2544  				lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
  2545  				continue // symbol in different object
  2546  			}
  2547  			if dupok {
  2548  				lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
  2549  				continue
  2550  			}
  2551  
  2552  			lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
  2553  		}
  2554  	}
  2555  
  2556  	// Now assemble global textp, and assign text symbols to units.
  2557  	for _, doInternal := range [2]bool{true, false} {
  2558  		for idx, lib := range libs {
  2559  			if intlibs[idx] != doInternal {
  2560  				continue
  2561  			}
  2562  			lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
  2563  			for i, list := range lists {
  2564  				for _, s := range list {
  2565  					sym := Sym(s)
  2566  					if !assignedToUnit.Has(sym) {
  2567  						textp = append(textp, sym)
  2568  						unit := l.SymUnit(sym)
  2569  						if unit != nil {
  2570  							unit.Textp = append(unit.Textp, s)
  2571  							assignedToUnit.Set(sym)
  2572  						}
  2573  						// Dupok symbols may be defined in multiple packages; the
  2574  						// associated package for a dupok sym is chosen sort of
  2575  						// arbitrarily (the first containing package that the linker
  2576  						// loads). Canonicalizes its Pkg to the package with which
  2577  						// it will be laid down in text.
  2578  						if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
  2579  							l.SetSymPkg(sym, lib.Pkg)
  2580  						}
  2581  					}
  2582  				}
  2583  			}
  2584  			lib.Textp = nil
  2585  			lib.DupTextSyms = nil
  2586  		}
  2587  	}
  2588  
  2589  	return textp
  2590  }
  2591  
  2592  // ErrorReporter is a helper class for reporting errors.
  2593  type ErrorReporter struct {
  2594  	ldr              *Loader
  2595  	AfterErrorAction func()
  2596  }
  2597  
  2598  // Errorf method logs an error message.
  2599  //
  2600  // After each error, the error actions function will be invoked; this
  2601  // will either terminate the link immediately (if -h option given)
  2602  // or it will keep a count and exit if more than 20 errors have been printed.
  2603  //
  2604  // Logging an error means that on exit cmd/link will delete any
  2605  // output file and return a non-zero error code.
  2606  func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
  2607  	if s != 0 && reporter.ldr.SymName(s) != "" {
  2608  		// Note: Replace is needed here because symbol names might have % in them,
  2609  		// due to the use of LinkString for names of instantiating types.
  2610  		format = strings.Replace(reporter.ldr.SymName(s), "%", "%%", -1) + ": " + format
  2611  	} else {
  2612  		format = fmt.Sprintf("sym %d: %s", s, format)
  2613  	}
  2614  	format += "\n"
  2615  	fmt.Fprintf(os.Stderr, format, args...)
  2616  	reporter.AfterErrorAction()
  2617  }
  2618  
  2619  // GetErrorReporter returns the loader's associated error reporter.
  2620  func (l *Loader) GetErrorReporter() *ErrorReporter {
  2621  	return l.errorReporter
  2622  }
  2623  
  2624  // Errorf method logs an error message. See ErrorReporter.Errorf for details.
  2625  func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
  2626  	l.errorReporter.Errorf(s, format, args...)
  2627  }
  2628  
  2629  // Symbol statistics.
  2630  func (l *Loader) Stat() string {
  2631  	s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
  2632  	s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
  2633  		l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
  2634  	return s
  2635  }
  2636  
  2637  // For debugging.
  2638  func (l *Loader) Dump() {
  2639  	fmt.Println("objs")
  2640  	for _, obj := range l.objs[goObjStart:] {
  2641  		if obj.r != nil {
  2642  			fmt.Println(obj.i, obj.r.unit.Lib)
  2643  		}
  2644  	}
  2645  	fmt.Println("extStart:", l.extStart)
  2646  	fmt.Println("Nsyms:", len(l.objSyms))
  2647  	fmt.Println("syms")
  2648  	for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
  2649  		pi := ""
  2650  		if l.IsExternal(i) {
  2651  			pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
  2652  		}
  2653  		sect := ""
  2654  		if l.SymSect(i) != nil {
  2655  			sect = l.SymSect(i).Name
  2656  		}
  2657  		fmt.Printf("%v %v %v %v %x %v\n", i, l.SymName(i), l.SymType(i), pi, l.SymValue(i), sect)
  2658  	}
  2659  	fmt.Println("symsByName")
  2660  	for name, i := range l.symsByName[0] {
  2661  		fmt.Println(i, name, 0)
  2662  	}
  2663  	for name, i := range l.symsByName[1] {
  2664  		fmt.Println(i, name, 1)
  2665  	}
  2666  	fmt.Println("payloads:")
  2667  	for i := range l.payloads {
  2668  		pp := l.payloads[i]
  2669  		fmt.Println(i, pp.name, pp.ver, pp.kind)
  2670  	}
  2671  }