]> 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() []byte {
1882         pcsp, end := (*goobj.FuncInfo)(nil).ReadPcsp(fi.data)
1883         return fi.r.BytesAt(fi.r.PcdataBase()+pcsp, int(end-pcsp))
1884 }
1885
1886 func (fi *FuncInfo) Pcfile() []byte {
1887         pcf, end := (*goobj.FuncInfo)(nil).ReadPcfile(fi.data)
1888         return fi.r.BytesAt(fi.r.PcdataBase()+pcf, int(end-pcf))
1889 }
1890
1891 func (fi *FuncInfo) Pcline() []byte {
1892         pcln, end := (*goobj.FuncInfo)(nil).ReadPcline(fi.data)
1893         return fi.r.BytesAt(fi.r.PcdataBase()+pcln, int(end-pcln))
1894 }
1895
1896 // Preload has to be called prior to invoking the various methods
1897 // below related to pcdata, funcdataoff, files, and inltree nodes.
1898 func (fi *FuncInfo) Preload() {
1899         fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
1900 }
1901
1902 func (fi *FuncInfo) Pcinline() []byte {
1903         if !fi.lengths.Initialized {
1904                 panic("need to call Preload first")
1905         }
1906         pcinl, end := (*goobj.FuncInfo)(nil).ReadPcinline(fi.data, fi.lengths.PcdataOff)
1907         return fi.r.BytesAt(fi.r.PcdataBase()+pcinl, int(end-pcinl))
1908 }
1909
1910 func (fi *FuncInfo) NumPcdata() uint32 {
1911         if !fi.lengths.Initialized {
1912                 panic("need to call Preload first")
1913         }
1914         return fi.lengths.NumPcdata
1915 }
1916
1917 func (fi *FuncInfo) Pcdata(k int) []byte {
1918         if !fi.lengths.Initialized {
1919                 panic("need to call Preload first")
1920         }
1921         pcdat, end := (*goobj.FuncInfo)(nil).ReadPcdata(fi.data, fi.lengths.PcdataOff, uint32(k))
1922         return fi.r.BytesAt(fi.r.PcdataBase()+pcdat, int(end-pcdat))
1923 }
1924
1925 func (fi *FuncInfo) NumFuncdataoff() uint32 {
1926         if !fi.lengths.Initialized {
1927                 panic("need to call Preload first")
1928         }
1929         return fi.lengths.NumFuncdataoff
1930 }
1931
1932 func (fi *FuncInfo) Funcdataoff(k int) int64 {
1933         if !fi.lengths.Initialized {
1934                 panic("need to call Preload first")
1935         }
1936         return (*goobj.FuncInfo)(nil).ReadFuncdataoff(fi.data, fi.lengths.FuncdataoffOff, uint32(k))
1937 }
1938
1939 func (fi *FuncInfo) Funcdata(syms []Sym) []Sym {
1940         if !fi.lengths.Initialized {
1941                 panic("need to call Preload first")
1942         }
1943         if int(fi.lengths.NumFuncdataoff) > cap(syms) {
1944                 syms = make([]Sym, 0, fi.lengths.NumFuncdataoff)
1945         } else {
1946                 syms = syms[:0]
1947         }
1948         for j := range fi.auxs {
1949                 a := &fi.auxs[j]
1950                 if a.Type() == goobj.AuxFuncdata {
1951                         syms = append(syms, fi.l.resolve(fi.r, a.Sym()))
1952                 }
1953         }
1954         return syms
1955 }
1956
1957 func (fi *FuncInfo) NumFile() uint32 {
1958         if !fi.lengths.Initialized {
1959                 panic("need to call Preload first")
1960         }
1961         return fi.lengths.NumFile
1962 }
1963
1964 func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
1965         if !fi.lengths.Initialized {
1966                 panic("need to call Preload first")
1967         }
1968         return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
1969 }
1970
1971 type InlTreeNode struct {
1972         Parent   int32
1973         File     goobj.CUFileIndex
1974         Line     int32
1975         Func     Sym
1976         ParentPC int32
1977 }
1978
1979 func (fi *FuncInfo) NumInlTree() uint32 {
1980         if !fi.lengths.Initialized {
1981                 panic("need to call Preload first")
1982         }
1983         return fi.lengths.NumInlTree
1984 }
1985
1986 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
1987         if !fi.lengths.Initialized {
1988                 panic("need to call Preload first")
1989         }
1990         node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
1991         return InlTreeNode{
1992                 Parent:   node.Parent,
1993                 File:     node.File,
1994                 Line:     node.Line,
1995                 Func:     fi.l.resolve(fi.r, node.Func),
1996                 ParentPC: node.ParentPC,
1997         }
1998 }
1999
2000 func (l *Loader) FuncInfo(i Sym) FuncInfo {
2001         var r *oReader
2002         var auxs []goobj.Aux
2003         if l.IsExternal(i) {
2004                 pp := l.getPayload(i)
2005                 if pp.objidx == 0 {
2006                         return FuncInfo{}
2007                 }
2008                 r = l.objs[pp.objidx].r
2009                 auxs = pp.auxs
2010         } else {
2011                 var li uint32
2012                 r, li = l.toLocal(i)
2013                 auxs = r.Auxs(li)
2014         }
2015         for j := range auxs {
2016                 a := &auxs[j]
2017                 if a.Type() == goobj.AuxFuncInfo {
2018                         b := r.Data(a.Sym().SymIdx)
2019                         return FuncInfo{l, r, b, auxs, goobj.FuncInfoLengths{}}
2020                 }
2021         }
2022         return FuncInfo{}
2023 }
2024
2025 // Preload a package: add autolibs, add defined package symbols to the symbol table.
2026 // Does not add non-package symbols yet, which will be done in LoadNonpkgSyms.
2027 // Does not read symbol data.
2028 // Returns the fingerprint of the object.
2029 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
2030         roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
2031         if err != nil {
2032                 log.Fatal("cannot read object file:", err)
2033         }
2034         r := goobj.NewReaderFromBytes(roObject, readonly)
2035         if r == nil {
2036                 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
2037                         log.Fatalf("found object file %s in old format", f.File().Name())
2038                 }
2039                 panic("cannot read object file")
2040         }
2041         pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
2042         ndef := r.NSym()
2043         nhashed64def := r.NHashed64def()
2044         nhasheddef := r.NHasheddef()
2045         or := &oReader{
2046                 Reader:       r,
2047                 unit:         unit,
2048                 version:      localSymVersion,
2049                 flags:        r.Flags(),
2050                 pkgprefix:    pkgprefix,
2051                 syms:         make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
2052                 ndef:         ndef,
2053                 nhasheddef:   nhasheddef,
2054                 nhashed64def: nhashed64def,
2055                 objidx:       uint32(len(l.objs)),
2056         }
2057
2058         // Autolib
2059         lib.Autolib = append(lib.Autolib, r.Autolib()...)
2060
2061         // DWARF file table
2062         nfile := r.NFile()
2063         unit.FileTable = make([]string, nfile)
2064         for i := range unit.FileTable {
2065                 unit.FileTable[i] = r.File(i)
2066         }
2067
2068         l.addObj(lib.Pkg, or)
2069         st := loadState{l: l}
2070         st.preloadSyms(or, pkgDef)
2071
2072         // The caller expects us consuming all the data
2073         f.MustSeek(length, os.SEEK_CUR)
2074
2075         return r.Fingerprint()
2076 }
2077
2078 // Holds the loader along with temporary states for loading symbols.
2079 type loadState struct {
2080         l            *Loader
2081         hashed64Syms map[uint64]symAndSize         // short hashed (content-addressable) symbols, keyed by content hash
2082         hashedSyms   map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
2083 }
2084
2085 // Preload symbols of given kind from an object.
2086 func (st *loadState) preloadSyms(r *oReader, kind int) {
2087         l := st.l
2088         var start, end uint32
2089         switch kind {
2090         case pkgDef:
2091                 start = 0
2092                 end = uint32(r.ndef)
2093         case hashed64Def:
2094                 start = uint32(r.ndef)
2095                 end = uint32(r.ndef + r.nhashed64def)
2096         case hashedDef:
2097                 start = uint32(r.ndef + r.nhashed64def)
2098                 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2099                 if l.hasUnknownPkgPath {
2100                         // The content hash depends on symbol name expansion. If any package is
2101                         // built without fully expanded names, the content hash is unreliable.
2102                         // Treat them as named symbols.
2103                         // This is rare.
2104                         // (We don't need to do this for hashed64Def case, as there the hash
2105                         // function is simply the identity function, which doesn't depend on
2106                         // name expansion.)
2107                         kind = nonPkgDef
2108                 }
2109         case nonPkgDef:
2110                 start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2111                 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
2112         default:
2113                 panic("preloadSyms: bad kind")
2114         }
2115         l.growAttrBitmaps(len(l.objSyms) + int(end-start))
2116         needNameExpansion := r.NeedNameExpansion()
2117         loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
2118         for i := start; i < end; i++ {
2119                 osym := r.Sym(i)
2120                 var name string
2121                 var v int
2122                 if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
2123                         name = osym.Name(r.Reader)
2124                         if needNameExpansion {
2125                                 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2126                         }
2127                         v = abiToVer(osym.ABI(), r.version)
2128                 }
2129                 gi := st.addSym(name, v, r, i, kind, osym)
2130                 r.syms[i] = gi
2131                 if osym.TopFrame() {
2132                         l.SetAttrTopFrame(gi, true)
2133                 }
2134                 if osym.Local() {
2135                         l.SetAttrLocal(gi, true)
2136                 }
2137                 if osym.UsedInIface() {
2138                         l.SetAttrUsedInIface(gi, true)
2139                 }
2140                 if strings.HasPrefix(name, "runtime.") ||
2141                         (loadingRuntimePkg && strings.HasPrefix(name, "type.")) {
2142                         if bi := goobj.BuiltinIdx(name, v); bi != -1 {
2143                                 // This is a definition of a builtin symbol. Record where it is.
2144                                 l.builtinSyms[bi] = gi
2145                         }
2146                 }
2147                 if a := int32(osym.Align()); a != 0 && a > l.SymAlign(gi) {
2148                         l.SetSymAlign(gi, a)
2149                 }
2150         }
2151 }
2152
2153 // Add hashed (content-addressable) symbols, non-package symbols, and
2154 // references to external symbols (which are always named).
2155 func (l *Loader) LoadNonpkgSyms(arch *sys.Arch) {
2156         l.npkgsyms = l.NSym()
2157         // Preallocate some space (a few hundreds KB) for some symbols.
2158         // As of Go 1.15, linking cmd/compile has ~8000 hashed64 symbols and
2159         // ~13000 hashed symbols.
2160         st := loadState{
2161                 l:            l,
2162                 hashed64Syms: make(map[uint64]symAndSize, 10000),
2163                 hashedSyms:   make(map[goobj.HashType]symAndSize, 15000),
2164         }
2165         for _, o := range l.objs[goObjStart:] {
2166                 st.preloadSyms(o.r, hashed64Def)
2167                 st.preloadSyms(o.r, hashedDef)
2168                 st.preloadSyms(o.r, nonPkgDef)
2169         }
2170         l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
2171         for _, o := range l.objs[goObjStart:] {
2172                 loadObjRefs(l, o.r, arch)
2173         }
2174         l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2175 }
2176
2177 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2178         // load non-package refs
2179         ndef := uint32(r.NAlldef())
2180         needNameExpansion := r.NeedNameExpansion()
2181         for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2182                 osym := r.Sym(ndef + i)
2183                 name := osym.Name(r.Reader)
2184                 if needNameExpansion {
2185                         name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2186                 }
2187                 v := abiToVer(osym.ABI(), r.version)
2188                 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2189                 gi := r.syms[ndef+i]
2190                 if osym.Local() {
2191                         l.SetAttrLocal(gi, true)
2192                 }
2193                 if osym.UsedInIface() {
2194                         l.SetAttrUsedInIface(gi, true)
2195                 }
2196         }
2197
2198         // load flags of package refs
2199         for i, n := 0, r.NRefFlags(); i < n; i++ {
2200                 rf := r.RefFlags(i)
2201                 gi := l.resolve(r, rf.Sym())
2202                 if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
2203                         l.SetAttrUsedInIface(gi, true)
2204                 }
2205         }
2206 }
2207
2208 func abiToVer(abi uint16, localSymVersion int) int {
2209         var v int
2210         if abi == goobj.SymABIstatic {
2211                 // Static
2212                 v = localSymVersion
2213         } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2214                 // Note that data symbols are "ABI0", which maps to version 0.
2215                 v = abiver
2216         } else {
2217                 log.Fatalf("invalid symbol ABI: %d", abi)
2218         }
2219         return v
2220 }
2221
2222 // ResolveABIAlias given a symbol returns the ABI alias target of that
2223 // symbol. If the sym in question is not an alias, the sym itself is
2224 // returned.
2225 func (l *Loader) ResolveABIAlias(s Sym) Sym {
2226         if s == 0 {
2227                 return 0
2228         }
2229         if l.SymType(s) != sym.SABIALIAS {
2230                 return s
2231         }
2232         relocs := l.Relocs(s)
2233         target := relocs.At(0).Sym()
2234         if l.SymType(target) == sym.SABIALIAS {
2235                 panic(fmt.Sprintf("ABI alias %s references another ABI alias %s", l.SymName(s), l.SymName(target)))
2236         }
2237         return target
2238 }
2239
2240 // TopLevelSym tests a symbol (by name and kind) to determine whether
2241 // the symbol first class sym (participating in the link) or is an
2242 // anonymous aux or sub-symbol containing some sub-part or payload of
2243 // another symbol.
2244 func (l *Loader) TopLevelSym(s Sym) bool {
2245         return topLevelSym(l.RawSymName(s), l.SymType(s))
2246 }
2247
2248 // topLevelSym tests a symbol name and kind to determine whether
2249 // the symbol first class sym (participating in the link) or is an
2250 // anonymous aux or sub-symbol containing some sub-part or payload of
2251 // another symbol.
2252 func topLevelSym(sname string, skind sym.SymKind) bool {
2253         if sname != "" {
2254                 return true
2255         }
2256         switch skind {
2257         case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2258                 return true
2259         default:
2260                 return false
2261         }
2262 }
2263
2264 // cloneToExternal takes the existing object file symbol (symIdx)
2265 // and creates a new external symbol payload that is a clone with
2266 // respect to name, version, type, relocations, etc. The idea here
2267 // is that if the linker decides it wants to update the contents of
2268 // a symbol originally discovered as part of an object file, it's
2269 // easier to do this if we make the updates to an external symbol
2270 // payload.
2271 func (l *Loader) cloneToExternal(symIdx Sym) {
2272         if l.IsExternal(symIdx) {
2273                 panic("sym is already external, no need for clone")
2274         }
2275
2276         // Read the particulars from object.
2277         r, li := l.toLocal(symIdx)
2278         osym := r.Sym(li)
2279         sname := osym.Name(r.Reader)
2280         if r.NeedNameExpansion() {
2281                 sname = strings.Replace(sname, "\"\".", r.pkgprefix, -1)
2282         }
2283         sver := abiToVer(osym.ABI(), r.version)
2284         skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2285
2286         // Create new symbol, update version and kind.
2287         pi := l.newPayload(sname, sver)
2288         pp := l.payloads[pi]
2289         pp.kind = skind
2290         pp.ver = sver
2291         pp.size = int64(osym.Siz())
2292         pp.objidx = r.objidx
2293
2294         // If this is a def, then copy the guts. We expect this case
2295         // to be very rare (one case it may come up is with -X).
2296         if li < uint32(r.NAlldef()) {
2297
2298                 // Copy relocations
2299                 relocs := l.Relocs(symIdx)
2300                 pp.relocs = make([]goobj.Reloc, relocs.Count())
2301                 pp.reltypes = make([]objabi.RelocType, relocs.Count())
2302                 for i := range pp.relocs {
2303                         // Copy the relocs slice.
2304                         // Convert local reference to global reference.
2305                         rel := relocs.At(i)
2306                         pp.relocs[i].Set(rel.Off(), rel.Siz(), 0, rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2307                         pp.reltypes[i] = rel.Type()
2308                 }
2309
2310                 // Copy data
2311                 pp.data = r.Data(li)
2312         }
2313
2314         // If we're overriding a data symbol, collect the associated
2315         // Gotype, so as to propagate it to the new symbol.
2316         auxs := r.Auxs(li)
2317         pp.auxs = auxs
2318
2319         // Install new payload to global index space.
2320         // (This needs to happen at the end, as the accessors above
2321         // need to access the old symbol content.)
2322         l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2323         l.extReader.syms = append(l.extReader.syms, symIdx)
2324 }
2325
2326 // Copy the payload of symbol src to dst. Both src and dst must be external
2327 // symbols.
2328 // The intended use case is that when building/linking against a shared library,
2329 // where we do symbol name mangling, the Go object file may have reference to
2330 // the original symbol name whereas the shared library provides a symbol with
2331 // the mangled name. When we do mangling, we copy payload of mangled to original.
2332 func (l *Loader) CopySym(src, dst Sym) {
2333         if !l.IsExternal(dst) {
2334                 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2335         }
2336         if !l.IsExternal(src) {
2337                 panic("src is not external") //l.cloneToExternal(src)
2338         }
2339         l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2340         l.SetSymPkg(dst, l.SymPkg(src))
2341         // TODO: other attributes?
2342 }
2343
2344 // CopyAttributes copies over all of the attributes of symbol 'src' to
2345 // symbol 'dst'.
2346 func (l *Loader) CopyAttributes(src Sym, dst Sym) {
2347         l.SetAttrReachable(dst, l.AttrReachable(src))
2348         l.SetAttrOnList(dst, l.AttrOnList(src))
2349         l.SetAttrLocal(dst, l.AttrLocal(src))
2350         l.SetAttrNotInSymbolTable(dst, l.AttrNotInSymbolTable(src))
2351         if l.IsExternal(dst) {
2352                 l.SetAttrVisibilityHidden(dst, l.AttrVisibilityHidden(src))
2353                 l.SetAttrDuplicateOK(dst, l.AttrDuplicateOK(src))
2354                 l.SetAttrShared(dst, l.AttrShared(src))
2355                 l.SetAttrExternal(dst, l.AttrExternal(src))
2356         } else {
2357                 // Some attributes are modifiable only for external symbols.
2358                 // In such cases, don't try to transfer over the attribute
2359                 // from the source even if there is a clash. This comes up
2360                 // when copying attributes from a dupOK ABI wrapper symbol to
2361                 // the real target symbol (which may not be marked dupOK).
2362         }
2363         l.SetAttrTopFrame(dst, l.AttrTopFrame(src))
2364         l.SetAttrSpecial(dst, l.AttrSpecial(src))
2365         l.SetAttrCgoExportDynamic(dst, l.AttrCgoExportDynamic(src))
2366         l.SetAttrCgoExportStatic(dst, l.AttrCgoExportStatic(src))
2367         l.SetAttrReadOnly(dst, l.AttrReadOnly(src))
2368 }
2369
2370 // CreateExtSym creates a new external symbol with the specified name
2371 // without adding it to any lookup tables, returning a Sym index for it.
2372 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2373         return l.newExtSym(name, ver)
2374 }
2375
2376 // CreateStaticSym creates a new static symbol with the specified name
2377 // without adding it to any lookup tables, returning a Sym index for it.
2378 func (l *Loader) CreateStaticSym(name string) Sym {
2379         // Assign a new unique negative version -- this is to mark the
2380         // symbol so that it is not included in the name lookup table.
2381         l.anonVersion--
2382         return l.newExtSym(name, l.anonVersion)
2383 }
2384
2385 func (l *Loader) FreeSym(i Sym) {
2386         if l.IsExternal(i) {
2387                 pp := l.getPayload(i)
2388                 *pp = extSymPayload{}
2389         }
2390 }
2391
2392 // relocId is essentially a <S,R> tuple identifying the Rth
2393 // relocation of symbol S.
2394 type relocId struct {
2395         sym  Sym
2396         ridx int
2397 }
2398
2399 // SetRelocVariant sets the 'variant' property of a relocation on
2400 // some specific symbol.
2401 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2402         // sanity check
2403         if relocs := l.Relocs(s); ri >= relocs.Count() {
2404                 panic("invalid relocation ID")
2405         }
2406         if l.relocVariant == nil {
2407                 l.relocVariant = make(map[relocId]sym.RelocVariant)
2408         }
2409         if v != 0 {
2410                 l.relocVariant[relocId{s, ri}] = v
2411         } else {
2412                 delete(l.relocVariant, relocId{s, ri})
2413         }
2414 }
2415
2416 // RelocVariant returns the 'variant' property of a relocation on
2417 // some specific symbol.
2418 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2419         return l.relocVariant[relocId{s, ri}]
2420 }
2421
2422 // UndefinedRelocTargets iterates through the global symbol index
2423 // space, looking for symbols with relocations targeting undefined
2424 // references. The linker's loadlib method uses this to determine if
2425 // there are unresolved references to functions in system libraries
2426 // (for example, libgcc.a), presumably due to CGO code. Return
2427 // value is a list of loader.Sym's corresponding to the undefined
2428 // cross-refs. The "limit" param controls the maximum number of
2429 // results returned; if "limit" is -1, then all undefs are returned.
2430 func (l *Loader) UndefinedRelocTargets(limit int) []Sym {
2431         result := []Sym{}
2432         for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2433                 relocs := l.Relocs(si)
2434                 for ri := 0; ri < relocs.Count(); ri++ {
2435                         r := relocs.At(ri)
2436                         rs := r.Sym()
2437                         if rs != 0 && l.SymType(rs) == sym.SXREF && l.RawSymName(rs) != ".got" {
2438                                 result = append(result, rs)
2439                                 if limit != -1 && len(result) >= limit {
2440                                         break
2441                                 }
2442                         }
2443                 }
2444         }
2445         return result
2446 }
2447
2448 // AssignTextSymbolOrder populates the Textp slices within each
2449 // library and compilation unit, insuring that packages are laid down
2450 // in dependency order (internal first, then everything else). Return value
2451 // is a slice of all text syms.
2452 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2453
2454         // Library Textp lists should be empty at this point.
2455         for _, lib := range libs {
2456                 if len(lib.Textp) != 0 {
2457                         panic("expected empty Textp slice for library")
2458                 }
2459                 if len(lib.DupTextSyms) != 0 {
2460                         panic("expected empty DupTextSyms slice for library")
2461                 }
2462         }
2463
2464         // Used to record which dupok symbol we've assigned to a unit.
2465         // Can't use the onlist attribute here because it will need to
2466         // clear for the later assignment of the sym.Symbol to a unit.
2467         // NB: we can convert to using onList once we no longer have to
2468         // call the regular addToTextp.
2469         assignedToUnit := MakeBitmap(l.NSym() + 1)
2470
2471         // Start off textp with reachable external syms.
2472         textp := []Sym{}
2473         for _, sym := range extsyms {
2474                 if !l.attrReachable.Has(sym) {
2475                         continue
2476                 }
2477                 textp = append(textp, sym)
2478         }
2479
2480         // Walk through all text symbols from Go object files and append
2481         // them to their corresponding library's textp list.
2482         for _, o := range l.objs[goObjStart:] {
2483                 r := o.r
2484                 lib := r.unit.Lib
2485                 for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
2486                         gi := l.toGlobal(r, i)
2487                         if !l.attrReachable.Has(gi) {
2488                                 continue
2489                         }
2490                         osym := r.Sym(i)
2491                         st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2492                         if st != sym.STEXT {
2493                                 continue
2494                         }
2495                         dupok := osym.Dupok()
2496                         if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2497                                 // A dupok text symbol is resolved to another package.
2498                                 // We still need to record its presence in the current
2499                                 // package, as the trampoline pass expects packages
2500                                 // are laid out in dependency order.
2501                                 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2502                                 continue // symbol in different object
2503                         }
2504                         if dupok {
2505                                 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2506                                 continue
2507                         }
2508
2509                         lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2510                 }
2511         }
2512
2513         // Now assemble global textp, and assign text symbols to units.
2514         for _, doInternal := range [2]bool{true, false} {
2515                 for idx, lib := range libs {
2516                         if intlibs[idx] != doInternal {
2517                                 continue
2518                         }
2519                         lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2520                         for i, list := range lists {
2521                                 for _, s := range list {
2522                                         sym := Sym(s)
2523                                         if l.attrReachable.Has(sym) && !assignedToUnit.Has(sym) {
2524                                                 textp = append(textp, sym)
2525                                                 unit := l.SymUnit(sym)
2526                                                 if unit != nil {
2527                                                         unit.Textp = append(unit.Textp, s)
2528                                                         assignedToUnit.Set(sym)
2529                                                 }
2530                                                 // Dupok symbols may be defined in multiple packages; the
2531                                                 // associated package for a dupok sym is chosen sort of
2532                                                 // arbitrarily (the first containing package that the linker
2533                                                 // loads). Canonicalizes its Pkg to the package with which
2534                                                 // it will be laid down in text.
2535                                                 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2536                                                         l.SetSymPkg(sym, lib.Pkg)
2537                                                 }
2538                                         }
2539                                 }
2540                         }
2541                         lib.Textp = nil
2542                         lib.DupTextSyms = nil
2543                 }
2544         }
2545
2546         return textp
2547 }
2548
2549 // ErrorReporter is a helper class for reporting errors.
2550 type ErrorReporter struct {
2551         ldr              *Loader
2552         AfterErrorAction func()
2553 }
2554
2555 // Errorf method logs an error message.
2556 //
2557 // After each error, the error actions function will be invoked; this
2558 // will either terminate the link immediately (if -h option given)
2559 // or it will keep a count and exit if more than 20 errors have been printed.
2560 //
2561 // Logging an error means that on exit cmd/link will delete any
2562 // output file and return a non-zero error code.
2563 //
2564 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2565         if s != 0 && reporter.ldr.SymName(s) != "" {
2566                 format = reporter.ldr.SymName(s) + ": " + format
2567         } else {
2568                 format = fmt.Sprintf("sym %d: %s", s, format)
2569         }
2570         format += "\n"
2571         fmt.Fprintf(os.Stderr, format, args...)
2572         reporter.AfterErrorAction()
2573 }
2574
2575 // GetErrorReporter returns the loader's associated error reporter.
2576 func (l *Loader) GetErrorReporter() *ErrorReporter {
2577         return l.errorReporter
2578 }
2579
2580 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2581 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2582         l.errorReporter.Errorf(s, format, args...)
2583 }
2584
2585 // Symbol statistics.
2586 func (l *Loader) Stat() string {
2587         s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
2588         s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
2589                 l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
2590         return s
2591 }
2592
2593 // For debugging.
2594 func (l *Loader) Dump() {
2595         fmt.Println("objs")
2596         for _, obj := range l.objs[goObjStart:] {
2597                 if obj.r != nil {
2598                         fmt.Println(obj.i, obj.r.unit.Lib)
2599                 }
2600         }
2601         fmt.Println("extStart:", l.extStart)
2602         fmt.Println("Nsyms:", len(l.objSyms))
2603         fmt.Println("syms")
2604         for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2605                 pi := interface{}("")
2606                 if l.IsExternal(i) {
2607                         pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2608                 }
2609                 fmt.Println(i, l.SymName(i), l.SymType(i), pi)
2610         }
2611         fmt.Println("symsByName")
2612         for name, i := range l.symsByName[0] {
2613                 fmt.Println(i, name, 0)
2614         }
2615         for name, i := range l.symsByName[1] {
2616                 fmt.Println(i, name, 1)
2617         }
2618         fmt.Println("payloads:")
2619         for i := range l.payloads {
2620                 pp := l.payloads[i]
2621                 fmt.Println(i, pp.name, pp.ver, pp.kind)
2622         }
2623 }