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