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