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