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