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.
14 "cmd/link/internal/sym"
26 // Sym encapsulates a global symbol index, used to identify a specific
27 // Go symbol. The 0-valued Sym is corresponds to an invalid symbol.
30 // Relocs encapsulates the set of relocations on a given symbol; an
31 // instance of this type is returned by the Loader Relocs() method.
35 li uint32 // local index of symbol whose relocs we're examining
36 r *oReader // object reader for containing package
40 // ExtReloc contains the payload for an external relocation.
41 type ExtReloc struct {
48 // Reloc holds a "handle" to access a relocation record from an
55 // External reloc types may not fit into a uint8 which the Go object file uses.
56 // Store it here, instead of in the byte of goobj.Reloc.
57 // For Go symbols this will always be zero.
58 // goobj.Reloc.Type() + typ is always the right type, for both Go and external
63 func (rel Reloc) Type() objabi.RelocType { return objabi.RelocType(rel.Reloc.Type()) + rel.typ }
64 func (rel Reloc) Sym() Sym { return rel.l.resolve(rel.r, rel.Reloc.Sym()) }
65 func (rel Reloc) SetSym(s Sym) { rel.Reloc.SetSym(goobj.SymRef{PkgIdx: 0, SymIdx: uint32(s)}) }
66 func (rel Reloc) IsMarker() bool { return rel.Siz() == 0 }
68 func (rel Reloc) SetType(t objabi.RelocType) {
69 if t != objabi.RelocType(uint8(t)) {
70 panic("SetType: type doesn't fit into Reloc")
72 rel.Reloc.SetType(uint8(t))
74 // should use SymbolBuilder.SetRelocType
75 panic("wrong method to set reloc type")
79 // Aux holds a "handle" to access an aux symbol record from an
87 func (a Aux) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
89 // oReader is a wrapper type of obj.Reader, along with some
93 unit *sym.CompilationUnit
94 version int // version of static symbol
95 flags uint32 // read from object file
97 syms []Sym // Sym's global index, indexed by local index
98 pkg []uint32 // indices of referenced package by PkgIdx (index into loader.objs array)
99 ndef int // cache goobj.Reader.NSym()
100 nhashed64def int // cache goobj.Reader.NHashed64Def()
101 nhasheddef int // cache goobj.Reader.NHashedDef()
102 objidx uint32 // index of this reader in the objs slice
105 // Total number of defined symbols (package symbols, hashed symbols, and
106 // non-package symbols).
107 func (r *oReader) NAlldef() int { return r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef() }
114 // objSym represents a symbol in an object file. It is a tuple of
115 // the object and the symbol's local index.
116 // For external symbols, objidx is the index of l.extReader (extObj),
117 // s is its index into the payload array.
118 // {0, 0} represents the nil symbol.
120 objidx uint32 // index of the object (in l.objs array)
121 s uint32 // local index
124 type nameVer struct {
132 func (bm Bitmap) Set(i Sym) {
133 n, r := uint(i)/32, uint(i)%32
137 // unset the i-th bit.
138 func (bm Bitmap) Unset(i Sym) {
139 n, r := uint(i)/32, uint(i)%32
143 // whether the i-th bit is set.
144 func (bm Bitmap) Has(i Sym) bool {
145 n, r := uint(i)/32, uint(i)%32
146 return bm[n]&(1<<r) != 0
149 // return current length of bitmap in bits.
150 func (bm Bitmap) Len() int {
154 // return the number of bits set.
155 func (bm Bitmap) Count() int {
157 for _, x := range bm {
158 s += bits.OnesCount32(x)
163 func MakeBitmap(n int) Bitmap {
164 return make(Bitmap, (n+31)/32)
167 // growBitmap insures that the specified bitmap has enough capacity,
168 // reallocating (doubling the size) if needed.
169 func growBitmap(reqLen int, b Bitmap) Bitmap {
172 b = append(b, MakeBitmap(reqLen+1-curLen)...)
177 type symAndSize struct {
182 // A Loader loads new object files and resolves indexed symbol references.
184 // Notes on the layout of global symbol index space:
186 // - Go object files are read before host object files; each Go object
187 // read adds its defined package symbols to the global index space.
188 // Nonpackage symbols are not yet added.
190 // - In loader.LoadNonpkgSyms, add non-package defined symbols and
191 // references in all object files to the global index space.
193 // - Host object file loading happens; the host object loader does a
194 // name/version lookup for each symbol it finds; this can wind up
195 // extending the external symbol index space range. The host object
196 // loader stores symbol payloads in loader.payloads using SymbolBuilder.
198 // - Each symbol gets a unique global index. For duplicated and
199 // overwriting/overwritten symbols, the second (or later) appearance
200 // of the symbol gets the same global index as the first appearance.
202 start map[*oReader]Sym // map from object file to its start index
203 objs []objIdx // sorted by start index (i.e. objIdx.i)
204 extStart Sym // from this index on, the symbols are externally defined
205 builtinSyms []Sym // global index of builtin symbols
207 objSyms []objSym // global index mapping to local index
209 symsByName [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
210 extStaticSyms map[nameVer]Sym // externally defined static symbols, keyed by name
212 extReader *oReader // a dummy oReader, for external symbols
213 payloadBatch []extSymPayload
214 payloads []*extSymPayload // contents of linker-materialized external syms
215 values []int64 // symbol values, indexed by global sym index
217 sects []*sym.Section // sections
218 symSects []uint16 // symbol's section, index to sects array
220 align []uint8 // symbol 2^N alignment, indexed by global index
222 deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
224 objByPkg map[string]uint32 // map package path to the index of its Go object reader
226 anonVersion int // most recently assigned ext static sym pseudo-version
228 // Bitmaps and other side structures used to store data used to store
229 // symbol flags/attributes; these are to be accessed via the
230 // corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
231 // visit the comments on these methods for more details on the
232 // semantics / interpretation of the specific flags or attribute.
233 attrReachable Bitmap // reachable symbols, indexed by global index
234 attrOnList Bitmap // "on list" symbols, indexed by global index
235 attrLocal Bitmap // "local" symbols, indexed by global index
236 attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by global idx
237 attrUsedInIface Bitmap // "used in interface" symbols, indexed by global idx
238 attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
239 attrDuplicateOK Bitmap // dupOK symbols, indexed by ext sym index
240 attrShared Bitmap // shared symbols, indexed by ext sym index
241 attrExternal Bitmap // external symbols, indexed by ext sym index
243 attrReadOnly map[Sym]bool // readonly data for this sym
244 attrTopFrame map[Sym]struct{} // top frame symbols
245 attrSpecial map[Sym]struct{} // "special" frame symbols
246 attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
247 attrCgoExportStatic map[Sym]struct{} // "cgo_export_static" symbols
248 generatedSyms map[Sym]struct{} // symbols that generate their content
250 // Outer and Sub relations for symbols.
251 // TODO: figure out whether it's more efficient to just have these
252 // as fields on extSymPayload (note that this won't be a viable
253 // strategy if somewhere in the linker we set sub/outer for a
254 // non-external sym).
258 dynimplib map[Sym]string // stores Dynimplib symbol attribute
259 dynimpvers map[Sym]string // stores Dynimpvers symbol attribute
260 localentry map[Sym]uint8 // stores Localentry symbol attribute
261 extname map[Sym]string // stores Extname symbol attribute
262 elfType map[Sym]elf.SymType // stores elf type symbol property
263 elfSym map[Sym]int32 // stores elf sym symbol property
264 localElfSym map[Sym]int32 // stores "local" elf sym symbol property
265 symPkg map[Sym]string // stores package for symbol, or library for shlib-derived syms
266 plt map[Sym]int32 // stores dynimport for pe objects
267 got map[Sym]int32 // stores got for pe objects
268 dynid map[Sym]int32 // stores Dynid for symbol
270 relocVariant map[relocId]sym.RelocVariant // stores variant relocs
272 // Used to implement field tracking; created during deadcode if
273 // field tracking is enabled. Reachparent[K] contains the index of
274 // the symbol that triggered the marking of symbol K as live.
279 hasUnknownPkgPath bool // if any Go object has unknown package path
281 strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
283 elfsetstring elfsetstringFunc
285 errorReporter *ErrorReporter
287 npkgsyms int // number of package symbols, for accounting
288 nhashedsyms int // number of hashed symbols, for accounting
306 type elfsetstringFunc func(str string, off int)
308 // extSymPayload holds the payload (data + relocations) for linker-synthesized
309 // external symbols (note that symbol value is stored in a separate slice).
310 type extSymPayload struct {
311 name string // TODO: would this be better as offset into str table?
315 objidx uint32 // index of original object if sym made by cloneToExternal
317 reltypes []objabi.RelocType // relocation types
324 FlagStrictDups = 1 << iota
327 func NewLoader(flags uint32, elfsetstring elfsetstringFunc, reporter *ErrorReporter) *Loader {
328 nbuiltin := goobj.NBuiltin()
329 extReader := &oReader{objidx: extObj}
331 start: make(map[*oReader]Sym),
332 objs: []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
333 objSyms: make([]objSym, 1, 1), // This will get overwritten later.
334 extReader: extReader,
335 symsByName: [2]map[string]Sym{make(map[string]Sym, 80000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
336 objByPkg: make(map[string]uint32),
337 outer: make(map[Sym]Sym),
338 sub: make(map[Sym]Sym),
339 dynimplib: make(map[Sym]string),
340 dynimpvers: make(map[Sym]string),
341 localentry: make(map[Sym]uint8),
342 extname: make(map[Sym]string),
343 attrReadOnly: make(map[Sym]bool),
344 elfType: make(map[Sym]elf.SymType),
345 elfSym: make(map[Sym]int32),
346 localElfSym: make(map[Sym]int32),
347 symPkg: make(map[Sym]string),
348 plt: make(map[Sym]int32),
349 got: make(map[Sym]int32),
350 dynid: make(map[Sym]int32),
351 attrTopFrame: make(map[Sym]struct{}),
352 attrSpecial: make(map[Sym]struct{}),
353 attrCgoExportDynamic: make(map[Sym]struct{}),
354 attrCgoExportStatic: make(map[Sym]struct{}),
355 generatedSyms: make(map[Sym]struct{}),
356 deferReturnTramp: make(map[Sym]bool),
357 extStaticSyms: make(map[nameVer]Sym),
358 builtinSyms: make([]Sym, nbuiltin),
360 elfsetstring: elfsetstring,
361 errorReporter: reporter,
362 sects: []*sym.Section{nil}, // reserve index 0 for nil section
368 // Add object file r, return the start index.
369 func (l *Loader) addObj(pkg string, r *oReader) Sym {
370 if _, ok := l.start[r]; ok {
371 panic("already added")
373 pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
374 if _, ok := l.objByPkg[pkg]; !ok {
375 l.objByPkg[pkg] = r.objidx
377 i := Sym(len(l.objSyms))
379 l.objs = append(l.objs, objIdx{r, i})
380 if r.NeedNameExpansion() && !r.FromAssembly() {
381 l.hasUnknownPkgPath = true
386 // Add a symbol from an object file, return the global index.
387 // If the symbol already exist, it returns the index of that symbol.
388 func (st *loadState) addSym(name string, ver int, r *oReader, li uint32, kind int, osym *goobj.Sym) Sym {
391 panic("addSym called after external symbol is created")
393 i := Sym(len(l.objSyms))
394 addToGlobal := func() {
395 l.objSyms = append(l.objSyms, objSym{r.objidx, li})
397 if name == "" && kind != hashed64Def && kind != hashedDef {
399 return i // unnamed aux symbol
401 if ver == r.version {
402 // Static symbol. Add its global index but don't
403 // add to name lookup table, as it cannot be
404 // referenced by name.
410 // Defined package symbols cannot be dup to each other.
411 // We load all the package symbols first, so we don't need
412 // to check dup here.
413 // We still add it to the lookup table, as it may still be
414 // referenced by name (e.g. through linkname).
415 l.symsByName[ver][name] = i
418 case hashed64Def, hashedDef:
419 // Hashed (content-addressable) symbol. Check the hash
420 // but don't add to name lookup table, as they are not
421 // referenced by name. Also no need to do overwriting
422 // check, as same hash indicates same content.
423 var checkHash func() (symAndSize, bool)
424 var addToHashMap func(symAndSize)
425 var h64 uint64 // only used for hashed64Def
426 var h *goobj.HashType // only used for hashedDef
427 if kind == hashed64Def {
428 checkHash = func() (symAndSize, bool) {
429 h64 = r.Hash64(li - uint32(r.ndef))
430 s, existed := st.hashed64Syms[h64]
433 addToHashMap = func(ss symAndSize) { st.hashed64Syms[h64] = ss }
435 checkHash = func() (symAndSize, bool) {
436 h = r.Hash(li - uint32(r.ndef+r.nhashed64def))
437 s, existed := st.hashedSyms[*h]
440 addToHashMap = func(ss symAndSize) { st.hashedSyms[*h] = ss }
443 if s, existed := checkHash(); existed {
444 // The content hash is built from symbol data and relocations. In the
445 // object file, the symbol data may not always contain trailing zeros,
446 // e.g. for [5]int{1,2,3} and [100]int{1,2,3}, the data is same
447 // (although the size is different).
448 // Also, for short symbols, the content hash is the identity function of
449 // the 8 bytes, and trailing zeros doesn't change the hash value, e.g.
450 // hash("A") == hash("A\0\0\0").
451 // So when two symbols have the same hash, we need to use the one with
454 // New symbol has larger size, use the new one. Rewrite the index mapping.
455 l.objSyms[s.sym] = objSym{r.objidx, li}
456 addToHashMap(symAndSize{s.sym, siz})
460 addToHashMap(symAndSize{i, siz})
465 // Non-package (named) symbol. Check if it already exists.
466 oldi, existed := l.symsByName[ver][name]
468 l.symsByName[ver][name] = i
472 // symbol already exists
474 if l.flags&FlagStrictDups != 0 {
475 l.checkdup(name, r, li, oldi)
479 oldr, oldli := l.toLocal(oldi)
480 oldsym := oldr.Sym(oldli)
484 overwrite := r.DataSize(li) != 0
486 // new symbol overwrites old symbol.
487 oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
488 if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
489 log.Fatalf("duplicated definition of symbol " + name)
491 l.objSyms[oldi] = objSym{r.objidx, li}
493 // old symbol overwrites new symbol.
494 typ := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
495 if !typ.IsData() { // only allow overwriting data symbol
496 log.Fatalf("duplicated definition of symbol " + name)
502 // newExtSym creates a new external sym with the specified
504 func (l *Loader) newExtSym(name string, ver int) Sym {
505 i := Sym(len(l.objSyms))
509 l.growValues(int(i) + 1)
510 l.growAttrBitmaps(int(i) + 1)
511 pi := l.newPayload(name, ver)
512 l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
513 l.extReader.syms = append(l.extReader.syms, i)
517 // LookupOrCreateSym looks up the symbol with the specified name/version,
518 // returning its Sym index if found. If the lookup fails, a new external
519 // Sym will be created, entered into the lookup tables, and returned.
520 func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
521 i := l.Lookup(name, ver)
525 i = l.newExtSym(name, ver)
526 static := ver >= sym.SymVerStatic || ver < 0
528 l.extStaticSyms[nameVer{name, ver}] = i
530 l.symsByName[ver][name] = i
535 func (l *Loader) IsExternal(i Sym) bool {
537 return l.isExtReader(r)
540 func (l *Loader) isExtReader(r *oReader) bool {
541 return r == l.extReader
544 // For external symbol, return its index in the payloads array.
545 // XXX result is actually not a global index. We (ab)use the Sym type
546 // so we don't need conversion for accessing bitmaps.
547 func (l *Loader) extIndex(i Sym) Sym {
548 _, li := l.toLocal(i)
552 // Get a new payload for external symbol, return its index in
553 // the payloads array.
554 func (l *Loader) newPayload(name string, ver int) int {
555 pi := len(l.payloads)
556 pp := l.allocPayload()
559 l.payloads = append(l.payloads, pp)
560 l.growExtAttrBitmaps()
564 // getPayload returns a pointer to the extSymPayload struct for an
565 // external symbol if the symbol has a payload. Will panic if the
566 // symbol in question is bogus (zero or not an external sym).
567 func (l *Loader) getPayload(i Sym) *extSymPayload {
568 if !l.IsExternal(i) {
569 panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
572 return l.payloads[pi]
575 // allocPayload allocates a new payload.
576 func (l *Loader) allocPayload() *extSymPayload {
577 batch := l.payloadBatch
579 batch = make([]extSymPayload, 1000)
582 l.payloadBatch = batch[1:]
586 func (ms *extSymPayload) Grow(siz int64) {
587 if int64(int(siz)) != siz {
588 log.Fatalf("symgrow size %d too long", siz)
590 if int64(len(ms.data)) >= siz {
593 if cap(ms.data) < int(siz) {
595 ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
596 ms.data = ms.data[0:cl]
598 ms.data = ms.data[:siz]
601 // Convert a local index to a global index.
602 func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
606 // Convert a global index to a local index.
607 func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
608 return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
611 // Resolve a local symbol reference. Return global index.
612 func (l *Loader) resolve(r *oReader, s goobj.SymRef) Sym {
614 switch p := s.PkgIdx; p {
615 case goobj.PkgIdxInvalid:
616 // {0, X} with non-zero X is never a valid sym reference from a Go object.
617 // We steal this space for symbol references from external objects.
618 // In this case, X is just the global index.
619 if l.isExtReader(r) {
626 case goobj.PkgIdxHashed64:
627 i := int(s.SymIdx) + r.ndef
629 case goobj.PkgIdxHashed:
630 i := int(s.SymIdx) + r.ndef + r.nhashed64def
632 case goobj.PkgIdxNone:
633 i := int(s.SymIdx) + r.ndef + r.nhashed64def + r.nhasheddef
635 case goobj.PkgIdxBuiltin:
636 if bi := l.builtinSyms[s.SymIdx]; bi != 0 {
639 l.reportMissingBuiltin(int(s.SymIdx), r.unit.Lib.Pkg)
641 case goobj.PkgIdxSelf:
644 rr = l.objs[r.pkg[p]].r
646 return l.toGlobal(rr, s.SymIdx)
649 // reportMissingBuiltin issues an error in the case where we have a
650 // relocation against a runtime builtin whose definition is not found
651 // when the runtime package is built. The canonical example is
652 // "runtime.racefuncenter" -- currently if you do something like
654 // go build -gcflags=-race myprogram.go
656 // the compiler will insert calls to the builtin runtime.racefuncenter,
657 // but the version of the runtime used for linkage won't actually contain
658 // definitions of that symbol. See issue #42396 for details.
660 // As currently implemented, this is a fatal error. This has drawbacks
661 // in that if there are multiple missing builtins, the error will only
662 // cite the first one. On the plus side, terminating the link here has
663 // advantages in that we won't run the risk of panics or crashes later
664 // on in the linker due to R_CALL relocations with 0-valued target
666 func (l *Loader) reportMissingBuiltin(bsym int, reflib string) {
667 bname, _ := goobj.BuiltinName(bsym)
668 log.Fatalf("reference to undefined builtin %q from package %q",
672 // Look up a symbol by name, return global index, or 0 if not found.
673 // This is more like Syms.ROLookup than Lookup -- it doesn't create
675 func (l *Loader) Lookup(name string, ver int) Sym {
676 if ver >= sym.SymVerStatic || ver < 0 {
677 return l.extStaticSyms[nameVer{name, ver}]
679 return l.symsByName[ver][name]
682 // Check that duplicate symbols have same contents.
683 func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
685 rdup, ldup := l.toLocal(dup)
686 pdup := rdup.Data(ldup)
687 if bytes.Equal(p, pdup) {
690 reason := "same length but different contents"
691 if len(p) != len(pdup) {
692 reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
694 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)
696 // For the moment, allow DWARF subprogram DIEs for
697 // auto-generated wrapper functions. What seems to happen
698 // here is that we get different line numbers on formal
699 // params; I am guessing that the pos is being inherited
700 // from the spot where the wrapper is needed.
701 allowed := strings.HasPrefix(name, "go.info.go.interface") ||
702 strings.HasPrefix(name, "go.info.go.builtin") ||
703 strings.HasPrefix(name, "go.debuglines")
709 func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
711 // Number of total symbols.
712 func (l *Loader) NSym() int {
713 return len(l.objSyms)
716 // Number of defined Go symbols.
717 func (l *Loader) NDef() int {
718 return int(l.extStart)
721 // Number of reachable symbols.
722 func (l *Loader) NReachableSym() int {
723 return l.attrReachable.Count()
726 // SymNameLen returns the length of the symbol name, trying hard not to load
728 func (l *Loader) SymNameLen(i Sym) int {
729 // Not much we can do about external symbols.
731 return len(l.SymName(i))
733 r, li := l.toLocal(i)
734 le := r.Sym(li).NameLen(r.Reader)
735 if !r.NeedNameExpansion() {
738 // Just load the symbol name. We don't know how expanded it'll be.
739 return len(l.SymName(i))
742 // Returns the raw (unpatched) name of the i-th symbol.
743 func (l *Loader) RawSymName(i Sym) string {
745 pp := l.getPayload(i)
748 r, li := l.toLocal(i)
749 return r.Sym(li).Name(r.Reader)
752 // Returns the (patched) name of the i-th symbol.
753 func (l *Loader) SymName(i Sym) string {
755 pp := l.getPayload(i)
758 r, li := l.toLocal(i)
759 name := r.Sym(li).Name(r.Reader)
760 if !r.NeedNameExpansion() {
763 return strings.Replace(name, "\"\".", r.pkgprefix, -1)
766 // Returns the version of the i-th symbol.
767 func (l *Loader) SymVersion(i Sym) int {
769 pp := l.getPayload(i)
772 r, li := l.toLocal(i)
773 return int(abiToVer(r.Sym(li).ABI(), r.version))
776 func (l *Loader) IsFileLocal(i Sym) bool {
777 return l.SymVersion(i) >= sym.SymVerStatic
780 // IsFromAssembly returns true if this symbol is derived from an
781 // object file generated by the Go assembler.
782 func (l *Loader) IsFromAssembly(i Sym) bool {
787 return r.FromAssembly()
790 // Returns the type of the i-th symbol.
791 func (l *Loader) SymType(i Sym) sym.SymKind {
793 pp := l.getPayload(i)
799 r, li := l.toLocal(i)
800 return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
803 // Returns the attributes of the i-th symbol.
804 func (l *Loader) SymAttr(i Sym) uint8 {
806 // TODO: do something? External symbols have different representation of attributes.
807 // For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
808 // set by external symbol.
811 r, li := l.toLocal(i)
812 return r.Sym(li).Flag()
815 // Returns the size of the i-th symbol.
816 func (l *Loader) SymSize(i Sym) int64 {
818 pp := l.getPayload(i)
821 r, li := l.toLocal(i)
822 return int64(r.Sym(li).Siz())
825 // AttrReachable returns true for symbols that are transitively
826 // referenced from the entry points. Unreachable symbols are not
827 // written to the output.
828 func (l *Loader) AttrReachable(i Sym) bool {
829 return l.attrReachable.Has(i)
832 // SetAttrReachable sets the reachability property for a symbol (see
834 func (l *Loader) SetAttrReachable(i Sym, v bool) {
836 l.attrReachable.Set(i)
838 l.attrReachable.Unset(i)
842 // AttrOnList returns true for symbols that are on some list (such as
843 // the list of all text symbols, or one of the lists of data symbols)
844 // and is consulted to avoid bugs where a symbol is put on a list
846 func (l *Loader) AttrOnList(i Sym) bool {
847 return l.attrOnList.Has(i)
850 // SetAttrOnList sets the "on list" property for a symbol (see
852 func (l *Loader) SetAttrOnList(i Sym, v bool) {
856 l.attrOnList.Unset(i)
860 // AttrLocal returns true for symbols that are only visible within the
861 // module (executable or shared library) being linked. This attribute
862 // is applied to thunks and certain other linker-generated symbols.
863 func (l *Loader) AttrLocal(i Sym) bool {
864 return l.attrLocal.Has(i)
867 // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
868 func (l *Loader) SetAttrLocal(i Sym, v bool) {
876 // AttrUsedInIface returns true for a type symbol that is used in
878 func (l *Loader) AttrUsedInIface(i Sym) bool {
879 return l.attrUsedInIface.Has(i)
882 func (l *Loader) SetAttrUsedInIface(i Sym, v bool) {
884 l.attrUsedInIface.Set(i)
886 l.attrUsedInIface.Unset(i)
890 // SymAddr checks that a symbol is reachable, and returns its value.
891 func (l *Loader) SymAddr(i Sym) int64 {
892 if !l.AttrReachable(i) {
893 panic("unreachable symbol in symaddr")
898 // AttrNotInSymbolTable returns true for symbols that should not be
899 // added to the symbol table of the final generated load module.
900 func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
901 return l.attrNotInSymbolTable.Has(i)
904 // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
905 // (see AttrNotInSymbolTable above).
906 func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
908 l.attrNotInSymbolTable.Set(i)
910 l.attrNotInSymbolTable.Unset(i)
914 // AttrVisibilityHidden symbols returns true for ELF symbols with
915 // visibility set to STV_HIDDEN. They become local symbols in
916 // the final executable. Only relevant when internally linking
917 // on an ELF platform.
918 func (l *Loader) AttrVisibilityHidden(i Sym) bool {
919 if !l.IsExternal(i) {
922 return l.attrVisibilityHidden.Has(l.extIndex(i))
925 // SetAttrVisibilityHidden sets the "hidden visibility" property for a
926 // symbol (see AttrVisibilityHidden).
927 func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
928 if !l.IsExternal(i) {
929 panic("tried to set visibility attr on non-external symbol")
932 l.attrVisibilityHidden.Set(l.extIndex(i))
934 l.attrVisibilityHidden.Unset(l.extIndex(i))
938 // AttrDuplicateOK returns true for a symbol that can be present in
939 // multiple object files.
940 func (l *Loader) AttrDuplicateOK(i Sym) bool {
941 if !l.IsExternal(i) {
942 // TODO: if this path winds up being taken frequently, it
943 // might make more sense to copy the flag value out of the object
944 // into a larger bitmap during preload.
945 r, li := l.toLocal(i)
946 return r.Sym(li).Dupok()
948 return l.attrDuplicateOK.Has(l.extIndex(i))
951 // SetAttrDuplicateOK sets the "duplicate OK" property for an external
952 // symbol (see AttrDuplicateOK).
953 func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
954 if !l.IsExternal(i) {
955 panic("tried to set dupok attr on non-external symbol")
958 l.attrDuplicateOK.Set(l.extIndex(i))
960 l.attrDuplicateOK.Unset(l.extIndex(i))
964 // AttrShared returns true for symbols compiled with the -shared option.
965 func (l *Loader) AttrShared(i Sym) bool {
966 if !l.IsExternal(i) {
967 // TODO: if this path winds up being taken frequently, it
968 // might make more sense to copy the flag value out of the
969 // object into a larger bitmap during preload.
973 return l.attrShared.Has(l.extIndex(i))
976 // SetAttrShared sets the "shared" property for an external
977 // symbol (see AttrShared).
978 func (l *Loader) SetAttrShared(i Sym, v bool) {
979 if !l.IsExternal(i) {
980 panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
983 l.attrShared.Set(l.extIndex(i))
985 l.attrShared.Unset(l.extIndex(i))
989 // AttrExternal returns true for function symbols loaded from host
991 func (l *Loader) AttrExternal(i Sym) bool {
992 if !l.IsExternal(i) {
995 return l.attrExternal.Has(l.extIndex(i))
998 // SetAttrExternal sets the "external" property for an host object
999 // symbol (see AttrExternal).
1000 func (l *Loader) SetAttrExternal(i Sym, v bool) {
1001 if !l.IsExternal(i) {
1002 panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.RawSymName(i)))
1005 l.attrExternal.Set(l.extIndex(i))
1007 l.attrExternal.Unset(l.extIndex(i))
1011 // AttrTopFrame returns true for a function symbol that is an entry
1012 // point, meaning that unwinders should stop when they hit this
1014 func (l *Loader) AttrTopFrame(i Sym) bool {
1015 _, ok := l.attrTopFrame[i]
1019 // SetAttrTopFrame sets the "top frame" property for a symbol (see
1021 func (l *Loader) SetAttrTopFrame(i Sym, v bool) {
1023 l.attrTopFrame[i] = struct{}{}
1025 delete(l.attrTopFrame, i)
1029 // AttrSpecial returns true for a symbols that do not have their
1030 // address (i.e. Value) computed by the usual mechanism of
1031 // data.go:dodata() & data.go:address().
1032 func (l *Loader) AttrSpecial(i Sym) bool {
1033 _, ok := l.attrSpecial[i]
1037 // SetAttrSpecial sets the "special" property for a symbol (see
1039 func (l *Loader) SetAttrSpecial(i Sym, v bool) {
1041 l.attrSpecial[i] = struct{}{}
1043 delete(l.attrSpecial, i)
1047 // AttrCgoExportDynamic returns true for a symbol that has been
1048 // specially marked via the "cgo_export_dynamic" compiler directive
1049 // written by cgo (in response to //export directives in the source).
1050 func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
1051 _, ok := l.attrCgoExportDynamic[i]
1055 // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
1056 // (see AttrCgoExportDynamic).
1057 func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
1059 l.attrCgoExportDynamic[i] = struct{}{}
1061 delete(l.attrCgoExportDynamic, i)
1065 // AttrCgoExportStatic returns true for a symbol that has been
1066 // specially marked via the "cgo_export_static" directive
1068 func (l *Loader) AttrCgoExportStatic(i Sym) bool {
1069 _, ok := l.attrCgoExportStatic[i]
1073 // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
1074 // (see AttrCgoExportStatic).
1075 func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
1077 l.attrCgoExportStatic[i] = struct{}{}
1079 delete(l.attrCgoExportStatic, i)
1083 // IsGeneratedSym returns true if a symbol's been previously marked as a
1084 // generator symbol through the SetIsGeneratedSym. The functions for generator
1085 // symbols are kept in the Link context.
1086 func (l *Loader) IsGeneratedSym(i Sym) bool {
1087 _, ok := l.generatedSyms[i]
1091 // SetIsGeneratedSym marks symbols as generated symbols. Data shouldn't be
1092 // stored in generated symbols, and a function is registered and called for
1093 // each of these symbols.
1094 func (l *Loader) SetIsGeneratedSym(i Sym, v bool) {
1095 if !l.IsExternal(i) {
1096 panic("only external symbols can be generated")
1099 l.generatedSyms[i] = struct{}{}
1101 delete(l.generatedSyms, i)
1105 func (l *Loader) AttrCgoExport(i Sym) bool {
1106 return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
1109 // AttrReadOnly returns true for a symbol whose underlying data
1110 // is stored via a read-only mmap.
1111 func (l *Loader) AttrReadOnly(i Sym) bool {
1112 if v, ok := l.attrReadOnly[i]; ok {
1115 if l.IsExternal(i) {
1116 pp := l.getPayload(i)
1118 return l.objs[pp.objidx].r.ReadOnly()
1122 r, _ := l.toLocal(i)
1126 // SetAttrReadOnly sets the "data is read only" property for a symbol
1127 // (see AttrReadOnly).
1128 func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
1129 l.attrReadOnly[i] = v
1132 // AttrSubSymbol returns true for symbols that are listed as a
1133 // sub-symbol of some other outer symbol. The sub/outer mechanism is
1134 // used when loading host objects (sections from the host object
1135 // become regular linker symbols and symbols go on the Sub list of
1136 // their section) and for constructing the global offset table when
1137 // internally linking a dynamic executable.
1139 // Note that in later stages of the linker, we set Outer(S) to some
1140 // container symbol C, but don't set Sub(C). Thus we have two
1141 // distinct scenarios:
1143 // - Outer symbol covers the address ranges of its sub-symbols.
1144 // Outer.Sub is set in this case.
1145 // - Outer symbol doesn't conver the address ranges. It is zero-sized
1146 // and doesn't have sub-symbols. In the case, the inner symbol is
1147 // not actually a "SubSymbol". (Tricky!)
1149 // This method returns TRUE only for sub-symbols in the first scenario.
1151 // FIXME: would be better to do away with this and have a better way
1152 // to represent container symbols.
1154 func (l *Loader) AttrSubSymbol(i Sym) bool {
1155 // we don't explicitly store this attribute any more -- return
1156 // a value based on the sub-symbol setting.
1161 return l.SubSym(o) != 0
1164 // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
1165 // clients should instead use the AddInteriorSym method to establish
1166 // containment relationships for host object symbols.
1168 // Returns whether the i-th symbol has ReflectMethod attribute set.
1169 func (l *Loader) IsReflectMethod(i Sym) bool {
1170 return l.SymAttr(i)&goobj.SymFlagReflectMethod != 0
1173 // Returns whether the i-th symbol is nosplit.
1174 func (l *Loader) IsNoSplit(i Sym) bool {
1175 return l.SymAttr(i)&goobj.SymFlagNoSplit != 0
1178 // Returns whether this is a Go type symbol.
1179 func (l *Loader) IsGoType(i Sym) bool {
1180 return l.SymAttr(i)&goobj.SymFlagGoType != 0
1183 // Returns whether this symbol should be included in typelink.
1184 func (l *Loader) IsTypelink(i Sym) bool {
1185 return l.SymAttr(i)&goobj.SymFlagTypelink != 0
1188 // Returns whether this symbol is an itab symbol.
1189 func (l *Loader) IsItab(i Sym) bool {
1190 if l.IsExternal(i) {
1193 r, li := l.toLocal(i)
1194 return r.Sym(li).IsItab()
1197 // Return whether this is a trampoline of a deferreturn call.
1198 func (l *Loader) IsDeferReturnTramp(i Sym) bool {
1199 return l.deferReturnTramp[i]
1202 // Set that i is a trampoline of a deferreturn call.
1203 func (l *Loader) SetIsDeferReturnTramp(i Sym, v bool) {
1204 l.deferReturnTramp[i] = v
1207 // growValues grows the slice used to store symbol values.
1208 func (l *Loader) growValues(reqLen int) {
1209 curLen := len(l.values)
1210 if reqLen > curLen {
1211 l.values = append(l.values, make([]int64, reqLen+1-curLen)...)
1215 // SymValue returns the value of the i-th symbol. i is global index.
1216 func (l *Loader) SymValue(i Sym) int64 {
1220 // SetSymValue sets the value of the i-th symbol. i is global index.
1221 func (l *Loader) SetSymValue(i Sym, val int64) {
1225 // AddToSymValue adds to the value of the i-th symbol. i is the global index.
1226 func (l *Loader) AddToSymValue(i Sym, val int64) {
1230 // Returns the symbol content of the i-th symbol. i is global index.
1231 func (l *Loader) Data(i Sym) []byte {
1232 if l.IsExternal(i) {
1233 pp := l.getPayload(i)
1239 r, li := l.toLocal(i)
1243 // FreeData clears the symbol data of an external symbol, allowing the memory
1244 // to be freed earlier. No-op for non-external symbols.
1245 // i is global index.
1246 func (l *Loader) FreeData(i Sym) {
1247 if l.IsExternal(i) {
1248 pp := l.getPayload(i)
1255 // SymAlign returns the alignment for a symbol.
1256 func (l *Loader) SymAlign(i Sym) int32 {
1257 if int(i) >= len(l.align) {
1258 // align is extended lazily -- it the sym in question is
1259 // outside the range of the existing slice, then we assume its
1260 // alignment has not yet been set.
1263 // TODO: would it make sense to return an arch-specific
1264 // alignment depending on section type? E.g. STEXT => 32,
1270 return int32(1 << (abits - 1))
1273 // SetSymAlign sets the alignment for a symbol.
1274 func (l *Loader) SetSymAlign(i Sym, align int32) {
1275 // Reject nonsense alignments.
1276 if align < 0 || align&(align-1) != 0 {
1277 panic("bad alignment value")
1279 if int(i) >= len(l.align) {
1280 l.align = append(l.align, make([]uint8, l.NSym()-len(l.align))...)
1285 l.align[i] = uint8(bits.Len32(uint32(align)))
1288 // SymValue returns the section of the i-th symbol. i is global index.
1289 func (l *Loader) SymSect(i Sym) *sym.Section {
1290 if int(i) >= len(l.symSects) {
1291 // symSects is extended lazily -- it the sym in question is
1292 // outside the range of the existing slice, then we assume its
1293 // section has not yet been set.
1296 return l.sects[l.symSects[i]]
1299 // SetSymSect sets the section of the i-th symbol. i is global index.
1300 func (l *Loader) SetSymSect(i Sym, sect *sym.Section) {
1301 if int(i) >= len(l.symSects) {
1302 l.symSects = append(l.symSects, make([]uint16, l.NSym()-len(l.symSects))...)
1304 l.symSects[i] = sect.Index
1307 // growSects grows the slice used to store symbol sections.
1308 func (l *Loader) growSects(reqLen int) {
1309 curLen := len(l.symSects)
1310 if reqLen > curLen {
1311 l.symSects = append(l.symSects, make([]uint16, reqLen+1-curLen)...)
1315 // NewSection creates a new (output) section.
1316 func (l *Loader) NewSection() *sym.Section {
1317 sect := new(sym.Section)
1319 if idx != int(uint16(idx)) {
1320 panic("too many sections created")
1322 sect.Index = uint16(idx)
1323 l.sects = append(l.sects, sect)
1327 // SymDynImplib returns the "dynimplib" attribute for the specified
1328 // symbol, making up a portion of the info for a symbol specified
1329 // on a "cgo_import_dynamic" compiler directive.
1330 func (l *Loader) SymDynimplib(i Sym) string {
1331 return l.dynimplib[i]
1334 // SetSymDynimplib sets the "dynimplib" attribute for a symbol.
1335 func (l *Loader) SetSymDynimplib(i Sym, value string) {
1336 // reject bad symbols
1337 if i >= Sym(len(l.objSyms)) || i == 0 {
1338 panic("bad symbol index in SetDynimplib")
1341 delete(l.dynimplib, i)
1343 l.dynimplib[i] = value
1347 // SymDynimpvers returns the "dynimpvers" attribute for the specified
1348 // symbol, making up a portion of the info for a symbol specified
1349 // on a "cgo_import_dynamic" compiler directive.
1350 func (l *Loader) SymDynimpvers(i Sym) string {
1351 return l.dynimpvers[i]
1354 // SetSymDynimpvers sets the "dynimpvers" attribute for a symbol.
1355 func (l *Loader) SetSymDynimpvers(i Sym, value string) {
1356 // reject bad symbols
1357 if i >= Sym(len(l.objSyms)) || i == 0 {
1358 panic("bad symbol index in SetDynimpvers")
1361 delete(l.dynimpvers, i)
1363 l.dynimpvers[i] = value
1367 // SymExtname returns the "extname" value for the specified
1369 func (l *Loader) SymExtname(i Sym) string {
1370 if s, ok := l.extname[i]; ok {
1376 // SetSymExtname sets the "extname" attribute for a symbol.
1377 func (l *Loader) SetSymExtname(i Sym, value string) {
1378 // reject bad symbols
1379 if i >= Sym(len(l.objSyms)) || i == 0 {
1380 panic("bad symbol index in SetExtname")
1383 delete(l.extname, i)
1385 l.extname[i] = value
1389 // SymElfType returns the previously recorded ELF type for a symbol
1390 // (used only for symbols read from shared libraries by ldshlibsyms).
1391 // It is not set for symbols defined by the packages being linked or
1392 // by symbols read by ldelf (and so is left as elf.STT_NOTYPE).
1393 func (l *Loader) SymElfType(i Sym) elf.SymType {
1394 if et, ok := l.elfType[i]; ok {
1397 return elf.STT_NOTYPE
1400 // SetSymElfType sets the elf type attribute for a symbol.
1401 func (l *Loader) SetSymElfType(i Sym, et elf.SymType) {
1402 // reject bad symbols
1403 if i >= Sym(len(l.objSyms)) || i == 0 {
1404 panic("bad symbol index in SetSymElfType")
1406 if et == elf.STT_NOTYPE {
1407 delete(l.elfType, i)
1413 // SymElfSym returns the ELF symbol index for a given loader
1414 // symbol, assigned during ELF symtab generation.
1415 func (l *Loader) SymElfSym(i Sym) int32 {
1419 // SetSymElfSym sets the elf symbol index for a symbol.
1420 func (l *Loader) SetSymElfSym(i Sym, es int32) {
1422 panic("bad sym index")
1431 // SymLocalElfSym returns the "local" ELF symbol index for a given loader
1432 // symbol, assigned during ELF symtab generation.
1433 func (l *Loader) SymLocalElfSym(i Sym) int32 {
1434 return l.localElfSym[i]
1437 // SetSymLocalElfSym sets the "local" elf symbol index for a symbol.
1438 func (l *Loader) SetSymLocalElfSym(i Sym, es int32) {
1440 panic("bad sym index")
1443 delete(l.localElfSym, i)
1445 l.localElfSym[i] = es
1449 // SymPlt returns the plt value for pe symbols.
1450 func (l *Loader) SymPlt(s Sym) int32 {
1451 if v, ok := l.plt[s]; ok {
1457 // SetPlt sets the plt value for pe symbols.
1458 func (l *Loader) SetPlt(i Sym, v int32) {
1459 if i >= Sym(len(l.objSyms)) || i == 0 {
1460 panic("bad symbol for SetPlt")
1469 // SymGot returns the got value for pe symbols.
1470 func (l *Loader) SymGot(s Sym) int32 {
1471 if v, ok := l.got[s]; ok {
1477 // SetGot sets the got value for pe symbols.
1478 func (l *Loader) SetGot(i Sym, v int32) {
1479 if i >= Sym(len(l.objSyms)) || i == 0 {
1480 panic("bad symbol for SetGot")
1489 // SymDynid returns the "dynid" property for the specified symbol.
1490 func (l *Loader) SymDynid(i Sym) int32 {
1491 if s, ok := l.dynid[i]; ok {
1497 // SetSymDynid sets the "dynid" property for a symbol.
1498 func (l *Loader) SetSymDynid(i Sym, val int32) {
1499 // reject bad symbols
1500 if i >= Sym(len(l.objSyms)) || i == 0 {
1501 panic("bad symbol index in SetSymDynid")
1510 // DynIdSyms returns the set of symbols for which dynID is set to an
1511 // interesting (non-default) value. This is expected to be a fairly
1513 func (l *Loader) DynidSyms() []Sym {
1514 sl := make([]Sym, 0, len(l.dynid))
1515 for s := range l.dynid {
1518 sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
1522 // SymGoType returns the 'Gotype' property for a given symbol (set by
1523 // the Go compiler for variable symbols). This version relies on
1524 // reading aux symbols for the target sym -- it could be that a faster
1525 // approach would be to check for gotype during preload and copy the
1526 // results in to a map (might want to try this at some point and see
1527 // if it helps speed things up).
1528 func (l *Loader) SymGoType(i Sym) Sym {
1530 var auxs []goobj.Aux
1531 if l.IsExternal(i) {
1532 pp := l.getPayload(i)
1533 r = l.objs[pp.objidx].r
1537 r, li = l.toLocal(i)
1540 for j := range auxs {
1543 case goobj.AuxGotype:
1544 return l.resolve(r, a.Sym())
1550 // SymUnit returns the compilation unit for a given symbol (which will
1551 // typically be nil for external or linker-manufactured symbols).
1552 func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
1553 if l.IsExternal(i) {
1554 pp := l.getPayload(i)
1556 r := l.objs[pp.objidx].r
1561 r, _ := l.toLocal(i)
1565 // SymPkg returns the package where the symbol came from (for
1566 // regular compiler-generated Go symbols), but in the case of
1567 // building with "-linkshared" (when a symbol is read from a
1568 // shared library), will hold the library name.
1569 // NOTE: this correspondes to sym.Symbol.File field.
1570 func (l *Loader) SymPkg(i Sym) string {
1571 if f, ok := l.symPkg[i]; ok {
1574 if l.IsExternal(i) {
1575 pp := l.getPayload(i)
1577 r := l.objs[pp.objidx].r
1578 return r.unit.Lib.Pkg
1582 r, _ := l.toLocal(i)
1583 return r.unit.Lib.Pkg
1586 // SetSymPkg sets the package/library for a symbol. This is
1587 // needed mainly for external symbols, specifically those imported
1588 // from shared libraries.
1589 func (l *Loader) SetSymPkg(i Sym, pkg string) {
1590 // reject bad symbols
1591 if i >= Sym(len(l.objSyms)) || i == 0 {
1592 panic("bad symbol index in SetSymPkg")
1597 // SymLocalentry returns the "local entry" value for the specified
1599 func (l *Loader) SymLocalentry(i Sym) uint8 {
1600 return l.localentry[i]
1603 // SetSymLocalentry sets the "local entry" attribute for a symbol.
1604 func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
1605 // reject bad symbols
1606 if i >= Sym(len(l.objSyms)) || i == 0 {
1607 panic("bad symbol index in SetSymLocalentry")
1610 delete(l.localentry, i)
1612 l.localentry[i] = value
1616 // Returns the number of aux symbols given a global index.
1617 func (l *Loader) NAux(i Sym) int {
1618 if l.IsExternal(i) {
1621 r, li := l.toLocal(i)
1625 // Returns the "handle" to the j-th aux symbol of the i-th symbol.
1626 func (l *Loader) Aux(i Sym, j int) Aux {
1627 if l.IsExternal(i) {
1630 r, li := l.toLocal(i)
1631 if j >= r.NAux(li) {
1634 return Aux{r.Aux(li, j), r, l}
1637 // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
1638 // symbols associated with a given function symbol. Prior to the
1639 // introduction of the loader, this was done purely using name
1640 // lookups, e.f. for function with name XYZ we would then look up
1641 // go.info.XYZ, etc.
1642 func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
1643 if l.SymType(fnSymIdx) != sym.STEXT {
1644 log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1646 if l.IsExternal(fnSymIdx) {
1647 // Current expectation is that any external function will
1648 // not have auxsyms.
1651 r, li := l.toLocal(fnSymIdx)
1653 for i := range auxs {
1656 case goobj.AuxDwarfInfo:
1657 auxDwarfInfo = l.resolve(r, a.Sym())
1658 if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
1659 panic("aux dwarf info sym with wrong type")
1661 case goobj.AuxDwarfLoc:
1662 auxDwarfLoc = l.resolve(r, a.Sym())
1663 if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
1664 panic("aux dwarf loc sym with wrong type")
1666 case goobj.AuxDwarfRanges:
1667 auxDwarfRanges = l.resolve(r, a.Sym())
1668 if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
1669 panic("aux dwarf ranges sym with wrong type")
1671 case goobj.AuxDwarfLines:
1672 auxDwarfLines = l.resolve(r, a.Sym())
1673 if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
1674 panic("aux dwarf lines sym with wrong type")
1681 // AddInteriorSym sets up 'interior' as an interior symbol of
1682 // container/payload symbol 'container'. An interior symbol does not
1683 // itself have data, but gives a name to a subrange of the data in its
1684 // container symbol. The container itself may or may not have a name.
1685 // This method is intended primarily for use in the host object
1686 // loaders, to capture the semantics of symbols and sections in an
1687 // object file. When reading a host object file, we'll typically
1688 // encounter a static section symbol (ex: ".text") containing content
1689 // for a collection of functions, then a series of ELF (or macho, etc)
1690 // symbol table entries each of which points into a sub-section
1691 // (offset and length) of its corresponding container symbol. Within
1692 // the go linker we create a loader.Sym for the container (which is
1693 // expected to have the actual content/payload) and then a set of
1694 // interior loader.Sym's that point into a portion of the container.
1695 func (l *Loader) AddInteriorSym(container Sym, interior Sym) {
1696 // Container symbols are expected to have content/data.
1697 // NB: this restriction may turn out to be too strict (it's possible
1698 // to imagine a zero-sized container with an interior symbol pointing
1699 // into it); it's ok to relax or remove it if we counter an
1700 // oddball host object that triggers this.
1701 if l.SymSize(container) == 0 && len(l.Data(container)) == 0 {
1702 panic("unexpected empty container symbol")
1704 // The interior symbols for a container are not expected to have
1705 // content/data or relocations.
1706 if len(l.Data(interior)) != 0 {
1707 panic("unexpected non-empty interior symbol")
1709 // Interior symbol is expected to be in the symbol table.
1710 if l.AttrNotInSymbolTable(interior) {
1711 panic("interior symbol must be in symtab")
1713 // Only a single level of containment is allowed.
1714 if l.OuterSym(container) != 0 {
1715 panic("outer has outer itself")
1717 // Interior sym should not already have a sibling.
1718 if l.SubSym(interior) != 0 {
1719 panic("sub set for subsym")
1721 // Interior sym should not already point at a container.
1722 if l.OuterSym(interior) != 0 {
1723 panic("outer already set for subsym")
1725 l.sub[interior] = l.sub[container]
1726 l.sub[container] = interior
1727 l.outer[interior] = container
1730 // OuterSym gets the outer symbol for host object loaded symbols.
1731 func (l *Loader) OuterSym(i Sym) Sym {
1732 // FIXME: add check for isExternal?
1736 // SubSym gets the subsymbol for host object loaded symbols.
1737 func (l *Loader) SubSym(i Sym) Sym {
1738 // NB: note -- no check for l.isExternal(), since I am pretty sure
1739 // that later phases in the linker set subsym for "type." syms
1743 // SetCarrierSym declares that 'c' is the carrier or container symbol
1744 // for 's'. Carrier symbols are used in the linker to as a container
1745 // for a collection of sub-symbols where the content of the
1746 // sub-symbols is effectively concatenated to form the content of the
1747 // carrier. The carrier is given a name in the output symbol table
1748 // while the sub-symbol names are not. For example, the Go compiler
1749 // emits named string symbols (type SGOSTRING) when compiling a
1750 // package; after being deduplicated, these symbols are collected into
1751 // a single unit by assigning them a new carrier symbol named
1752 // "go.string.*" (which appears in the final symbol table for the
1753 // output load module).
1754 func (l *Loader) SetCarrierSym(s Sym, c Sym) {
1756 panic("invalid carrier in SetCarrierSym")
1759 panic("invalid sub-symbol in SetCarrierSym")
1761 // Carrier symbols are not expected to have content/data. It is
1762 // ok for them to have non-zero size (to allow for use of generator
1764 if len(l.Data(c)) != 0 {
1765 panic("unexpected non-empty carrier symbol")
1768 // relocsym's foldSubSymbolOffset requires that we only
1769 // have a single level of containment-- enforce here.
1770 if l.outer[c] != 0 {
1771 panic("invalid nested carrier sym")
1775 // Initialize Reachable bitmap and its siblings for running deadcode pass.
1776 func (l *Loader) InitReachable() {
1777 l.growAttrBitmaps(l.NSym() + 1)
1780 type symWithVal struct {
1784 type bySymValue []symWithVal
1786 func (s bySymValue) Len() int { return len(s) }
1787 func (s bySymValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1788 func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
1790 // SortSub walks through the sub-symbols for 's' and sorts them
1791 // in place by increasing value. Return value is the new
1792 // sub symbol for the specified outer symbol.
1793 func (l *Loader) SortSub(s Sym) Sym {
1795 if s == 0 || l.sub[s] == 0 {
1799 // Sort symbols using a slice first. Use a stable sort on the off
1800 // chance that there's more than once symbol with the same value,
1801 // so as to preserve reproducible builds.
1802 sl := []symWithVal{}
1803 for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
1804 sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
1806 sort.Stable(bySymValue(sl))
1808 // Then apply any changes needed to the sub map.
1810 for i := len(sl) - 1; i >= 0; i-- {
1816 // Update sub for outer symbol, then return
1821 // SortSyms sorts a list of symbols by their value.
1822 func (l *Loader) SortSyms(ss []Sym) {
1823 sort.SliceStable(ss, func(i, j int) bool { return l.SymValue(ss[i]) < l.SymValue(ss[j]) })
1826 // Insure that reachable bitmap and its siblings have enough size.
1827 func (l *Loader) growAttrBitmaps(reqLen int) {
1828 if reqLen > l.attrReachable.Len() {
1829 // These are indexed by global symbol
1830 l.attrReachable = growBitmap(reqLen, l.attrReachable)
1831 l.attrOnList = growBitmap(reqLen, l.attrOnList)
1832 l.attrLocal = growBitmap(reqLen, l.attrLocal)
1833 l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
1834 l.attrUsedInIface = growBitmap(reqLen, l.attrUsedInIface)
1836 l.growExtAttrBitmaps()
1839 func (l *Loader) growExtAttrBitmaps() {
1840 // These are indexed by external symbol index (e.g. l.extIndex(i))
1841 extReqLen := len(l.payloads)
1842 if extReqLen > l.attrVisibilityHidden.Len() {
1843 l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
1844 l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
1845 l.attrShared = growBitmap(extReqLen, l.attrShared)
1846 l.attrExternal = growBitmap(extReqLen, l.attrExternal)
1850 func (relocs *Relocs) Count() int { return len(relocs.rs) }
1852 // At returns the j-th reloc for a global symbol.
1853 func (relocs *Relocs) At(j int) Reloc {
1854 if relocs.l.isExtReader(relocs.r) {
1855 pp := relocs.l.payloads[relocs.li]
1856 return Reloc{&relocs.rs[j], relocs.r, relocs.l, pp.reltypes[j]}
1858 return Reloc{&relocs.rs[j], relocs.r, relocs.l, 0}
1861 // Relocs returns a Relocs object for the given global sym.
1862 func (l *Loader) Relocs(i Sym) Relocs {
1863 r, li := l.toLocal(i)
1865 panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
1867 return l.relocs(r, li)
1870 // Relocs returns a Relocs object given a local sym index and reader.
1871 func (l *Loader) relocs(r *oReader, li uint32) Relocs {
1872 var rs []goobj.Reloc
1873 if l.isExtReader(r) {
1874 pp := l.payloads[li]
1887 // FuncInfo provides hooks to access goobj.FuncInfo in the objects.
1888 type FuncInfo struct {
1893 lengths goobj.FuncInfoLengths
1896 func (fi *FuncInfo) Valid() bool { return fi.r != nil }
1898 func (fi *FuncInfo) Args() int {
1899 return int((*goobj.FuncInfo)(nil).ReadArgs(fi.data))
1902 func (fi *FuncInfo) Locals() int {
1903 return int((*goobj.FuncInfo)(nil).ReadLocals(fi.data))
1906 func (fi *FuncInfo) FuncID() objabi.FuncID {
1907 return objabi.FuncID((*goobj.FuncInfo)(nil).ReadFuncID(fi.data))
1910 func (fi *FuncInfo) Pcsp() Sym {
1911 sym := (*goobj.FuncInfo)(nil).ReadPcsp(fi.data)
1912 return fi.l.resolve(fi.r, sym)
1915 func (fi *FuncInfo) Pcfile() Sym {
1916 sym := (*goobj.FuncInfo)(nil).ReadPcfile(fi.data)
1917 return fi.l.resolve(fi.r, sym)
1920 func (fi *FuncInfo) Pcline() Sym {
1921 sym := (*goobj.FuncInfo)(nil).ReadPcline(fi.data)
1922 return fi.l.resolve(fi.r, sym)
1925 func (fi *FuncInfo) Pcinline() Sym {
1926 sym := (*goobj.FuncInfo)(nil).ReadPcinline(fi.data)
1927 return fi.l.resolve(fi.r, sym)
1930 // Preload has to be called prior to invoking the various methods
1931 // below related to pcdata, funcdataoff, files, and inltree nodes.
1932 func (fi *FuncInfo) Preload() {
1933 fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
1936 func (fi *FuncInfo) Pcdata() []Sym {
1937 if !fi.lengths.Initialized {
1938 panic("need to call Preload first")
1940 syms := (*goobj.FuncInfo)(nil).ReadPcdata(fi.data)
1941 ret := make([]Sym, len(syms))
1942 for i := range ret {
1943 ret[i] = fi.l.resolve(fi.r, syms[i])
1948 func (fi *FuncInfo) NumFuncdataoff() uint32 {
1949 if !fi.lengths.Initialized {
1950 panic("need to call Preload first")
1952 return fi.lengths.NumFuncdataoff
1955 func (fi *FuncInfo) Funcdataoff(k int) int64 {
1956 if !fi.lengths.Initialized {
1957 panic("need to call Preload first")
1959 return (*goobj.FuncInfo)(nil).ReadFuncdataoff(fi.data, fi.lengths.FuncdataoffOff, uint32(k))
1962 func (fi *FuncInfo) Funcdata(syms []Sym) []Sym {
1963 if !fi.lengths.Initialized {
1964 panic("need to call Preload first")
1966 if int(fi.lengths.NumFuncdataoff) > cap(syms) {
1967 syms = make([]Sym, 0, fi.lengths.NumFuncdataoff)
1971 for j := range fi.auxs {
1973 if a.Type() == goobj.AuxFuncdata {
1974 syms = append(syms, fi.l.resolve(fi.r, a.Sym()))
1980 func (fi *FuncInfo) NumFile() uint32 {
1981 if !fi.lengths.Initialized {
1982 panic("need to call Preload first")
1984 return fi.lengths.NumFile
1987 func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
1988 if !fi.lengths.Initialized {
1989 panic("need to call Preload first")
1991 return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
1994 type InlTreeNode struct {
1996 File goobj.CUFileIndex
2002 func (fi *FuncInfo) NumInlTree() uint32 {
2003 if !fi.lengths.Initialized {
2004 panic("need to call Preload first")
2006 return fi.lengths.NumInlTree
2009 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
2010 if !fi.lengths.Initialized {
2011 panic("need to call Preload first")
2013 node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
2015 Parent: node.Parent,
2018 Func: fi.l.resolve(fi.r, node.Func),
2019 ParentPC: node.ParentPC,
2023 func (l *Loader) FuncInfo(i Sym) FuncInfo {
2025 var auxs []goobj.Aux
2026 if l.IsExternal(i) {
2027 pp := l.getPayload(i)
2031 r = l.objs[pp.objidx].r
2035 r, li = l.toLocal(i)
2038 for j := range auxs {
2040 if a.Type() == goobj.AuxFuncInfo {
2041 b := r.Data(a.Sym().SymIdx)
2042 return FuncInfo{l, r, b, auxs, goobj.FuncInfoLengths{}}
2048 // Preload a package: adds autolib.
2049 // Does not add defined package or non-packaged symbols to the symbol table.
2050 // These are done in LoadSyms.
2051 // Does not read symbol data.
2052 // Returns the fingerprint of the object.
2053 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
2054 roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
2056 log.Fatal("cannot read object file:", err)
2058 r := goobj.NewReaderFromBytes(roObject, readonly)
2060 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
2061 log.Fatalf("found object file %s in old format", f.File().Name())
2063 panic("cannot read object file")
2065 pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
2067 nhashed64def := r.NHashed64def()
2068 nhasheddef := r.NHasheddef()
2072 version: localSymVersion,
2074 pkgprefix: pkgprefix,
2075 syms: make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
2077 nhasheddef: nhasheddef,
2078 nhashed64def: nhashed64def,
2079 objidx: uint32(len(l.objs)),
2083 lib.Autolib = append(lib.Autolib, r.Autolib()...)
2087 unit.FileTable = make([]string, nfile)
2088 for i := range unit.FileTable {
2089 unit.FileTable[i] = r.File(i)
2092 l.addObj(lib.Pkg, or)
2094 // The caller expects us consuming all the data
2095 f.MustSeek(length, os.SEEK_CUR)
2097 return r.Fingerprint()
2100 // Holds the loader along with temporary states for loading symbols.
2101 type loadState struct {
2103 hashed64Syms map[uint64]symAndSize // short hashed (content-addressable) symbols, keyed by content hash
2104 hashedSyms map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
2107 // Preload symbols of given kind from an object.
2108 func (st *loadState) preloadSyms(r *oReader, kind int) {
2110 var start, end uint32
2114 end = uint32(r.ndef)
2116 start = uint32(r.ndef)
2117 end = uint32(r.ndef + r.nhashed64def)
2119 start = uint32(r.ndef + r.nhashed64def)
2120 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2121 if l.hasUnknownPkgPath {
2122 // The content hash depends on symbol name expansion. If any package is
2123 // built without fully expanded names, the content hash is unreliable.
2124 // Treat them as named symbols.
2126 // (We don't need to do this for hashed64Def case, as there the hash
2127 // function is simply the identity function, which doesn't depend on
2132 start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2133 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
2135 panic("preloadSyms: bad kind")
2137 l.growAttrBitmaps(len(l.objSyms) + int(end-start))
2138 needNameExpansion := r.NeedNameExpansion()
2139 loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
2140 for i := start; i < end; i++ {
2144 if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
2145 name = osym.Name(r.Reader)
2146 if needNameExpansion {
2147 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2149 v = abiToVer(osym.ABI(), r.version)
2151 gi := st.addSym(name, v, r, i, kind, osym)
2153 if osym.TopFrame() {
2154 l.SetAttrTopFrame(gi, true)
2157 l.SetAttrLocal(gi, true)
2159 if osym.UsedInIface() {
2160 l.SetAttrUsedInIface(gi, true)
2162 if strings.HasPrefix(name, "runtime.") ||
2163 (loadingRuntimePkg && strings.HasPrefix(name, "type.")) {
2164 if bi := goobj.BuiltinIdx(name, v); bi != -1 {
2165 // This is a definition of a builtin symbol. Record where it is.
2166 l.builtinSyms[bi] = gi
2169 if a := int32(osym.Align()); a != 0 && a > l.SymAlign(gi) {
2170 l.SetSymAlign(gi, a)
2175 // Add syms, hashed (content-addressable) symbols, non-package symbols, and
2176 // references to external symbols (which are always named).
2177 func (l *Loader) LoadSyms(arch *sys.Arch) {
2178 // Allocate space for symbols, making a guess as to how much space we need.
2179 // This function was determined empirically by looking at the cmd/compile on
2180 // Darwin, and picking factors for hashed and hashed64 syms.
2181 var symSize, hashedSize, hashed64Size int
2182 for _, o := range l.objs[goObjStart:] {
2183 symSize += o.r.ndef + o.r.nhasheddef/2 + o.r.nhashed64def/2 + o.r.NNonpkgdef()
2184 hashedSize += o.r.nhasheddef / 2
2185 hashed64Size += o.r.nhashed64def / 2
2187 // Index 0 is invalid for symbols.
2188 l.objSyms = make([]objSym, 1, symSize)
2190 l.npkgsyms = l.NSym()
2193 hashed64Syms: make(map[uint64]symAndSize, hashed64Size),
2194 hashedSyms: make(map[goobj.HashType]symAndSize, hashedSize),
2197 for _, o := range l.objs[goObjStart:] {
2198 st.preloadSyms(o.r, pkgDef)
2200 for _, o := range l.objs[goObjStart:] {
2201 st.preloadSyms(o.r, hashed64Def)
2202 st.preloadSyms(o.r, hashedDef)
2203 st.preloadSyms(o.r, nonPkgDef)
2205 l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
2206 for _, o := range l.objs[goObjStart:] {
2207 loadObjRefs(l, o.r, arch)
2209 l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2212 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2213 // load non-package refs
2214 ndef := uint32(r.NAlldef())
2215 needNameExpansion := r.NeedNameExpansion()
2216 for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2217 osym := r.Sym(ndef + i)
2218 name := osym.Name(r.Reader)
2219 if needNameExpansion {
2220 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2222 v := abiToVer(osym.ABI(), r.version)
2223 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2224 gi := r.syms[ndef+i]
2226 l.SetAttrLocal(gi, true)
2228 if osym.UsedInIface() {
2229 l.SetAttrUsedInIface(gi, true)
2233 // referenced packages
2235 r.pkg = make([]uint32, npkg)
2236 for i := 1; i < npkg; i++ { // PkgIdx 0 is a dummy invalid package
2238 objidx, ok := l.objByPkg[pkg]
2240 log.Fatalf("reference of nonexisted package %s, from %v", pkg, r.unit.Lib)
2245 // load flags of package refs
2246 for i, n := 0, r.NRefFlags(); i < n; i++ {
2248 gi := l.resolve(r, rf.Sym())
2249 if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
2250 l.SetAttrUsedInIface(gi, true)
2255 func abiToVer(abi uint16, localSymVersion int) int {
2257 if abi == goobj.SymABIstatic {
2260 } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2261 // Note that data symbols are "ABI0", which maps to version 0.
2264 log.Fatalf("invalid symbol ABI: %d", abi)
2269 // ResolveABIAlias given a symbol returns the ABI alias target of that
2270 // symbol. If the sym in question is not an alias, the sym itself is
2272 func (l *Loader) ResolveABIAlias(s Sym) Sym {
2276 if l.SymType(s) != sym.SABIALIAS {
2279 relocs := l.Relocs(s)
2280 target := relocs.At(0).Sym()
2281 if l.SymType(target) == sym.SABIALIAS {
2282 panic(fmt.Sprintf("ABI alias %s references another ABI alias %s", l.SymName(s), l.SymName(target)))
2287 // TopLevelSym tests a symbol (by name and kind) to determine whether
2288 // the symbol first class sym (participating in the link) or is an
2289 // anonymous aux or sub-symbol containing some sub-part or payload of
2291 func (l *Loader) TopLevelSym(s Sym) bool {
2292 return topLevelSym(l.RawSymName(s), l.SymType(s))
2295 // topLevelSym tests a symbol name and kind to determine whether
2296 // the symbol first class sym (participating in the link) or is an
2297 // anonymous aux or sub-symbol containing some sub-part or payload of
2299 func topLevelSym(sname string, skind sym.SymKind) bool {
2304 case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2311 // cloneToExternal takes the existing object file symbol (symIdx)
2312 // and creates a new external symbol payload that is a clone with
2313 // respect to name, version, type, relocations, etc. The idea here
2314 // is that if the linker decides it wants to update the contents of
2315 // a symbol originally discovered as part of an object file, it's
2316 // easier to do this if we make the updates to an external symbol
2318 func (l *Loader) cloneToExternal(symIdx Sym) {
2319 if l.IsExternal(symIdx) {
2320 panic("sym is already external, no need for clone")
2323 // Read the particulars from object.
2324 r, li := l.toLocal(symIdx)
2326 sname := osym.Name(r.Reader)
2327 if r.NeedNameExpansion() {
2328 sname = strings.Replace(sname, "\"\".", r.pkgprefix, -1)
2330 sver := abiToVer(osym.ABI(), r.version)
2331 skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2333 // Create new symbol, update version and kind.
2334 pi := l.newPayload(sname, sver)
2335 pp := l.payloads[pi]
2338 pp.size = int64(osym.Siz())
2339 pp.objidx = r.objidx
2341 // If this is a def, then copy the guts. We expect this case
2342 // to be very rare (one case it may come up is with -X).
2343 if li < uint32(r.NAlldef()) {
2346 relocs := l.Relocs(symIdx)
2347 pp.relocs = make([]goobj.Reloc, relocs.Count())
2348 pp.reltypes = make([]objabi.RelocType, relocs.Count())
2349 for i := range pp.relocs {
2350 // Copy the relocs slice.
2351 // Convert local reference to global reference.
2353 pp.relocs[i].Set(rel.Off(), rel.Siz(), 0, rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2354 pp.reltypes[i] = rel.Type()
2358 pp.data = r.Data(li)
2361 // If we're overriding a data symbol, collect the associated
2362 // Gotype, so as to propagate it to the new symbol.
2366 // Install new payload to global index space.
2367 // (This needs to happen at the end, as the accessors above
2368 // need to access the old symbol content.)
2369 l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2370 l.extReader.syms = append(l.extReader.syms, symIdx)
2373 // Copy the payload of symbol src to dst. Both src and dst must be external
2375 // The intended use case is that when building/linking against a shared library,
2376 // where we do symbol name mangling, the Go object file may have reference to
2377 // the original symbol name whereas the shared library provides a symbol with
2378 // the mangled name. When we do mangling, we copy payload of mangled to original.
2379 func (l *Loader) CopySym(src, dst Sym) {
2380 if !l.IsExternal(dst) {
2381 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2383 if !l.IsExternal(src) {
2384 panic("src is not external") //l.cloneToExternal(src)
2386 l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2387 l.SetSymPkg(dst, l.SymPkg(src))
2388 // TODO: other attributes?
2391 // CopyAttributes copies over all of the attributes of symbol 'src' to
2393 func (l *Loader) CopyAttributes(src Sym, dst Sym) {
2394 l.SetAttrReachable(dst, l.AttrReachable(src))
2395 l.SetAttrOnList(dst, l.AttrOnList(src))
2396 l.SetAttrLocal(dst, l.AttrLocal(src))
2397 l.SetAttrNotInSymbolTable(dst, l.AttrNotInSymbolTable(src))
2398 if l.IsExternal(dst) {
2399 l.SetAttrVisibilityHidden(dst, l.AttrVisibilityHidden(src))
2400 l.SetAttrDuplicateOK(dst, l.AttrDuplicateOK(src))
2401 l.SetAttrShared(dst, l.AttrShared(src))
2402 l.SetAttrExternal(dst, l.AttrExternal(src))
2404 // Some attributes are modifiable only for external symbols.
2405 // In such cases, don't try to transfer over the attribute
2406 // from the source even if there is a clash. This comes up
2407 // when copying attributes from a dupOK ABI wrapper symbol to
2408 // the real target symbol (which may not be marked dupOK).
2410 l.SetAttrTopFrame(dst, l.AttrTopFrame(src))
2411 l.SetAttrSpecial(dst, l.AttrSpecial(src))
2412 l.SetAttrCgoExportDynamic(dst, l.AttrCgoExportDynamic(src))
2413 l.SetAttrCgoExportStatic(dst, l.AttrCgoExportStatic(src))
2414 l.SetAttrReadOnly(dst, l.AttrReadOnly(src))
2417 // CreateExtSym creates a new external symbol with the specified name
2418 // without adding it to any lookup tables, returning a Sym index for it.
2419 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2420 return l.newExtSym(name, ver)
2423 // CreateStaticSym creates a new static symbol with the specified name
2424 // without adding it to any lookup tables, returning a Sym index for it.
2425 func (l *Loader) CreateStaticSym(name string) Sym {
2426 // Assign a new unique negative version -- this is to mark the
2427 // symbol so that it is not included in the name lookup table.
2429 return l.newExtSym(name, l.anonVersion)
2432 func (l *Loader) FreeSym(i Sym) {
2433 if l.IsExternal(i) {
2434 pp := l.getPayload(i)
2435 *pp = extSymPayload{}
2439 // relocId is essentially a <S,R> tuple identifying the Rth
2440 // relocation of symbol S.
2441 type relocId struct {
2446 // SetRelocVariant sets the 'variant' property of a relocation on
2447 // some specific symbol.
2448 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2450 if relocs := l.Relocs(s); ri >= relocs.Count() {
2451 panic("invalid relocation ID")
2453 if l.relocVariant == nil {
2454 l.relocVariant = make(map[relocId]sym.RelocVariant)
2457 l.relocVariant[relocId{s, ri}] = v
2459 delete(l.relocVariant, relocId{s, ri})
2463 // RelocVariant returns the 'variant' property of a relocation on
2464 // some specific symbol.
2465 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2466 return l.relocVariant[relocId{s, ri}]
2469 // UndefinedRelocTargets iterates through the global symbol index
2470 // space, looking for symbols with relocations targeting undefined
2471 // references. The linker's loadlib method uses this to determine if
2472 // there are unresolved references to functions in system libraries
2473 // (for example, libgcc.a), presumably due to CGO code. Return
2474 // value is a list of loader.Sym's corresponding to the undefined
2475 // cross-refs. The "limit" param controls the maximum number of
2476 // results returned; if "limit" is -1, then all undefs are returned.
2477 func (l *Loader) UndefinedRelocTargets(limit int) []Sym {
2479 for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2480 relocs := l.Relocs(si)
2481 for ri := 0; ri < relocs.Count(); ri++ {
2484 if rs != 0 && l.SymType(rs) == sym.SXREF && l.RawSymName(rs) != ".got" {
2485 result = append(result, rs)
2486 if limit != -1 && len(result) >= limit {
2495 // AssignTextSymbolOrder populates the Textp slices within each
2496 // library and compilation unit, insuring that packages are laid down
2497 // in dependency order (internal first, then everything else). Return value
2498 // is a slice of all text syms.
2499 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2501 // Library Textp lists should be empty at this point.
2502 for _, lib := range libs {
2503 if len(lib.Textp) != 0 {
2504 panic("expected empty Textp slice for library")
2506 if len(lib.DupTextSyms) != 0 {
2507 panic("expected empty DupTextSyms slice for library")
2511 // Used to record which dupok symbol we've assigned to a unit.
2512 // Can't use the onlist attribute here because it will need to
2513 // clear for the later assignment of the sym.Symbol to a unit.
2514 // NB: we can convert to using onList once we no longer have to
2515 // call the regular addToTextp.
2516 assignedToUnit := MakeBitmap(l.NSym() + 1)
2518 // Start off textp with reachable external syms.
2520 for _, sym := range extsyms {
2521 if !l.attrReachable.Has(sym) {
2524 textp = append(textp, sym)
2527 // Walk through all text symbols from Go object files and append
2528 // them to their corresponding library's textp list.
2529 for _, o := range l.objs[goObjStart:] {
2532 for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
2533 gi := l.toGlobal(r, i)
2534 if !l.attrReachable.Has(gi) {
2538 st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2539 if st != sym.STEXT {
2542 dupok := osym.Dupok()
2543 if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2544 // A dupok text symbol is resolved to another package.
2545 // We still need to record its presence in the current
2546 // package, as the trampoline pass expects packages
2547 // are laid out in dependency order.
2548 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2549 continue // symbol in different object
2552 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2556 lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2560 // Now assemble global textp, and assign text symbols to units.
2561 for _, doInternal := range [2]bool{true, false} {
2562 for idx, lib := range libs {
2563 if intlibs[idx] != doInternal {
2566 lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2567 for i, list := range lists {
2568 for _, s := range list {
2570 if l.attrReachable.Has(sym) && !assignedToUnit.Has(sym) {
2571 textp = append(textp, sym)
2572 unit := l.SymUnit(sym)
2574 unit.Textp = append(unit.Textp, s)
2575 assignedToUnit.Set(sym)
2577 // Dupok symbols may be defined in multiple packages; the
2578 // associated package for a dupok sym is chosen sort of
2579 // arbitrarily (the first containing package that the linker
2580 // loads). Canonicalizes its Pkg to the package with which
2581 // it will be laid down in text.
2582 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2583 l.SetSymPkg(sym, lib.Pkg)
2589 lib.DupTextSyms = nil
2596 // ErrorReporter is a helper class for reporting errors.
2597 type ErrorReporter struct {
2599 AfterErrorAction func()
2602 // Errorf method logs an error message.
2604 // After each error, the error actions function will be invoked; this
2605 // will either terminate the link immediately (if -h option given)
2606 // or it will keep a count and exit if more than 20 errors have been printed.
2608 // Logging an error means that on exit cmd/link will delete any
2609 // output file and return a non-zero error code.
2611 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2612 if s != 0 && reporter.ldr.SymName(s) != "" {
2613 format = reporter.ldr.SymName(s) + ": " + format
2615 format = fmt.Sprintf("sym %d: %s", s, format)
2618 fmt.Fprintf(os.Stderr, format, args...)
2619 reporter.AfterErrorAction()
2622 // GetErrorReporter returns the loader's associated error reporter.
2623 func (l *Loader) GetErrorReporter() *ErrorReporter {
2624 return l.errorReporter
2627 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2628 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2629 l.errorReporter.Errorf(s, format, args...)
2632 // Symbol statistics.
2633 func (l *Loader) Stat() string {
2634 s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
2635 s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
2636 l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
2641 func (l *Loader) Dump() {
2643 for _, obj := range l.objs[goObjStart:] {
2645 fmt.Println(obj.i, obj.r.unit.Lib)
2648 fmt.Println("extStart:", l.extStart)
2649 fmt.Println("Nsyms:", len(l.objSyms))
2651 for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2653 if l.IsExternal(i) {
2654 pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2657 if l.SymSect(i) != nil {
2658 sect = l.SymSect(i).Name
2660 fmt.Printf("%v %v %v %v %x %v\n", i, l.SymName(i), l.SymType(i), pi, l.SymValue(i), sect)
2662 fmt.Println("symsByName")
2663 for name, i := range l.symsByName[0] {
2664 fmt.Println(i, name, 0)
2666 for name, i := range l.symsByName[1] {
2667 fmt.Println(i, name, 1)
2669 fmt.Println("payloads:")
2670 for i := range l.payloads {
2672 fmt.Println(i, pp.name, pp.ver, pp.kind)