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