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