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