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