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