Skip to content
Snippets Groups Projects
loader.go 42.5 KiB
Newer Older
  • Learn to ignore specific revisions
  • // Copyright 2019 The Go Authors. All rights reserved.
    // Use of this source code is governed by a BSD-style
    // license that can be found in the LICENSE file.
    
    
    	"cmd/internal/goobj2"
    	"cmd/internal/obj"
    	"cmd/internal/objabi"
    	"cmd/internal/sys"
    	"cmd/link/internal/sym"
    	"fmt"
    	"log"
    	"os"
    	"sort"
    	"strconv"
    	"strings"
    )
    
    var _ = fmt.Print
    
    
    // Sym encapsulates a global symbol index, used to identify a specific
    // Go symbol. The 0-valued Sym is corresponds to an invalid symbol.
    type Sym int
    
    
    // Relocs encapsulates the set of relocations on a given symbol; an
    // instance of this type is returned by the Loader Relocs() method.
    type Relocs struct {
    	Count int // number of relocs
    
    	li int      // local index of symbol whose relocs we're examining
    	r  *oReader // object reader for containing package
    	l  *Loader  // loader
    
    	extIdx Sym // index of external symbol we're examining or 0
    
    }
    
    // Reloc contains the payload for a specific relocation.
    // TODO: replace this with sym.Reloc, once we change the
    // relocation target from "*sym.Symbol" to "loader.Sym" in sym.Reloc.
    type Reloc struct {
    	Off  int32            // offset to rewrite
    	Size uint8            // number of bytes to rewrite: 0, 1, 2, or 4
    	Type objabi.RelocType // the relocation type
    	Add  int64            // addend
    	Sym  Sym              // global index of symbol the reloc addresses
    }
    
    
    // oReader is a wrapper type of obj.Reader, along with some
    // extra information.
    // TODO: rename to objReader once the old one is gone?
    type oReader struct {
    	*goobj2.Reader
    	unit      *sym.CompilationUnit
    
    	version   int    // version of static symbol
    	flags     uint32 // read from object file
    
    	rcache    []Sym // cache mapping local PkgNone symbol to resolved Sym
    
    type objIdx struct {
    
    }
    
    type nameVer struct {
    	name string
    	v    int
    }
    
    
    type bitmap []uint32
    
    // set the i-th bit.
    func (bm bitmap) Set(i Sym) {
    	n, r := uint(i)/32, uint(i)%32
    	bm[n] |= 1 << r
    }
    
    // whether the i-th bit is set.
    func (bm bitmap) Has(i Sym) bool {
    	n, r := uint(i)/32, uint(i)%32
    	return bm[n]&(1<<r) != 0
    }
    
    
    // return current length of bitmap in bits.
    func (bm bitmap) len() int {
    	return len(bm) * 32
    }
    
    func makeBitmap(n int) bitmap {
    	return make(bitmap, (n+31)/32)
    }
    
    
    // growBitmap insures that the specified bitmap has enough capacity,
    // reallocating (doubling the size) if needed.
    func growBitmap(reqLen int, b bitmap) bitmap {
    	curLen := b.len()
    	if reqLen > curLen {
    		b = append(b, makeBitmap(reqLen-curLen)...)
    	}
    	return b
    }
    
    
    // A Loader loads new object files and resolves indexed symbol references.
    
    //
    // Notes on the layout of global symbol index space:
    //
    // - Go object files are read before host object files; each Go object
    //   read allocates a new chunk of global index space of size P + NP,
    //   where P is the number of package defined symbols in the object and
    //   NP is the number of non-package defined symbols.
    //
    // - In loader.LoadRefs(), the loader makes a sweep through all of the
    //   non-package references in each object file and allocates sym indices
    //   for any symbols that have not yet been defined (start of this space
    //   is marked by loader.extStart).
    //
    // - Host object file loading happens; the host object loader does a
    //   name/version lookup for each symbol it finds; this can wind up
    //   extending the external symbol index space range. The host object
    //   loader currently stores symbol payloads in sym.Symbol objects,
    //   which get handed off to the loader.
    //
    // - A given external symbol (Sym) either has a sym.Symbol acting as
    //   its backing store (this will continue to be the case until we
    //   finish rewriting the host object loader to work entirely with
    //   loader.Sym) or it has a "payload" backing store (represented by
    //   extSymPayload). Newly created external symbols (created by
    //   a call to AddExtSym or equivalent) start out in the "has payload"
    //   state, and continue until installSym is called for the sym
    //   index in question.
    //
    // - At some point (when the wayfront is pushed through all of the
    //   linker), all external symbols will be payload-based, and we can
    //   get rid of the loader.Syms array.
    //
    
    	start       map[*oReader]Sym // map from object file to its start index
    	objs        []objIdx         // sorted by start index (i.e. objIdx.i)
    	max         Sym              // current max index
    	extStart    Sym              // from this index on, the symbols are externally defined
    	builtinSyms []Sym            // global index of builtin symbols
    
    	ocache      int              // index (into 'objs') of most recent lookup
    
    	symsByName    [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
    	extStaticSyms map[nameVer]Sym   // externally defined static symbols, keyed by name
    	overwrite     map[Sym]Sym       // overwrite[i]=j if symbol j overwrites symbol i
    
    	payloads []extSymPayload // contents of linker-materialized external syms
    
    
    	itablink map[Sym]struct{} // itablink[j] defined if j is go.itablink.*
    
    
    	objByPkg map[string]*oReader // map package path to its Go object reader
    
    
    	Syms     []*sym.Symbol // indexed symbols. XXX we still make sym.Symbol for now.
    	symBatch []sym.Symbol  // batch of symbols.
    
    	anonVersion int // most recently assigned ext static sym pseudo-version
    
    
    	Reachable bitmap // bitmap of reachable symbols, indexed by global index
    
    
    	// Used to implement field tracking; created during deadcode if
    	// field tracking is enabled. Reachparent[K] contains the index of
    	// the symbol that triggered the marking of symbol K as live.
    	Reachparent []Sym
    
    
    	relocBatch []sym.Reloc // for bulk allocation of relocations
    
    
    	flags uint32
    
    	strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
    
    // extSymPayload holds the payload (data + relocations) for linker-synthesized
    // external symbols.
    type extSymPayload struct {
    	name   string // TODO: would this be better as offset into str table?
    	size   int64
    	value  int64
    	ver    int
    	kind   sym.SymKind
    	relocs []Reloc
    	data   []byte
    }
    
    
    const (
    	// Loader.flags
    	FlagStrictDups = 1 << iota
    )
    
    func NewLoader(flags uint32) *Loader {
    
    		start:         make(map[*oReader]Sym),
    
    		symsByName:    [2]map[string]Sym{make(map[string]Sym), make(map[string]Sym)},
    		objByPkg:      make(map[string]*oReader),
    		overwrite:     make(map[Sym]Sym),
    		itablink:      make(map[Sym]struct{}),
    		extStaticSyms: make(map[nameVer]Sym),
    
    		builtinSyms:   make([]Sym, nbuiltin),
    
    	}
    }
    
    // Return the start index in the global index space for a given object file.
    
    func (l *Loader) startIndex(r *oReader) Sym {
    
    	return l.start[r]
    }
    
    // Add object file r, return the start index.
    
    func (l *Loader) addObj(pkg string, r *oReader) Sym {
    
    	if _, ok := l.start[r]; ok {
    		panic("already added")
    	}
    
    	pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
    
    	if _, ok := l.objByPkg[pkg]; !ok {
    		l.objByPkg[pkg] = r
    	}
    
    	n := r.NSym() + r.NNonpkgdef()
    	i := l.max + 1
    	l.start[r] = i
    
    	l.objs = append(l.objs, objIdx{r, i, i + Sym(n) - 1})
    
    	return i
    }
    
    // Add a symbol with a given index, return if it is added.
    
    func (l *Loader) AddSym(name string, ver int, i Sym, r *oReader, dupok bool, typ sym.SymKind) bool {
    
    	if l.extStart != 0 {
    		panic("AddSym called after AddExtSym is called")
    	}
    
    	if ver == r.version {
    		// Static symbol. Add its global index but don't
    		// add to name lookup table, as it cannot be
    		// referenced by name.
    		return true
    	}
    
    	if oldi, ok := l.symsByName[ver][name]; ok {
    
    			if l.flags&FlagStrictDups != 0 {
    				l.checkdup(name, i, r, oldi)
    			}
    
    		oldr, li := l.toLocal(oldi)
    		oldsym := goobj2.Sym{}
    		oldsym.Read(oldr.Reader, oldr.SymOff(li))
    		if oldsym.Dupok() {
    			return false
    		}
    
    		overwrite := r.DataSize(int(i-l.startIndex(r))) != 0
    
    		if overwrite {
    			// new symbol overwrites old symbol.
    			oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type)]
    
    			if !oldtyp.IsData() && r.DataSize(li) == 0 {
    
    				log.Fatalf("duplicated definition of symbol " + name)
    			}
    			l.overwrite[oldi] = i
    		} else {
    			// old symbol overwrites new symbol.
    			if typ != sym.SDATA && typ != sym.SNOPTRDATA && typ != sym.SBSS && typ != sym.SNOPTRBSS { // only allow overwriting data symbol
    				log.Fatalf("duplicated definition of symbol " + name)
    			}
    			l.overwrite[i] = oldi
    
    	l.symsByName[ver][name] = i
    
    // newExtSym creates a new external sym with the specified
    // name/version.
    func (l *Loader) newExtSym(name string, ver int) Sym {
    	l.max++
    	i := l.max
    	if l.extStart == 0 {
    		l.extStart = i
    	}
    	l.growSyms(int(i))
    	pi := i - l.extStart
    	l.payloads[pi].name = name
    	l.payloads[pi].ver = ver
    	return i
    }
    
    
    // Add an external symbol (without index). Return the index of newly added
    // symbol, or 0 if not added.
    
    func (l *Loader) AddExtSym(name string, ver int) Sym {
    
    	i := l.Lookup(name, ver)
    	if i != 0 {
    		return 0
    	}
    	i = l.newExtSym(name, ver)
    	static := ver >= sym.SymVerStatic || ver < 0
    
    		l.extStaticSyms[nameVer{name, ver}] = i
    
    	return i
    }
    
    // LookupOrCreateSym looks up the symbol with the specified name/version,
    // returning its Sym index if found. If the lookup fails, a new external
    // Sym will be created, entered into the lookup tables, and returned.
    func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
    	i := l.Lookup(name, ver)
    	if i != 0 {
    		return i
    	}
    	i = l.newExtSym(name, ver)
    	static := ver >= sym.SymVerStatic || ver < 0
    
    	if static {
    		l.extStaticSyms[nameVer{name, ver}] = i
    	} else {
    		l.symsByName[ver][name] = i
    	}
    
    func (l *Loader) IsExternal(i Sym) bool {
    
    	return l.extStart != 0 && i >= l.extStart
    }
    
    
    // getPayload returns a pointer to the extSymPayload struct for an
    // external symbol if the symbol has a payload, or nil if the
    // data for the sym is being stored in a sym.Symbol. Will panic if
    // the symbol in question is bogus (zero or not an external sym).
    func (l *Loader) getPayload(i Sym) *extSymPayload {
    	if l.extStart == 0 || i < l.extStart {
    		panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
    	}
    	if l.Syms[i] != nil {
    		return nil
    	}
    	pi := i - l.extStart
    	return &l.payloads[pi]
    }
    
    
    // Ensure Syms slice has enough space.
    
    func (l *Loader) growSyms(i int) {
    	n := len(l.Syms)
    	if n > i {
    		return
    	}
    	l.Syms = append(l.Syms, make([]*sym.Symbol, i+1-n)...)
    
    	l.payloads = append(l.payloads, make([]extSymPayload, i+1-n)...)
    	l.growReachable(int(i))
    
    // Convert a local index to a global index.
    
    func (l *Loader) toGlobal(r *oReader, i int) Sym {
    	g := l.startIndex(r) + Sym(i)
    
    	if ov, ok := l.overwrite[g]; ok {
    		return ov
    	}
    	return g
    
    // Convert a global index to a local index.
    
    func (l *Loader) toLocal(i Sym) (*oReader, int) {
    
    	if ov, ok := l.overwrite[i]; ok {
    		i = ov
    	}
    
    		return nil, int(i - l.extStart)
    
    	oc := l.ocache
    	if oc != 0 && i >= l.objs[oc].i && i <= l.objs[oc].e {
    		return l.objs[oc].r, int(i - l.objs[oc].i)
    	}
    
    	// Search for the local object holding index i.
    	// Below k is the first one that has its start index > i,
    	// so k-1 is the one we want.
    	k := sort.Search(len(l.objs), func(k int) bool {
    		return l.objs[k].i > i
    	})
    
    	return l.objs[k-1].r, int(i - l.objs[k-1].i)
    
    // rcacheGet checks for a valid entry for 's' in the readers cache,
    // where 's' is a local PkgIdxNone ref or def, or zero if
    // the cache is empty or doesn't contain a value for 's'.
    func (or *oReader) rcacheGet(symIdx uint32) Sym {
    	if len(or.rcache) > 0 {
    		return or.rcache[symIdx]
    	}
    	return 0
    }
    
    // rcacheSet installs a new entry in the oReader's PkgNone
    // resolver cache for the specified PkgIdxNone ref or def,
    // allocating a new cache if needed.
    func (or *oReader) rcacheSet(symIdx uint32, gsym Sym) {
    	if len(or.rcache) == 0 {
    		or.rcache = make([]Sym, or.NNonpkgdef()+or.NNonpkgref())
    	}
    	or.rcache[symIdx] = gsym
    }
    
    
    // Resolve a local symbol reference. Return global index.
    
    func (l *Loader) resolve(r *oReader, s goobj2.SymRef) Sym {
    
    	var rr *oReader
    	switch p := s.PkgIdx; p {
    	case goobj2.PkgIdxInvalid:
    		if s.SymIdx != 0 {
    			panic("bad sym ref")
    		}
    		return 0
    	case goobj2.PkgIdxNone:
    
    		// Check for cached version first
    		if cached := r.rcacheGet(s.SymIdx); cached != 0 {
    			return cached
    		}
    
    		// Resolve by name
    		i := int(s.SymIdx) + r.NSym()
    		osym := goobj2.Sym{}
    		osym.Read(r.Reader, r.SymOff(i))
    		name := strings.Replace(osym.Name, "\"\".", r.pkgprefix, -1)
    		v := abiToVer(osym.ABI, r.version)
    
    		gsym := l.Lookup(name, v)
    		// Add to cache, then return.
    		r.rcacheSet(s.SymIdx, gsym)
    		return gsym
    
    		return l.builtinSyms[s.SymIdx]
    
    	case goobj2.PkgIdxSelf:
    		rr = r
    	default:
    		pkg := r.Pkg(int(p))
    
    		var ok bool
    		rr, ok = l.objByPkg[pkg]
    		if !ok {
    			log.Fatalf("reference of nonexisted package %s, from %v", pkg, r.unit.Lib)
    		}
    
    	return l.toGlobal(rr, int(s.SymIdx))
    
    // Look up a symbol by name, return global index, or 0 if not found.
    // This is more like Syms.ROLookup than Lookup -- it doesn't create
    // new symbol.
    
    func (l *Loader) Lookup(name string, ver int) Sym {
    
    	if ver >= sym.SymVerStatic || ver < 0 {
    
    		return l.extStaticSyms[nameVer{name, ver}]
    	}
    	return l.symsByName[ver][name]
    
    // Returns whether i is a dup of another symbol, and i is not
    // "primary", i.e. Lookup i by name will not return i.
    func (l *Loader) IsDup(i Sym) bool {
    	if _, ok := l.overwrite[i]; ok {
    		return true
    	}
    
    		return false
    	}
    	r, li := l.toLocal(i)
    	osym := goobj2.Sym{}
    	osym.Read(r.Reader, r.SymOff(li))
    	if !osym.Dupok() {
    		return false
    	}
    	if osym.Name == "" {
    
    		return false // Unnamed aux symbol cannot be dup.
    	}
    	if osym.ABI == goobj2.SymABIstatic {
    		return false // Static symbol cannot be dup.
    
    	}
    	name := strings.Replace(osym.Name, "\"\".", r.pkgprefix, -1)
    	ver := abiToVer(osym.ABI, r.version)
    
    	return l.symsByName[ver][name] != i
    
    // Check that duplicate symbols have same contents.
    func (l *Loader) checkdup(name string, i Sym, r *oReader, dup Sym) {
    	li := int(i - l.startIndex(r))
    	p := r.Data(li)
    	if strings.HasPrefix(name, "go.info.") {
    		p, _ = patchDWARFName1(p, r)
    	}
    	rdup, ldup := l.toLocal(dup)
    	pdup := rdup.Data(ldup)
    	if strings.HasPrefix(name, "go.info.") {
    		pdup, _ = patchDWARFName1(pdup, rdup)
    	}
    	if bytes.Equal(p, pdup) {
    		return
    	}
    	reason := "same length but different contents"
    	if len(p) != len(pdup) {
    		reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
    	}
    	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)
    
    	// For the moment, whitelist DWARF subprogram DIEs for
    	// auto-generated wrapper functions. What seems to happen
    	// here is that we get different line numbers on formal
    	// params; I am guessing that the pos is being inherited
    	// from the spot where the wrapper is needed.
    	whitelist := strings.HasPrefix(name, "go.info.go.interface") ||
    		strings.HasPrefix(name, "go.info.go.builtin") ||
    		strings.HasPrefix(name, "go.debuglines")
    	if !whitelist {
    		l.strictDupMsgs++
    	}
    }
    
    func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
    
    
    // Number of total symbols.
    func (l *Loader) NSym() int {
    	return int(l.max + 1)
    }
    
    
    // Number of defined Go symbols.
    func (l *Loader) NDef() int {
    	return int(l.extStart)
    }
    
    
    // Returns the raw (unpatched) name of the i-th symbol.
    func (l *Loader) RawSymName(i Sym) string {
    
    		if s := l.Syms[i]; s != nil {
    			return s.Name
    		}
    
    	osym := goobj2.Sym{}
    	osym.Read(r.Reader, r.SymOff(li))
    	return osym.Name
    }
    
    // Returns the (patched) name of the i-th symbol.
    func (l *Loader) SymName(i Sym) string {
    
    		if s := l.Syms[i]; s != nil {
    			return s.Name // external name should already be patched?
    		}
    
    	osym := goobj2.Sym{}
    	osym.Read(r.Reader, r.SymOff(li))
    	return strings.Replace(osym.Name, "\"\".", r.pkgprefix, -1)
    }
    
    // Returns the type of the i-th symbol.
    func (l *Loader) SymType(i Sym) sym.SymKind {
    
    		if s := l.Syms[i]; s != nil {
    			return s.Type
    		}
    
    		pp := l.getPayload(i)
    		if pp != nil {
    			return pp.kind
    		}
    
    	osym := goobj2.Sym{}
    	osym.Read(r.Reader, r.SymOff(li))
    	return sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type)]
    }
    
    
    // Returns the attributes of the i-th symbol.
    func (l *Loader) SymAttr(i Sym) uint8 {
    
    		// TODO: do something? External symbols have different representation of attributes. For now, ReflectMethod is the only thing matters and it cannot be set by external symbol.
    
    	osym := goobj2.Sym{}
    	osym.Read(r.Reader, r.SymOff(li))
    	return osym.Flag
    }
    
    // Returns whether the i-th symbol has ReflectMethod attribute set.
    func (l *Loader) IsReflectMethod(i Sym) bool {
    	return l.SymAttr(i)&goobj2.SymFlagReflectMethod != 0
    }
    
    
    // Returns whether this is a Go type symbol.
    func (l *Loader) IsGoType(i Sym) bool {
    	return l.SymAttr(i)&goobj2.SymFlagGoType != 0
    }
    
    
    // Returns whether this is a "go.itablink.*" symbol.
    func (l *Loader) IsItabLink(i Sym) bool {
    	if _, ok := l.itablink[i]; ok {
    		return true
    	}
    	return false
    }
    
    
    // Returns the symbol content of the i-th symbol. i is global index.
    func (l *Loader) Data(i Sym) []byte {
    
    		if s := l.Syms[i]; s != nil {
    			return s.P
    		}
    
    		pp := l.getPayload(i)
    		if pp != nil {
    			return pp.data
    		}
    
    // Returns the number of aux symbols given a global index.
    func (l *Loader) NAux(i Sym) int {
    
    	return r.NAux(li)
    }
    
    // Returns the referred symbol of the j-th aux symbol of the i-th
    // symbol.
    func (l *Loader) AuxSym(i Sym, j int) Sym {
    
    	a := goobj2.Aux{}
    	a.Read(r.Reader, r.AuxOff(li, j))
    
    // ReadAuxSyms reads the aux symbol ids for the specified symbol into the
    // slice passed as a parameter. If the slice capacity is not large enough, a new
    // larger slice will be allocated. Final slice is returned.
    func (l *Loader) ReadAuxSyms(symIdx Sym, dst []Sym) []Sym {
    
    	if l.IsExternal(symIdx) {
    
    		return dst[:0]
    	}
    	naux := l.NAux(symIdx)
    	if naux == 0 {
    		return dst[:0]
    	}
    
    	if cap(dst) < naux {
    		dst = make([]Sym, naux)
    	}
    	dst = dst[:0]
    
    	r, li := l.toLocal(symIdx)
    	for i := 0; i < naux; i++ {
    		a := goobj2.Aux{}
    		a.Read(r.Reader, r.AuxOff(li, i))
    		dst = append(dst, l.resolve(r, a.Sym))
    	}
    
    	return dst
    }
    
    
    // OuterSym gets the outer symbol for host object loaded symbols.
    func (l *Loader) OuterSym(i Sym) Sym {
    	sym := l.Syms[i]
    	if sym != nil && sym.Outer != nil {
    		outer := sym.Outer
    		return l.Lookup(outer.Name, int(outer.Version))
    	}
    	return 0
    }
    
    
    // SubSym gets the subsymbol for host object loaded symbols.
    
    func (l *Loader) SubSym(i Sym) Sym {
    	sym := l.Syms[i]
    	if sym != nil && sym.Sub != nil {
    		sub := sym.Sub
    		return l.Lookup(sub.Name, int(sub.Version))
    	}
    	return 0
    }
    
    
    // Initialize Reachable bitmap for running deadcode pass.
    func (l *Loader) InitReachable() {
    
    	l.growReachable(l.NSym())
    }
    
    // Insure that reachable bitmap has enough size.
    func (l *Loader) growReachable(reqLen int) {
    	if reqLen > l.Reachable.len() {
    		l.Reachable = growBitmap(reqLen, l.Reachable)
    	}
    
    // At method returns the j-th reloc for a global symbol.
    func (relocs *Relocs) At(j int) Reloc {
    
    	if s := relocs.l.Syms[relocs.extIdx]; s != nil {
    		rel := s.R[j]
    
    		return Reloc{
    			Off:  rel.Off,
    			Size: rel.Siz,
    			Type: rel.Type,
    			Add:  rel.Add,
    			Sym:  relocs.l.Lookup(rel.Sym.Name, int(rel.Sym.Version)),
    		}
    	}
    
    	if relocs.extIdx != 0 {
    		pp := relocs.l.getPayload(relocs.extIdx)
    		return pp.relocs[j]
    	}
    
    	rel := goobj2.Reloc{}
    	rel.Read(relocs.r.Reader, relocs.r.RelocOff(relocs.li, j))
    
    	target := relocs.l.resolve(relocs.r, rel.Sym)
    
    	return Reloc{
    		Off:  rel.Off,
    		Size: rel.Siz,
    		Type: objabi.RelocType(rel.Type),
    		Add:  rel.Add,
    		Sym:  target,
    	}
    }
    
    
    // ReadAll method reads all relocations for a symbol into the
    // specified slice. If the slice capacity is not large enough, a new
    // larger slice will be allocated. Final slice is returned.
    func (relocs *Relocs) ReadAll(dst []Reloc) []Reloc {
    	if relocs.Count == 0 {
    
    	}
    
    	if cap(dst) < relocs.Count {
    		dst = make([]Reloc, relocs.Count)
    	}
    	dst = dst[:0]
    
    
    	if s := relocs.l.Syms[relocs.extIdx]; s != nil {
    
    		for i := 0; i < relocs.Count; i++ {
    
    			rel := Reloc{
    				Off:  erel.Off,
    				Size: erel.Siz,
    				Type: erel.Type,
    				Add:  erel.Add,
    				Sym:  relocs.l.Lookup(erel.Sym.Name, int(erel.Sym.Version)),
    			}
    			dst = append(dst, rel)
    		}
    		return dst
    	}
    
    
    	if relocs.extIdx != 0 {
    		pp := relocs.l.getPayload(relocs.extIdx)
    		dst = append(dst, pp.relocs...)
    		return dst
    	}
    
    
    	off := relocs.r.RelocOff(relocs.li, 0)
    	for i := 0; i < relocs.Count; i++ {
    		rel := goobj2.Reloc{}
    		rel.Read(relocs.r.Reader, off)
    		off += uint32(rel.Size())
    		target := relocs.l.resolve(relocs.r, rel.Sym)
    		dst = append(dst, Reloc{
    			Off:  rel.Off,
    			Size: rel.Siz,
    			Type: objabi.RelocType(rel.Type),
    			Add:  rel.Add,
    			Sym:  target,
    		})
    	}
    	return dst
    }
    
    
    // Relocs returns a Relocs object for the given global sym.
    func (l *Loader) Relocs(i Sym) Relocs {
    
    			return Relocs{Count: len(s.R), l: l, extIdx: i}
    		}
    		pp := l.getPayload(i)
    		if pp != nil {
    			return Relocs{Count: len(pp.relocs), l: l, extIdx: i}
    
    	if r == nil {
    		panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
    	}
    
    	return l.relocs(r, li)
    }
    
    // Relocs returns a Relocs object given a local sym index and reader.
    func (l *Loader) relocs(r *oReader, li int) Relocs {
    	return Relocs{
    		Count: r.NReloc(li),
    		li:    li,
    		r:     r,
    		l:     l,
    	}
    }
    
    
    // Preload a package: add autolibs, add symbols to the symbol table.
    // Does not read symbol data yet.
    
    func (l *Loader) Preload(arch *sys.Arch, syms *sym.Symbols, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64, pn string, flags int) {
    
    	roObject, readonly, err := f.Slice(uint64(length))
    	if err != nil {
    		log.Fatal("cannot read object file:", err)
    	}
    	r := goobj2.NewReaderFromBytes(roObject, readonly)
    
    	if r == nil {
    		panic("cannot read object file")
    	}
    	localSymVersion := syms.IncVersion()
    	pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
    
    	or := &oReader{r, unit, localSymVersion, r.Flags(), pkgprefix, nil}
    
    	lib.ImportStrings = append(lib.ImportStrings, r.Autolib()...)
    
    	// DWARF file table
    	nfile := r.NDwarfFile()
    	unit.DWARFFileTable = make([]string, nfile)
    	for i := range unit.DWARFFileTable {
    		unit.DWARFFileTable[i] = r.DwarfFile(i)
    	}
    
    
    
    	ndef := r.NSym()
    	nnonpkgdef := r.NNonpkgdef()
    	for i, n := 0, ndef+nnonpkgdef; i < n; i++ {
    		osym := goobj2.Sym{}
    		osym.Read(r, r.SymOff(i))
    		name := strings.Replace(osym.Name, "\"\".", pkgprefix, -1)
    		if name == "" {
    			continue // don't add unnamed aux symbol
    		}
    		v := abiToVer(osym.ABI, localSymVersion)
    
    		added := l.AddSym(name, v, istart+Sym(i), or, dupok, sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type)])
    		if added && strings.HasPrefix(name, "go.itablink.") {
    			l.itablink[istart+Sym(i)] = struct{}{}
    		}
    
    		if added && strings.HasPrefix(name, "runtime.") {
    			if bi := goobj2.BuiltinIdx(name, v); bi != -1 {
    				// This is a definition of a builtin symbol. Record where it is.
    				l.builtinSyms[bi] = istart + Sym(i)
    			}
    		}
    
    	}
    
    	// The caller expects us consuming all the data
    	f.MustSeek(length, os.SEEK_CUR)
    }
    
    // Make sure referenced symbols are added. Most of them should already be added.
    // This should only be needed for referenced external symbols.
    
    func (l *Loader) LoadRefs(arch *sys.Arch, syms *sym.Symbols) {
    
    	for _, o := range l.objs[1:] {
    		loadObjRefs(l, o.r, arch, syms)
    	}
    }
    
    func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch, syms *sym.Symbols) {
    
    	ndef := r.NSym() + r.NNonpkgdef()
    	for i, n := 0, r.NNonpkgref(); i < n; i++ {
    		osym := goobj2.Sym{}
    
    		name := strings.Replace(osym.Name, "\"\".", r.pkgprefix, -1)
    
    	}
    }
    
    func abiToVer(abi uint16, localSymVersion int) int {
    	var v int
    	if abi == goobj2.SymABIstatic {
    		// Static
    		v = localSymVersion
    	} else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
    		// Note that data symbols are "ABI0", which maps to version 0.
    		v = abiver
    	} else {
    		log.Fatalf("invalid symbol ABI: %d", abi)
    	}
    	return v
    }
    
    func preprocess(arch *sys.Arch, s *sym.Symbol) {
    	if s.Name != "" && s.Name[0] == '$' && len(s.Name) > 5 && s.Type == 0 && len(s.P) == 0 {
    		x, err := strconv.ParseUint(s.Name[5:], 16, 64)
    		if err != nil {
    			log.Panicf("failed to parse $-symbol %s: %v", s.Name, err)
    		}
    		s.Type = sym.SRODATA
    		s.Attr |= sym.AttrLocal
    		switch s.Name[:5] {
    		case "$f32.":
    			if uint64(uint32(x)) != x {
    				log.Panicf("$-symbol %s too large: %d", s.Name, x)
    			}
    			s.AddUint32(arch, uint32(x))
    		case "$f64.", "$i64.":
    			s.AddUint64(arch, x)
    		default:
    			log.Panicf("unrecognized $-symbol: %s", s.Name)
    		}
    	}
    }
    
    
    func (l *Loader) LoadFull(arch *sys.Arch, syms *sym.Symbols) {
    
    
    	nr := 0 // total number of sym.Reloc's we'll need
    
    		nr += loadObjSyms(l, syms, o.r)
    
    	// allocate a single large slab of relocations for all live symbols
    	l.relocBatch = make([]sym.Reloc, nr)
    
    
    	// external symbols
    	for i := l.extStart; i <= l.max; i++ {
    
    		if s := l.Syms[i]; s != nil {
    			s.Attr.Set(sym.AttrReachable, l.Reachable.Has(i))
    			continue // already loaded from external object
    		}
    
    		sname := l.payloads[i-l.extStart].name
    		sver := l.payloads[i-l.extStart].ver
    		if l.Reachable.Has(i) || strings.HasPrefix(sname, "gofile..") { // XXX file symbols are used but not marked
    			s := l.allocSym(sname, sver)
    			pp := l.getPayload(i)
    			if pp != nil {
    				if pp.kind != sym.Sxxx || len(pp.relocs) != 0 || len(pp.data) != 0 {
    					// Unpack payload into sym. Currently there is nothing
    					// to do here, but eventually we'll need a real
    					// implementation.
    					panic("need to handle this")
    				}
    			}
    
    			s.Attr.Set(sym.AttrReachable, l.Reachable.Has(i))
    
    
    	// Resolve ABI aliases for external symbols. This is only
    	// needed for internal cgo linking.
    	// (The old code does this in deadcode, but deadcode2 doesn't
    	// do this.)
    	for i := l.extStart; i <= l.max; i++ {
    		if s := l.Syms[i]; s != nil && s.Attr.Reachable() {
    			for ri := range s.R {
    				r := &s.R[ri]
    				if r.Sym != nil && r.Sym.Type == sym.SABIALIAS {
    					r.Sym = r.Sym.R[0].Sym
    				}
    			}
    		}
    	}
    
    // ExtractSymbols grabs the symbols out of the loader for work that hasn't been
    // ported to the new symbol type.
    func (l *Loader) ExtractSymbols(syms *sym.Symbols) {
    	// Nil out overwritten symbols.
    	// Overwritten Go symbols aren't a problem (as they're lazy loaded), but
    	// symbols loaded from host object loaders are fully loaded, and we might
    	// have multiple symbols with the same name. This loop nils them out.
    	for oldI := range l.overwrite {
    		l.Syms[oldI] = nil
    	}
    
    
    	// Add symbols to the ctxt.Syms lookup table. This explicitly skips things
    	// created via loader.Create (marked with versions less than zero), since
    	// if we tried to add these we'd wind up with collisions. We do, however,
    	// add these symbols to the list of global symbols so that other future
    	// steps (like pclntab generation) can find these symbols if neceassary.
    	// Along the way, update the version from the negative anon version to
    	// something larger than sym.SymVerStatic (needed so that
    	// sym.symbol.IsFileLocal() works properly).
    
    	anonVerReplacement := syms.IncVersion()
    
    	for _, s := range l.Syms {