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