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