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)}) }
67 func (rel Reloc) SetType(t objabi.RelocType) {
68 if t != objabi.RelocType(uint8(t)) {
69 panic("SetType: type doesn't fit into Reloc")
71 rel.Reloc.SetType(uint8(t))
73 // should use SymbolBuilder.SetRelocType
74 panic("wrong method to set reloc type")
78 // Aux holds a "handle" to access an aux symbol record from an
86 func (a Aux) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
88 // oReader is a wrapper type of obj.Reader, along with some
92 unit *sym.CompilationUnit
93 version int // version of static symbol
94 flags uint32 // read from object file
96 syms []Sym // Sym's global index, indexed by local index
97 ndef int // cache goobj.Reader.NSym()
98 nhashed64def int // cache goobj.Reader.NHashed64Def()
99 nhasheddef int // cache goobj.Reader.NHashedDef()
100 objidx uint32 // index of this reader in the objs slice
103 // Total number of defined symbols (package symbols, hashed symbols, and
104 // non-package symbols).
105 func (r *oReader) NAlldef() int { return r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef() }
112 // objSym represents a symbol in an object file. It is a tuple of
113 // the object and the symbol's local index.
114 // For external symbols, objidx is the index of l.extReader (extObj),
115 // s is its index into the payload array.
116 // {0, 0} represents the nil symbol.
118 objidx uint32 // index of the object (in l.objs array)
119 s uint32 // local index
122 type nameVer struct {
130 func (bm Bitmap) Set(i Sym) {
131 n, r := uint(i)/32, uint(i)%32
135 // unset the i-th bit.
136 func (bm Bitmap) Unset(i Sym) {
137 n, r := uint(i)/32, uint(i)%32
141 // whether the i-th bit is set.
142 func (bm Bitmap) Has(i Sym) bool {
143 n, r := uint(i)/32, uint(i)%32
144 return bm[n]&(1<<r) != 0
147 // return current length of bitmap in bits.
148 func (bm Bitmap) Len() int {
152 // return the number of bits set.
153 func (bm Bitmap) Count() int {
155 for _, x := range bm {
156 s += bits.OnesCount32(x)
161 func MakeBitmap(n int) Bitmap {
162 return make(Bitmap, (n+31)/32)
165 // growBitmap insures that the specified bitmap has enough capacity,
166 // reallocating (doubling the size) if needed.
167 func growBitmap(reqLen int, b Bitmap) Bitmap {
170 b = append(b, MakeBitmap(reqLen+1-curLen)...)
175 type symAndSize struct {
180 // A Loader loads new object files and resolves indexed symbol references.
182 // Notes on the layout of global symbol index space:
184 // - Go object files are read before host object files; each Go object
185 // read adds its defined package symbols to the global index space.
186 // Nonpackage symbols are not yet added.
188 // - In loader.LoadNonpkgSyms, add non-package defined symbols and
189 // references in all object files to the global index space.
191 // - Host object file loading happens; the host object loader does a
192 // name/version lookup for each symbol it finds; this can wind up
193 // extending the external symbol index space range. The host object
194 // loader stores symbol payloads in loader.payloads using SymbolBuilder.
196 // - Each symbol gets a unique global index. For duplicated and
197 // overwriting/overwritten symbols, the second (or later) appearance
198 // of the symbol gets the same global index as the first appearance.
200 start map[*oReader]Sym // map from object file to its start index
201 objs []objIdx // sorted by start index (i.e. objIdx.i)
202 extStart Sym // from this index on, the symbols are externally defined
203 builtinSyms []Sym // global index of builtin symbols
205 objSyms []objSym // global index mapping to local index
207 symsByName [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
208 extStaticSyms map[nameVer]Sym // externally defined static symbols, keyed by name
210 extReader *oReader // a dummy oReader, for external symbols
211 payloadBatch []extSymPayload
212 payloads []*extSymPayload // contents of linker-materialized external syms
213 values []int64 // symbol values, indexed by global sym index
215 sects []*sym.Section // sections
216 symSects []uint16 // symbol's section, index to sects array
218 align []uint8 // symbol 2^N alignment, indexed by global index
220 deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
222 objByPkg map[string]*oReader // map package path to its Go object reader
224 anonVersion int // most recently assigned ext static sym pseudo-version
226 // Bitmaps and other side structures used to store data used to store
227 // symbol flags/attributes; these are to be accessed via the
228 // corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
229 // visit the comments on these methods for more details on the
230 // semantics / interpretation of the specific flags or attribute.
231 attrReachable Bitmap // reachable symbols, indexed by global index
232 attrOnList Bitmap // "on list" symbols, indexed by global index
233 attrLocal Bitmap // "local" symbols, indexed by global index
234 attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by global idx
235 attrUsedInIface Bitmap // "used in interface" symbols, indexed by global idx
236 attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
237 attrDuplicateOK Bitmap // dupOK symbols, indexed by ext sym index
238 attrShared Bitmap // shared symbols, indexed by ext sym index
239 attrExternal Bitmap // external symbols, indexed by ext sym index
241 attrReadOnly map[Sym]bool // readonly data for this sym
242 attrTopFrame map[Sym]struct{} // top frame symbols
243 attrSpecial map[Sym]struct{} // "special" frame symbols
244 attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
245 attrCgoExportStatic map[Sym]struct{} // "cgo_export_static" symbols
246 generatedSyms map[Sym]struct{} // symbols that generate their content
248 // Outer and Sub relations for symbols.
249 // TODO: figure out whether it's more efficient to just have these
250 // as fields on extSymPayload (note that this won't be a viable
251 // strategy if somewhere in the linker we set sub/outer for a
252 // non-external sym).
256 dynimplib map[Sym]string // stores Dynimplib symbol attribute
257 dynimpvers map[Sym]string // stores Dynimpvers symbol attribute
258 localentry map[Sym]uint8 // stores Localentry symbol attribute
259 extname map[Sym]string // stores Extname symbol attribute
260 elfType map[Sym]elf.SymType // stores elf type symbol property
261 elfSym map[Sym]int32 // stores elf sym symbol property
262 localElfSym map[Sym]int32 // stores "local" elf sym symbol property
263 symPkg map[Sym]string // stores package for symbol, or library for shlib-derived syms
264 plt map[Sym]int32 // stores dynimport for pe objects
265 got map[Sym]int32 // stores got for pe objects
266 dynid map[Sym]int32 // stores Dynid for symbol
268 relocVariant map[relocId]sym.RelocVariant // stores variant relocs
270 // Used to implement field tracking; created during deadcode if
271 // field tracking is enabled. Reachparent[K] contains the index of
272 // the symbol that triggered the marking of symbol K as live.
277 hasUnknownPkgPath bool // if any Go object has unknown package path
279 strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
281 elfsetstring elfsetstringFunc
283 errorReporter *ErrorReporter
285 npkgsyms int // number of package symbols, for accounting
286 nhashedsyms int // number of hashed symbols, for accounting
304 type elfsetstringFunc func(str string, off int)
306 // extSymPayload holds the payload (data + relocations) for linker-synthesized
307 // external symbols (note that symbol value is stored in a separate slice).
308 type extSymPayload struct {
309 name string // TODO: would this be better as offset into str table?
313 objidx uint32 // index of original object if sym made by cloneToExternal
315 reltypes []objabi.RelocType // relocation types
322 FlagStrictDups = 1 << iota
325 func NewLoader(flags uint32, elfsetstring elfsetstringFunc, reporter *ErrorReporter) *Loader {
326 nbuiltin := goobj.NBuiltin()
327 extReader := &oReader{objidx: extObj}
329 start: make(map[*oReader]Sym),
330 objs: []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
331 objSyms: make([]objSym, 1, 100000), // reserve index 0 for nil symbol
332 extReader: extReader,
333 symsByName: [2]map[string]Sym{make(map[string]Sym, 80000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
334 objByPkg: make(map[string]*oReader),
335 outer: make(map[Sym]Sym),
336 sub: make(map[Sym]Sym),
337 dynimplib: make(map[Sym]string),
338 dynimpvers: make(map[Sym]string),
339 localentry: make(map[Sym]uint8),
340 extname: make(map[Sym]string),
341 attrReadOnly: make(map[Sym]bool),
342 elfType: make(map[Sym]elf.SymType),
343 elfSym: make(map[Sym]int32),
344 localElfSym: make(map[Sym]int32),
345 symPkg: make(map[Sym]string),
346 plt: make(map[Sym]int32),
347 got: make(map[Sym]int32),
348 dynid: make(map[Sym]int32),
349 attrTopFrame: make(map[Sym]struct{}),
350 attrSpecial: make(map[Sym]struct{}),
351 attrCgoExportDynamic: make(map[Sym]struct{}),
352 attrCgoExportStatic: make(map[Sym]struct{}),
353 generatedSyms: make(map[Sym]struct{}),
354 deferReturnTramp: make(map[Sym]bool),
355 extStaticSyms: make(map[nameVer]Sym),
356 builtinSyms: make([]Sym, nbuiltin),
358 elfsetstring: elfsetstring,
359 errorReporter: reporter,
360 sects: []*sym.Section{nil}, // reserve index 0 for nil section
366 // Add object file r, return the start index.
367 func (l *Loader) addObj(pkg string, r *oReader) Sym {
368 if _, ok := l.start[r]; ok {
369 panic("already added")
371 pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
372 if _, ok := l.objByPkg[pkg]; !ok {
375 i := Sym(len(l.objSyms))
377 l.objs = append(l.objs, objIdx{r, i})
378 if r.NeedNameExpansion() && !r.FromAssembly() {
379 l.hasUnknownPkgPath = true
384 // Add a symbol from an object file, return the global index.
385 // If the symbol already exist, it returns the index of that symbol.
386 func (st *loadState) addSym(name string, ver int, r *oReader, li uint32, kind int, osym *goobj.Sym) Sym {
389 panic("addSym called after external symbol is created")
391 i := Sym(len(l.objSyms))
392 addToGlobal := func() {
393 l.objSyms = append(l.objSyms, objSym{r.objidx, li})
395 if name == "" && kind != hashed64Def && kind != hashedDef {
397 return i // unnamed aux symbol
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.
408 // Defined package symbols cannot be dup to each other.
409 // We load all the package symbols first, so we don't need
410 // to check dup here.
411 // We still add it to the lookup table, as it may still be
412 // referenced by name (e.g. through linkname).
413 l.symsByName[ver][name] = i
416 case hashed64Def, hashedDef:
417 // Hashed (content-addressable) symbol. Check the hash
418 // but don't add to name lookup table, as they are not
419 // referenced by name. Also no need to do overwriting
420 // check, as same hash indicates same content.
421 var checkHash func() (symAndSize, bool)
422 var addToHashMap func(symAndSize)
423 var h64 uint64 // only used for hashed64Def
424 var h *goobj.HashType // only used for hashedDef
425 if kind == hashed64Def {
426 checkHash = func() (symAndSize, bool) {
427 h64 = r.Hash64(li - uint32(r.ndef))
428 s, existed := st.hashed64Syms[h64]
431 addToHashMap = func(ss symAndSize) { st.hashed64Syms[h64] = ss }
433 checkHash = func() (symAndSize, bool) {
434 h = r.Hash(li - uint32(r.ndef+r.nhashed64def))
435 s, existed := st.hashedSyms[*h]
438 addToHashMap = func(ss symAndSize) { st.hashedSyms[*h] = ss }
441 if s, existed := checkHash(); existed {
442 // The content hash is built from symbol data and relocations. In the
443 // object file, the symbol data may not always contain trailing zeros,
444 // e.g. for [5]int{1,2,3} and [100]int{1,2,3}, the data is same
445 // (although the size is different).
446 // Also, for short symbols, the content hash is the identity function of
447 // the 8 bytes, and trailing zeros doesn't change the hash value, e.g.
448 // hash("A") == hash("A\0\0\0").
449 // So when two symbols have the same hash, we need to use the one with
452 // New symbol has larger size, use the new one. Rewrite the index mapping.
453 l.objSyms[s.sym] = objSym{r.objidx, li}
454 addToHashMap(symAndSize{s.sym, siz})
458 addToHashMap(symAndSize{i, siz})
463 // Non-package (named) symbol. Check if it already exists.
464 oldi, existed := l.symsByName[ver][name]
466 l.symsByName[ver][name] = i
470 // symbol already exists
472 if l.flags&FlagStrictDups != 0 {
473 l.checkdup(name, r, li, oldi)
477 oldr, oldli := l.toLocal(oldi)
478 oldsym := oldr.Sym(oldli)
482 overwrite := r.DataSize(li) != 0
484 // new symbol overwrites old symbol.
485 oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
486 if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
487 log.Fatalf("duplicated definition of symbol " + name)
489 l.objSyms[oldi] = objSym{r.objidx, li}
491 // old symbol overwrites new symbol.
492 typ := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
493 if !typ.IsData() { // only allow overwriting data symbol
494 log.Fatalf("duplicated definition of symbol " + name)
500 // newExtSym creates a new external sym with the specified
502 func (l *Loader) newExtSym(name string, ver int) Sym {
503 i := Sym(len(l.objSyms))
507 l.growValues(int(i) + 1)
508 l.growAttrBitmaps(int(i) + 1)
509 pi := l.newPayload(name, ver)
510 l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
511 l.extReader.syms = append(l.extReader.syms, i)
515 // LookupOrCreateSym looks up the symbol with the specified name/version,
516 // returning its Sym index if found. If the lookup fails, a new external
517 // Sym will be created, entered into the lookup tables, and returned.
518 func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
519 i := l.Lookup(name, ver)
523 i = l.newExtSym(name, ver)
524 static := ver >= sym.SymVerStatic || ver < 0
526 l.extStaticSyms[nameVer{name, ver}] = i
528 l.symsByName[ver][name] = i
533 func (l *Loader) IsExternal(i Sym) bool {
535 return l.isExtReader(r)
538 func (l *Loader) isExtReader(r *oReader) bool {
539 return r == l.extReader
542 // For external symbol, return its index in the payloads array.
543 // XXX result is actually not a global index. We (ab)use the Sym type
544 // so we don't need conversion for accessing bitmaps.
545 func (l *Loader) extIndex(i Sym) Sym {
546 _, li := l.toLocal(i)
550 // Get a new payload for external symbol, return its index in
551 // the payloads array.
552 func (l *Loader) newPayload(name string, ver int) int {
553 pi := len(l.payloads)
554 pp := l.allocPayload()
557 l.payloads = append(l.payloads, pp)
558 l.growExtAttrBitmaps()
562 // getPayload returns a pointer to the extSymPayload struct for an
563 // external symbol if the symbol has a payload. Will panic if the
564 // symbol in question is bogus (zero or not an external sym).
565 func (l *Loader) getPayload(i Sym) *extSymPayload {
566 if !l.IsExternal(i) {
567 panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
570 return l.payloads[pi]
573 // allocPayload allocates a new payload.
574 func (l *Loader) allocPayload() *extSymPayload {
575 batch := l.payloadBatch
577 batch = make([]extSymPayload, 1000)
580 l.payloadBatch = batch[1:]
584 func (ms *extSymPayload) Grow(siz int64) {
585 if int64(int(siz)) != siz {
586 log.Fatalf("symgrow size %d too long", siz)
588 if int64(len(ms.data)) >= siz {
591 if cap(ms.data) < int(siz) {
593 ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
594 ms.data = ms.data[0:cl]
596 ms.data = ms.data[:siz]
599 // Convert a local index to a global index.
600 func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
604 // Convert a global index to a local index.
605 func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
606 return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
609 // Resolve a local symbol reference. Return global index.
610 func (l *Loader) resolve(r *oReader, s goobj.SymRef) Sym {
612 switch p := s.PkgIdx; p {
613 case goobj.PkgIdxInvalid:
614 // {0, X} with non-zero X is never a valid sym reference from a Go object.
615 // We steal this space for symbol references from external objects.
616 // In this case, X is just the global index.
617 if l.isExtReader(r) {
624 case goobj.PkgIdxHashed64:
625 i := int(s.SymIdx) + r.ndef
627 case goobj.PkgIdxHashed:
628 i := int(s.SymIdx) + r.ndef + r.nhashed64def
630 case goobj.PkgIdxNone:
631 i := int(s.SymIdx) + r.ndef + r.nhashed64def + r.nhasheddef
633 case goobj.PkgIdxBuiltin:
634 return l.builtinSyms[s.SymIdx]
635 case goobj.PkgIdxSelf:
640 rr, ok = l.objByPkg[pkg]
642 log.Fatalf("reference of nonexisted package %s, from %v", pkg, r.unit.Lib)
645 return l.toGlobal(rr, s.SymIdx)
648 // Look up a symbol by name, return global index, or 0 if not found.
649 // This is more like Syms.ROLookup than Lookup -- it doesn't create
651 func (l *Loader) Lookup(name string, ver int) Sym {
652 if ver >= sym.SymVerStatic || ver < 0 {
653 return l.extStaticSyms[nameVer{name, ver}]
655 return l.symsByName[ver][name]
658 // Check that duplicate symbols have same contents.
659 func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
661 rdup, ldup := l.toLocal(dup)
662 pdup := rdup.Data(ldup)
663 if bytes.Equal(p, pdup) {
666 reason := "same length but different contents"
667 if len(p) != len(pdup) {
668 reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
670 fmt.Fprintf(os.Stderr, "cmd/link: while reading object for '%v': duplicate symbol '%s', previous def at '%v', with mismatched payload: %s\n", r.unit.Lib, name, rdup.unit.Lib, reason)
672 // For the moment, allow DWARF subprogram DIEs for
673 // auto-generated wrapper functions. What seems to happen
674 // here is that we get different line numbers on formal
675 // params; I am guessing that the pos is being inherited
676 // from the spot where the wrapper is needed.
677 allowed := strings.HasPrefix(name, "go.info.go.interface") ||
678 strings.HasPrefix(name, "go.info.go.builtin") ||
679 strings.HasPrefix(name, "go.debuglines")
685 func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
687 // Number of total symbols.
688 func (l *Loader) NSym() int {
689 return len(l.objSyms)
692 // Number of defined Go symbols.
693 func (l *Loader) NDef() int {
694 return int(l.extStart)
697 // Number of reachable symbols.
698 func (l *Loader) NReachableSym() int {
699 return l.attrReachable.Count()
702 // SymNameLen returns the length of the symbol name, trying hard not to load
704 func (l *Loader) SymNameLen(i Sym) int {
705 // Not much we can do about external symbols.
707 return len(l.SymName(i))
709 r, li := l.toLocal(i)
710 le := r.Sym(li).NameLen(r.Reader)
711 if !r.NeedNameExpansion() {
714 // Just load the symbol name. We don't know how expanded it'll be.
715 return len(l.SymName(i))
718 // Returns the raw (unpatched) name of the i-th symbol.
719 func (l *Loader) RawSymName(i Sym) string {
721 pp := l.getPayload(i)
724 r, li := l.toLocal(i)
725 return r.Sym(li).Name(r.Reader)
728 // Returns the (patched) name of the i-th symbol.
729 func (l *Loader) SymName(i Sym) string {
731 pp := l.getPayload(i)
734 r, li := l.toLocal(i)
735 name := r.Sym(li).Name(r.Reader)
736 if !r.NeedNameExpansion() {
739 return strings.Replace(name, "\"\".", r.pkgprefix, -1)
742 // Returns the version of the i-th symbol.
743 func (l *Loader) SymVersion(i Sym) int {
745 pp := l.getPayload(i)
748 r, li := l.toLocal(i)
749 return int(abiToVer(r.Sym(li).ABI(), r.version))
752 func (l *Loader) IsFileLocal(i Sym) bool {
753 return l.SymVersion(i) >= sym.SymVerStatic
756 // IsFromAssembly returns true if this symbol is derived from an
757 // object file generated by the Go assembler.
758 func (l *Loader) IsFromAssembly(i Sym) bool {
763 return r.FromAssembly()
766 // Returns the type of the i-th symbol.
767 func (l *Loader) SymType(i Sym) sym.SymKind {
769 pp := l.getPayload(i)
775 r, li := l.toLocal(i)
776 return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
779 // Returns the attributes of the i-th symbol.
780 func (l *Loader) SymAttr(i Sym) uint8 {
782 // TODO: do something? External symbols have different representation of attributes.
783 // For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
784 // set by external symbol.
787 r, li := l.toLocal(i)
788 return r.Sym(li).Flag()
791 // Returns the size of the i-th symbol.
792 func (l *Loader) SymSize(i Sym) int64 {
794 pp := l.getPayload(i)
797 r, li := l.toLocal(i)
798 return int64(r.Sym(li).Siz())
801 // AttrReachable returns true for symbols that are transitively
802 // referenced from the entry points. Unreachable symbols are not
803 // written to the output.
804 func (l *Loader) AttrReachable(i Sym) bool {
805 return l.attrReachable.Has(i)
808 // SetAttrReachable sets the reachability property for a symbol (see
810 func (l *Loader) SetAttrReachable(i Sym, v bool) {
812 l.attrReachable.Set(i)
814 l.attrReachable.Unset(i)
818 // AttrOnList returns true for symbols that are on some list (such as
819 // the list of all text symbols, or one of the lists of data symbols)
820 // and is consulted to avoid bugs where a symbol is put on a list
822 func (l *Loader) AttrOnList(i Sym) bool {
823 return l.attrOnList.Has(i)
826 // SetAttrOnList sets the "on list" property for a symbol (see
828 func (l *Loader) SetAttrOnList(i Sym, v bool) {
832 l.attrOnList.Unset(i)
836 // AttrLocal returns true for symbols that are only visible within the
837 // module (executable or shared library) being linked. This attribute
838 // is applied to thunks and certain other linker-generated symbols.
839 func (l *Loader) AttrLocal(i Sym) bool {
840 return l.attrLocal.Has(i)
843 // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
844 func (l *Loader) SetAttrLocal(i Sym, v bool) {
852 // AttrUsedInIface returns true for a type symbol that is used in
854 func (l *Loader) AttrUsedInIface(i Sym) bool {
855 return l.attrUsedInIface.Has(i)
858 func (l *Loader) SetAttrUsedInIface(i Sym, v bool) {
860 l.attrUsedInIface.Set(i)
862 l.attrUsedInIface.Unset(i)
866 // SymAddr checks that a symbol is reachable, and returns its value.
867 func (l *Loader) SymAddr(i Sym) int64 {
868 if !l.AttrReachable(i) {
869 panic("unreachable symbol in symaddr")
874 // AttrNotInSymbolTable returns true for symbols that should not be
875 // added to the symbol table of the final generated load module.
876 func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
877 return l.attrNotInSymbolTable.Has(i)
880 // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
881 // (see AttrNotInSymbolTable above).
882 func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
884 l.attrNotInSymbolTable.Set(i)
886 l.attrNotInSymbolTable.Unset(i)
890 // AttrVisibilityHidden symbols returns true for ELF symbols with
891 // visibility set to STV_HIDDEN. They become local symbols in
892 // the final executable. Only relevant when internally linking
893 // on an ELF platform.
894 func (l *Loader) AttrVisibilityHidden(i Sym) bool {
895 if !l.IsExternal(i) {
898 return l.attrVisibilityHidden.Has(l.extIndex(i))
901 // SetAttrVisibilityHidden sets the "hidden visibility" property for a
902 // symbol (see AttrVisibilityHidden).
903 func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
904 if !l.IsExternal(i) {
905 panic("tried to set visibility attr on non-external symbol")
908 l.attrVisibilityHidden.Set(l.extIndex(i))
910 l.attrVisibilityHidden.Unset(l.extIndex(i))
914 // AttrDuplicateOK returns true for a symbol that can be present in
915 // multiple object files.
916 func (l *Loader) AttrDuplicateOK(i Sym) bool {
917 if !l.IsExternal(i) {
918 // TODO: if this path winds up being taken frequently, it
919 // might make more sense to copy the flag value out of the object
920 // into a larger bitmap during preload.
921 r, li := l.toLocal(i)
922 return r.Sym(li).Dupok()
924 return l.attrDuplicateOK.Has(l.extIndex(i))
927 // SetAttrDuplicateOK sets the "duplicate OK" property for an external
928 // symbol (see AttrDuplicateOK).
929 func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
930 if !l.IsExternal(i) {
931 panic("tried to set dupok attr on non-external symbol")
934 l.attrDuplicateOK.Set(l.extIndex(i))
936 l.attrDuplicateOK.Unset(l.extIndex(i))
940 // AttrShared returns true for symbols compiled with the -shared option.
941 func (l *Loader) AttrShared(i Sym) bool {
942 if !l.IsExternal(i) {
943 // TODO: if this path winds up being taken frequently, it
944 // might make more sense to copy the flag value out of the
945 // object into a larger bitmap during preload.
949 return l.attrShared.Has(l.extIndex(i))
952 // SetAttrShared sets the "shared" property for an external
953 // symbol (see AttrShared).
954 func (l *Loader) SetAttrShared(i Sym, v bool) {
955 if !l.IsExternal(i) {
956 panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
959 l.attrShared.Set(l.extIndex(i))
961 l.attrShared.Unset(l.extIndex(i))
965 // AttrExternal returns true for function symbols loaded from host
967 func (l *Loader) AttrExternal(i Sym) bool {
968 if !l.IsExternal(i) {
971 return l.attrExternal.Has(l.extIndex(i))
974 // SetAttrExternal sets the "external" property for an host object
975 // symbol (see AttrExternal).
976 func (l *Loader) SetAttrExternal(i Sym, v bool) {
977 if !l.IsExternal(i) {
978 panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.RawSymName(i)))
981 l.attrExternal.Set(l.extIndex(i))
983 l.attrExternal.Unset(l.extIndex(i))
987 // AttrTopFrame returns true for a function symbol that is an entry
988 // point, meaning that unwinders should stop when they hit this
990 func (l *Loader) AttrTopFrame(i Sym) bool {
991 _, ok := l.attrTopFrame[i]
995 // SetAttrTopFrame sets the "top frame" property for a symbol (see
997 func (l *Loader) SetAttrTopFrame(i Sym, v bool) {
999 l.attrTopFrame[i] = struct{}{}
1001 delete(l.attrTopFrame, i)
1005 // AttrSpecial returns true for a symbols that do not have their
1006 // address (i.e. Value) computed by the usual mechanism of
1007 // data.go:dodata() & data.go:address().
1008 func (l *Loader) AttrSpecial(i Sym) bool {
1009 _, ok := l.attrSpecial[i]
1013 // SetAttrSpecial sets the "special" property for a symbol (see
1015 func (l *Loader) SetAttrSpecial(i Sym, v bool) {
1017 l.attrSpecial[i] = struct{}{}
1019 delete(l.attrSpecial, i)
1023 // AttrCgoExportDynamic returns true for a symbol that has been
1024 // specially marked via the "cgo_export_dynamic" compiler directive
1025 // written by cgo (in response to //export directives in the source).
1026 func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
1027 _, ok := l.attrCgoExportDynamic[i]
1031 // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
1032 // (see AttrCgoExportDynamic).
1033 func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
1035 l.attrCgoExportDynamic[i] = struct{}{}
1037 delete(l.attrCgoExportDynamic, i)
1041 // AttrCgoExportStatic returns true for a symbol that has been
1042 // specially marked via the "cgo_export_static" directive
1044 func (l *Loader) AttrCgoExportStatic(i Sym) bool {
1045 _, ok := l.attrCgoExportStatic[i]
1049 // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
1050 // (see AttrCgoExportStatic).
1051 func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
1053 l.attrCgoExportStatic[i] = struct{}{}
1055 delete(l.attrCgoExportStatic, i)
1059 // IsGeneratedSym returns true if a symbol's been previously marked as a
1060 // generator symbol through the SetIsGeneratedSym. The functions for generator
1061 // symbols are kept in the Link context.
1062 func (l *Loader) IsGeneratedSym(i Sym) bool {
1063 _, ok := l.generatedSyms[i]
1067 // SetIsGeneratedSym marks symbols as generated symbols. Data shouldn't be
1068 // stored in generated symbols, and a function is registered and called for
1069 // each of these symbols.
1070 func (l *Loader) SetIsGeneratedSym(i Sym, v bool) {
1071 if !l.IsExternal(i) {
1072 panic("only external symbols can be generated")
1075 l.generatedSyms[i] = struct{}{}
1077 delete(l.generatedSyms, i)
1081 func (l *Loader) AttrCgoExport(i Sym) bool {
1082 return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
1085 // AttrReadOnly returns true for a symbol whose underlying data
1086 // is stored via a read-only mmap.
1087 func (l *Loader) AttrReadOnly(i Sym) bool {
1088 if v, ok := l.attrReadOnly[i]; ok {
1091 if l.IsExternal(i) {
1092 pp := l.getPayload(i)
1094 return l.objs[pp.objidx].r.ReadOnly()
1098 r, _ := l.toLocal(i)
1102 // SetAttrReadOnly sets the "data is read only" property for a symbol
1103 // (see AttrReadOnly).
1104 func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
1105 l.attrReadOnly[i] = v
1108 // AttrSubSymbol returns true for symbols that are listed as a
1109 // sub-symbol of some other outer symbol. The sub/outer mechanism is
1110 // used when loading host objects (sections from the host object
1111 // become regular linker symbols and symbols go on the Sub list of
1112 // their section) and for constructing the global offset table when
1113 // internally linking a dynamic executable.
1115 // Note that in later stages of the linker, we set Outer(S) to some
1116 // container symbol C, but don't set Sub(C). Thus we have two
1117 // distinct scenarios:
1119 // - Outer symbol covers the address ranges of its sub-symbols.
1120 // Outer.Sub is set in this case.
1121 // - Outer symbol doesn't conver the address ranges. It is zero-sized
1122 // and doesn't have sub-symbols. In the case, the inner symbol is
1123 // not actually a "SubSymbol". (Tricky!)
1125 // This method returns TRUE only for sub-symbols in the first scenario.
1127 // FIXME: would be better to do away with this and have a better way
1128 // to represent container symbols.
1130 func (l *Loader) AttrSubSymbol(i Sym) bool {
1131 // we don't explicitly store this attribute any more -- return
1132 // a value based on the sub-symbol setting.
1137 return l.SubSym(o) != 0
1140 // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
1141 // clients should instead use the AddInteriorSym method to establish
1142 // containment relationships for host object symbols.
1144 // Returns whether the i-th symbol has ReflectMethod attribute set.
1145 func (l *Loader) IsReflectMethod(i Sym) bool {
1146 return l.SymAttr(i)&goobj.SymFlagReflectMethod != 0
1149 // Returns whether the i-th symbol is nosplit.
1150 func (l *Loader) IsNoSplit(i Sym) bool {
1151 return l.SymAttr(i)&goobj.SymFlagNoSplit != 0
1154 // Returns whether this is a Go type symbol.
1155 func (l *Loader) IsGoType(i Sym) bool {
1156 return l.SymAttr(i)&goobj.SymFlagGoType != 0
1159 // Returns whether this symbol should be included in typelink.
1160 func (l *Loader) IsTypelink(i Sym) bool {
1161 return l.SymAttr(i)&goobj.SymFlagTypelink != 0
1164 // Returns whether this symbol is an itab symbol.
1165 func (l *Loader) IsItab(i Sym) bool {
1166 if l.IsExternal(i) {
1169 r, li := l.toLocal(i)
1170 return r.Sym(li).IsItab()
1173 // Return whether this is a trampoline of a deferreturn call.
1174 func (l *Loader) IsDeferReturnTramp(i Sym) bool {
1175 return l.deferReturnTramp[i]
1178 // Set that i is a trampoline of a deferreturn call.
1179 func (l *Loader) SetIsDeferReturnTramp(i Sym, v bool) {
1180 l.deferReturnTramp[i] = v
1183 // growValues grows the slice used to store symbol values.
1184 func (l *Loader) growValues(reqLen int) {
1185 curLen := len(l.values)
1186 if reqLen > curLen {
1187 l.values = append(l.values, make([]int64, reqLen+1-curLen)...)
1191 // SymValue returns the value of the i-th symbol. i is global index.
1192 func (l *Loader) SymValue(i Sym) int64 {
1196 // SetSymValue sets the value of the i-th symbol. i is global index.
1197 func (l *Loader) SetSymValue(i Sym, val int64) {
1201 // AddToSymValue adds to the value of the i-th symbol. i is the global index.
1202 func (l *Loader) AddToSymValue(i Sym, val int64) {
1206 // Returns the symbol content of the i-th symbol. i is global index.
1207 func (l *Loader) Data(i Sym) []byte {
1208 if l.IsExternal(i) {
1209 pp := l.getPayload(i)
1215 r, li := l.toLocal(i)
1219 // FreeData clears the symbol data of an external symbol, allowing the memory
1220 // to be freed earlier. No-op for non-external symbols.
1221 // i is global index.
1222 func (l *Loader) FreeData(i Sym) {
1223 if l.IsExternal(i) {
1224 pp := l.getPayload(i)
1231 // SymAlign returns the alignment for a symbol.
1232 func (l *Loader) SymAlign(i Sym) int32 {
1233 if int(i) >= len(l.align) {
1234 // align is extended lazily -- it the sym in question is
1235 // outside the range of the existing slice, then we assume its
1236 // alignment has not yet been set.
1239 // TODO: would it make sense to return an arch-specific
1240 // alignment depending on section type? E.g. STEXT => 32,
1246 return int32(1 << (abits - 1))
1249 // SetSymAlign sets the alignment for a symbol.
1250 func (l *Loader) SetSymAlign(i Sym, align int32) {
1251 // Reject nonsense alignments.
1252 if align < 0 || align&(align-1) != 0 {
1253 panic("bad alignment value")
1255 if int(i) >= len(l.align) {
1256 l.align = append(l.align, make([]uint8, l.NSym()-len(l.align))...)
1261 l.align[i] = uint8(bits.Len32(uint32(align)))
1264 // SymValue returns the section of the i-th symbol. i is global index.
1265 func (l *Loader) SymSect(i Sym) *sym.Section {
1266 if int(i) >= len(l.symSects) {
1267 // symSects is extended lazily -- it the sym in question is
1268 // outside the range of the existing slice, then we assume its
1269 // section has not yet been set.
1272 return l.sects[l.symSects[i]]
1275 // SetSymSect sets the section of the i-th symbol. i is global index.
1276 func (l *Loader) SetSymSect(i Sym, sect *sym.Section) {
1277 if int(i) >= len(l.symSects) {
1278 l.symSects = append(l.symSects, make([]uint16, l.NSym()-len(l.symSects))...)
1280 l.symSects[i] = sect.Index
1283 // growSects grows the slice used to store symbol sections.
1284 func (l *Loader) growSects(reqLen int) {
1285 curLen := len(l.symSects)
1286 if reqLen > curLen {
1287 l.symSects = append(l.symSects, make([]uint16, reqLen+1-curLen)...)
1291 // NewSection creates a new (output) section.
1292 func (l *Loader) NewSection() *sym.Section {
1293 sect := new(sym.Section)
1295 if idx != int(uint16(idx)) {
1296 panic("too many sections created")
1298 sect.Index = uint16(idx)
1299 l.sects = append(l.sects, sect)
1303 // SymDynImplib returns the "dynimplib" attribute for the specified
1304 // symbol, making up a portion of the info for a symbol specified
1305 // on a "cgo_import_dynamic" compiler directive.
1306 func (l *Loader) SymDynimplib(i Sym) string {
1307 return l.dynimplib[i]
1310 // SetSymDynimplib sets the "dynimplib" attribute for a symbol.
1311 func (l *Loader) SetSymDynimplib(i Sym, value string) {
1312 // reject bad symbols
1313 if i >= Sym(len(l.objSyms)) || i == 0 {
1314 panic("bad symbol index in SetDynimplib")
1317 delete(l.dynimplib, i)
1319 l.dynimplib[i] = value
1323 // SymDynimpvers returns the "dynimpvers" attribute for the specified
1324 // symbol, making up a portion of the info for a symbol specified
1325 // on a "cgo_import_dynamic" compiler directive.
1326 func (l *Loader) SymDynimpvers(i Sym) string {
1327 return l.dynimpvers[i]
1330 // SetSymDynimpvers sets the "dynimpvers" attribute for a symbol.
1331 func (l *Loader) SetSymDynimpvers(i Sym, value string) {
1332 // reject bad symbols
1333 if i >= Sym(len(l.objSyms)) || i == 0 {
1334 panic("bad symbol index in SetDynimpvers")
1337 delete(l.dynimpvers, i)
1339 l.dynimpvers[i] = value
1343 // SymExtname returns the "extname" value for the specified
1345 func (l *Loader) SymExtname(i Sym) string {
1346 if s, ok := l.extname[i]; ok {
1352 // SetSymExtname sets the "extname" attribute for a symbol.
1353 func (l *Loader) SetSymExtname(i Sym, value string) {
1354 // reject bad symbols
1355 if i >= Sym(len(l.objSyms)) || i == 0 {
1356 panic("bad symbol index in SetExtname")
1359 delete(l.extname, i)
1361 l.extname[i] = value
1365 // SymElfType returns the previously recorded ELF type for a symbol
1366 // (used only for symbols read from shared libraries by ldshlibsyms).
1367 // It is not set for symbols defined by the packages being linked or
1368 // by symbols read by ldelf (and so is left as elf.STT_NOTYPE).
1369 func (l *Loader) SymElfType(i Sym) elf.SymType {
1370 if et, ok := l.elfType[i]; ok {
1373 return elf.STT_NOTYPE
1376 // SetSymElfType sets the elf type attribute for a symbol.
1377 func (l *Loader) SetSymElfType(i Sym, et elf.SymType) {
1378 // reject bad symbols
1379 if i >= Sym(len(l.objSyms)) || i == 0 {
1380 panic("bad symbol index in SetSymElfType")
1382 if et == elf.STT_NOTYPE {
1383 delete(l.elfType, i)
1389 // SymElfSym returns the ELF symbol index for a given loader
1390 // symbol, assigned during ELF symtab generation.
1391 func (l *Loader) SymElfSym(i Sym) int32 {
1395 // SetSymElfSym sets the elf symbol index for a symbol.
1396 func (l *Loader) SetSymElfSym(i Sym, es int32) {
1398 panic("bad sym index")
1407 // SymLocalElfSym returns the "local" ELF symbol index for a given loader
1408 // symbol, assigned during ELF symtab generation.
1409 func (l *Loader) SymLocalElfSym(i Sym) int32 {
1410 return l.localElfSym[i]
1413 // SetSymLocalElfSym sets the "local" elf symbol index for a symbol.
1414 func (l *Loader) SetSymLocalElfSym(i Sym, es int32) {
1416 panic("bad sym index")
1419 delete(l.localElfSym, i)
1421 l.localElfSym[i] = es
1425 // SymPlt returns the plt value for pe symbols.
1426 func (l *Loader) SymPlt(s Sym) int32 {
1427 if v, ok := l.plt[s]; ok {
1433 // SetPlt sets the plt value for pe symbols.
1434 func (l *Loader) SetPlt(i Sym, v int32) {
1435 if i >= Sym(len(l.objSyms)) || i == 0 {
1436 panic("bad symbol for SetPlt")
1445 // SymGot returns the got value for pe symbols.
1446 func (l *Loader) SymGot(s Sym) int32 {
1447 if v, ok := l.got[s]; ok {
1453 // SetGot sets the got value for pe symbols.
1454 func (l *Loader) SetGot(i Sym, v int32) {
1455 if i >= Sym(len(l.objSyms)) || i == 0 {
1456 panic("bad symbol for SetGot")
1465 // SymDynid returns the "dynid" property for the specified symbol.
1466 func (l *Loader) SymDynid(i Sym) int32 {
1467 if s, ok := l.dynid[i]; ok {
1473 // SetSymDynid sets the "dynid" property for a symbol.
1474 func (l *Loader) SetSymDynid(i Sym, val int32) {
1475 // reject bad symbols
1476 if i >= Sym(len(l.objSyms)) || i == 0 {
1477 panic("bad symbol index in SetSymDynid")
1486 // DynIdSyms returns the set of symbols for which dynID is set to an
1487 // interesting (non-default) value. This is expected to be a fairly
1489 func (l *Loader) DynidSyms() []Sym {
1490 sl := make([]Sym, 0, len(l.dynid))
1491 for s := range l.dynid {
1494 sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
1498 // SymGoType returns the 'Gotype' property for a given symbol (set by
1499 // the Go compiler for variable symbols). This version relies on
1500 // reading aux symbols for the target sym -- it could be that a faster
1501 // approach would be to check for gotype during preload and copy the
1502 // results in to a map (might want to try this at some point and see
1503 // if it helps speed things up).
1504 func (l *Loader) SymGoType(i Sym) Sym {
1506 var auxs []goobj.Aux
1507 if l.IsExternal(i) {
1508 pp := l.getPayload(i)
1509 r = l.objs[pp.objidx].r
1513 r, li = l.toLocal(i)
1516 for j := range auxs {
1519 case goobj.AuxGotype:
1520 return l.resolve(r, a.Sym())
1526 // SymUnit returns the compilation unit for a given symbol (which will
1527 // typically be nil for external or linker-manufactured symbols).
1528 func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
1529 if l.IsExternal(i) {
1530 pp := l.getPayload(i)
1532 r := l.objs[pp.objidx].r
1537 r, _ := l.toLocal(i)
1541 // SymPkg returns the package where the symbol came from (for
1542 // regular compiler-generated Go symbols), but in the case of
1543 // building with "-linkshared" (when a symbol is read from a
1544 // shared library), will hold the library name.
1545 // NOTE: this correspondes to sym.Symbol.File field.
1546 func (l *Loader) SymPkg(i Sym) string {
1547 if f, ok := l.symPkg[i]; ok {
1550 if l.IsExternal(i) {
1551 pp := l.getPayload(i)
1553 r := l.objs[pp.objidx].r
1554 return r.unit.Lib.Pkg
1558 r, _ := l.toLocal(i)
1559 return r.unit.Lib.Pkg
1562 // SetSymPkg sets the package/library for a symbol. This is
1563 // needed mainly for external symbols, specifically those imported
1564 // from shared libraries.
1565 func (l *Loader) SetSymPkg(i Sym, pkg string) {
1566 // reject bad symbols
1567 if i >= Sym(len(l.objSyms)) || i == 0 {
1568 panic("bad symbol index in SetSymPkg")
1573 // SymLocalentry returns the "local entry" value for the specified
1575 func (l *Loader) SymLocalentry(i Sym) uint8 {
1576 return l.localentry[i]
1579 // SetSymLocalentry sets the "local entry" attribute for a symbol.
1580 func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
1581 // reject bad symbols
1582 if i >= Sym(len(l.objSyms)) || i == 0 {
1583 panic("bad symbol index in SetSymLocalentry")
1586 delete(l.localentry, i)
1588 l.localentry[i] = value
1592 // Returns the number of aux symbols given a global index.
1593 func (l *Loader) NAux(i Sym) int {
1594 if l.IsExternal(i) {
1597 r, li := l.toLocal(i)
1601 // Returns the "handle" to the j-th aux symbol of the i-th symbol.
1602 func (l *Loader) Aux(i Sym, j int) Aux {
1603 if l.IsExternal(i) {
1606 r, li := l.toLocal(i)
1607 if j >= r.NAux(li) {
1610 return Aux{r.Aux(li, j), r, l}
1613 // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
1614 // symbols associated with a given function symbol. Prior to the
1615 // introduction of the loader, this was done purely using name
1616 // lookups, e.f. for function with name XYZ we would then look up
1617 // go.info.XYZ, etc.
1618 func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
1619 if l.SymType(fnSymIdx) != sym.STEXT {
1620 log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1622 if l.IsExternal(fnSymIdx) {
1623 // Current expectation is that any external function will
1624 // not have auxsyms.
1627 r, li := l.toLocal(fnSymIdx)
1629 for i := range auxs {
1632 case goobj.AuxDwarfInfo:
1633 auxDwarfInfo = l.resolve(r, a.Sym())
1634 if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
1635 panic("aux dwarf info sym with wrong type")
1637 case goobj.AuxDwarfLoc:
1638 auxDwarfLoc = l.resolve(r, a.Sym())
1639 if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
1640 panic("aux dwarf loc sym with wrong type")
1642 case goobj.AuxDwarfRanges:
1643 auxDwarfRanges = l.resolve(r, a.Sym())
1644 if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
1645 panic("aux dwarf ranges sym with wrong type")
1647 case goobj.AuxDwarfLines:
1648 auxDwarfLines = l.resolve(r, a.Sym())
1649 if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
1650 panic("aux dwarf lines sym with wrong type")
1657 // AddInteriorSym sets up 'interior' as an interior symbol of
1658 // container/payload symbol 'container'. An interior symbol does not
1659 // itself have data, but gives a name to a subrange of the data in its
1660 // container symbol. The container itself may or may not have a name.
1661 // This method is intended primarily for use in the host object
1662 // loaders, to capture the semantics of symbols and sections in an
1663 // object file. When reading a host object file, we'll typically
1664 // encounter a static section symbol (ex: ".text") containing content
1665 // for a collection of functions, then a series of ELF (or macho, etc)
1666 // symbol table entries each of which points into a sub-section
1667 // (offset and length) of its corresponding container symbol. Within
1668 // the go linker we create a loader.Sym for the container (which is
1669 // expected to have the actual content/payload) and then a set of
1670 // interior loader.Sym's that point into a portion of the container.
1671 func (l *Loader) AddInteriorSym(container Sym, interior Sym) {
1672 // Container symbols are expected to have content/data.
1673 // NB: this restriction may turn out to be too strict (it's possible
1674 // to imagine a zero-sized container with an interior symbol pointing
1675 // into it); it's ok to relax or remove it if we counter an
1676 // oddball host object that triggers this.
1677 if l.SymSize(container) == 0 && len(l.Data(container)) == 0 {
1678 panic("unexpected empty container symbol")
1680 // The interior symbols for a container are not expected to have
1681 // content/data or relocations.
1682 if len(l.Data(interior)) != 0 {
1683 panic("unexpected non-empty interior symbol")
1685 // Interior symbol is expected to be in the symbol table.
1686 if l.AttrNotInSymbolTable(interior) {
1687 panic("interior symbol must be in symtab")
1689 // Only a single level of containment is allowed.
1690 if l.OuterSym(container) != 0 {
1691 panic("outer has outer itself")
1693 // Interior sym should not already have a sibling.
1694 if l.SubSym(interior) != 0 {
1695 panic("sub set for subsym")
1697 // Interior sym should not already point at a container.
1698 if l.OuterSym(interior) != 0 {
1699 panic("outer already set for subsym")
1701 l.sub[interior] = l.sub[container]
1702 l.sub[container] = interior
1703 l.outer[interior] = container
1706 // OuterSym gets the outer symbol for host object loaded symbols.
1707 func (l *Loader) OuterSym(i Sym) Sym {
1708 // FIXME: add check for isExternal?
1712 // SubSym gets the subsymbol for host object loaded symbols.
1713 func (l *Loader) SubSym(i Sym) Sym {
1714 // NB: note -- no check for l.isExternal(), since I am pretty sure
1715 // that later phases in the linker set subsym for "type." syms
1719 // SetCarrierSym declares that 'c' is the carrier or container symbol
1720 // for 's'. Carrier symbols are used in the linker to as a container
1721 // for a collection of sub-symbols where the content of the
1722 // sub-symbols is effectively concatenated to form the content of the
1723 // carrier. The carrier is given a name in the output symbol table
1724 // while the sub-symbol names are not. For example, the Go compiler
1725 // emits named string symbols (type SGOSTRING) when compiling a
1726 // package; after being deduplicated, these symbols are collected into
1727 // a single unit by assigning them a new carrier symbol named
1728 // "go.string.*" (which appears in the final symbol table for the
1729 // output load module).
1730 func (l *Loader) SetCarrierSym(s Sym, c Sym) {
1732 panic("invalid carrier in SetCarrierSym")
1735 panic("invalid sub-symbol in SetCarrierSym")
1737 // Carrier symbols are not expected to have content/data. It is
1738 // ok for them to have non-zero size (to allow for use of generator
1740 if len(l.Data(c)) != 0 {
1741 panic("unexpected non-empty carrier symbol")
1744 // relocsym's foldSubSymbolOffset requires that we only
1745 // have a single level of containment-- enforce here.
1746 if l.outer[c] != 0 {
1747 panic("invalid nested carrier sym")
1751 // Initialize Reachable bitmap and its siblings for running deadcode pass.
1752 func (l *Loader) InitReachable() {
1753 l.growAttrBitmaps(l.NSym() + 1)
1756 type symWithVal struct {
1760 type bySymValue []symWithVal
1762 func (s bySymValue) Len() int { return len(s) }
1763 func (s bySymValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1764 func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
1766 // SortSub walks through the sub-symbols for 's' and sorts them
1767 // in place by increasing value. Return value is the new
1768 // sub symbol for the specified outer symbol.
1769 func (l *Loader) SortSub(s Sym) Sym {
1771 if s == 0 || l.sub[s] == 0 {
1775 // Sort symbols using a slice first. Use a stable sort on the off
1776 // chance that there's more than once symbol with the same value,
1777 // so as to preserve reproducible builds.
1778 sl := []symWithVal{}
1779 for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
1780 sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
1782 sort.Stable(bySymValue(sl))
1784 // Then apply any changes needed to the sub map.
1786 for i := len(sl) - 1; i >= 0; i-- {
1792 // Update sub for outer symbol, then return
1797 // Insure that reachable bitmap and its siblings have enough size.
1798 func (l *Loader) growAttrBitmaps(reqLen int) {
1799 if reqLen > l.attrReachable.Len() {
1800 // These are indexed by global symbol
1801 l.attrReachable = growBitmap(reqLen, l.attrReachable)
1802 l.attrOnList = growBitmap(reqLen, l.attrOnList)
1803 l.attrLocal = growBitmap(reqLen, l.attrLocal)
1804 l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
1805 l.attrUsedInIface = growBitmap(reqLen, l.attrUsedInIface)
1807 l.growExtAttrBitmaps()
1810 func (l *Loader) growExtAttrBitmaps() {
1811 // These are indexed by external symbol index (e.g. l.extIndex(i))
1812 extReqLen := len(l.payloads)
1813 if extReqLen > l.attrVisibilityHidden.Len() {
1814 l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
1815 l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
1816 l.attrShared = growBitmap(extReqLen, l.attrShared)
1817 l.attrExternal = growBitmap(extReqLen, l.attrExternal)
1821 func (relocs *Relocs) Count() int { return len(relocs.rs) }
1823 // At returns the j-th reloc for a global symbol.
1824 func (relocs *Relocs) At(j int) Reloc {
1825 if relocs.l.isExtReader(relocs.r) {
1826 pp := relocs.l.payloads[relocs.li]
1827 return Reloc{&relocs.rs[j], relocs.r, relocs.l, pp.reltypes[j]}
1829 return Reloc{&relocs.rs[j], relocs.r, relocs.l, 0}
1832 // Relocs returns a Relocs object for the given global sym.
1833 func (l *Loader) Relocs(i Sym) Relocs {
1834 r, li := l.toLocal(i)
1836 panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
1838 return l.relocs(r, li)
1841 // Relocs returns a Relocs object given a local sym index and reader.
1842 func (l *Loader) relocs(r *oReader, li uint32) Relocs {
1843 var rs []goobj.Reloc
1844 if l.isExtReader(r) {
1845 pp := l.payloads[li]
1858 // FuncInfo provides hooks to access goobj.FuncInfo in the objects.
1859 type FuncInfo struct {
1864 lengths goobj.FuncInfoLengths
1867 func (fi *FuncInfo) Valid() bool { return fi.r != nil }
1869 func (fi *FuncInfo) Args() int {
1870 return int((*goobj.FuncInfo)(nil).ReadArgs(fi.data))
1873 func (fi *FuncInfo) Locals() int {
1874 return int((*goobj.FuncInfo)(nil).ReadLocals(fi.data))
1877 func (fi *FuncInfo) FuncID() objabi.FuncID {
1878 return objabi.FuncID((*goobj.FuncInfo)(nil).ReadFuncID(fi.data))
1881 func (fi *FuncInfo) Pcsp() Sym {
1882 sym := (*goobj.FuncInfo)(nil).ReadPcsp(fi.data)
1883 return fi.l.resolve(fi.r, sym)
1886 func (fi *FuncInfo) Pcfile() Sym {
1887 sym := (*goobj.FuncInfo)(nil).ReadPcfile(fi.data)
1888 return fi.l.resolve(fi.r, sym)
1891 func (fi *FuncInfo) Pcline() Sym {
1892 sym := (*goobj.FuncInfo)(nil).ReadPcline(fi.data)
1893 return fi.l.resolve(fi.r, sym)
1896 func (fi *FuncInfo) Pcinline() Sym {
1897 sym := (*goobj.FuncInfo)(nil).ReadPcinline(fi.data)
1898 return fi.l.resolve(fi.r, sym)
1901 // Preload has to be called prior to invoking the various methods
1902 // below related to pcdata, funcdataoff, files, and inltree nodes.
1903 func (fi *FuncInfo) Preload() {
1904 fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
1907 func (fi *FuncInfo) Pcdata() []Sym {
1908 if !fi.lengths.Initialized {
1909 panic("need to call Preload first")
1911 syms := (*goobj.FuncInfo)(nil).ReadPcdata(fi.data)
1912 ret := make([]Sym, len(syms))
1913 for i := range ret {
1914 ret[i] = fi.l.resolve(fi.r, syms[i])
1919 func (fi *FuncInfo) NumFuncdataoff() uint32 {
1920 if !fi.lengths.Initialized {
1921 panic("need to call Preload first")
1923 return fi.lengths.NumFuncdataoff
1926 func (fi *FuncInfo) Funcdataoff(k int) int64 {
1927 if !fi.lengths.Initialized {
1928 panic("need to call Preload first")
1930 return (*goobj.FuncInfo)(nil).ReadFuncdataoff(fi.data, fi.lengths.FuncdataoffOff, uint32(k))
1933 func (fi *FuncInfo) Funcdata(syms []Sym) []Sym {
1934 if !fi.lengths.Initialized {
1935 panic("need to call Preload first")
1937 if int(fi.lengths.NumFuncdataoff) > cap(syms) {
1938 syms = make([]Sym, 0, fi.lengths.NumFuncdataoff)
1942 for j := range fi.auxs {
1944 if a.Type() == goobj.AuxFuncdata {
1945 syms = append(syms, fi.l.resolve(fi.r, a.Sym()))
1951 func (fi *FuncInfo) NumFile() uint32 {
1952 if !fi.lengths.Initialized {
1953 panic("need to call Preload first")
1955 return fi.lengths.NumFile
1958 func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
1959 if !fi.lengths.Initialized {
1960 panic("need to call Preload first")
1962 return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
1965 type InlTreeNode struct {
1967 File goobj.CUFileIndex
1973 func (fi *FuncInfo) NumInlTree() uint32 {
1974 if !fi.lengths.Initialized {
1975 panic("need to call Preload first")
1977 return fi.lengths.NumInlTree
1980 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
1981 if !fi.lengths.Initialized {
1982 panic("need to call Preload first")
1984 node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
1986 Parent: node.Parent,
1989 Func: fi.l.resolve(fi.r, node.Func),
1990 ParentPC: node.ParentPC,
1994 func (l *Loader) FuncInfo(i Sym) FuncInfo {
1996 var auxs []goobj.Aux
1997 if l.IsExternal(i) {
1998 pp := l.getPayload(i)
2002 r = l.objs[pp.objidx].r
2006 r, li = l.toLocal(i)
2009 for j := range auxs {
2011 if a.Type() == goobj.AuxFuncInfo {
2012 b := r.Data(a.Sym().SymIdx)
2013 return FuncInfo{l, r, b, auxs, goobj.FuncInfoLengths{}}
2019 // Preload a package: add autolibs, add defined package symbols to the symbol table.
2020 // Does not add non-package symbols yet, which will be done in LoadNonpkgSyms.
2021 // Does not read symbol data.
2022 // Returns the fingerprint of the object.
2023 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
2024 roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
2026 log.Fatal("cannot read object file:", err)
2028 r := goobj.NewReaderFromBytes(roObject, readonly)
2030 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
2031 log.Fatalf("found object file %s in old format", f.File().Name())
2033 panic("cannot read object file")
2035 pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
2037 nhashed64def := r.NHashed64def()
2038 nhasheddef := r.NHasheddef()
2042 version: localSymVersion,
2044 pkgprefix: pkgprefix,
2045 syms: make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
2047 nhasheddef: nhasheddef,
2048 nhashed64def: nhashed64def,
2049 objidx: uint32(len(l.objs)),
2053 lib.Autolib = append(lib.Autolib, r.Autolib()...)
2057 unit.FileTable = make([]string, nfile)
2058 for i := range unit.FileTable {
2059 unit.FileTable[i] = r.File(i)
2062 l.addObj(lib.Pkg, or)
2063 st := loadState{l: l}
2064 st.preloadSyms(or, pkgDef)
2066 // The caller expects us consuming all the data
2067 f.MustSeek(length, os.SEEK_CUR)
2069 return r.Fingerprint()
2072 // Holds the loader along with temporary states for loading symbols.
2073 type loadState struct {
2075 hashed64Syms map[uint64]symAndSize // short hashed (content-addressable) symbols, keyed by content hash
2076 hashedSyms map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
2079 // Preload symbols of given kind from an object.
2080 func (st *loadState) preloadSyms(r *oReader, kind int) {
2082 var start, end uint32
2086 end = uint32(r.ndef)
2088 start = uint32(r.ndef)
2089 end = uint32(r.ndef + r.nhashed64def)
2091 start = uint32(r.ndef + r.nhashed64def)
2092 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2093 if l.hasUnknownPkgPath {
2094 // The content hash depends on symbol name expansion. If any package is
2095 // built without fully expanded names, the content hash is unreliable.
2096 // Treat them as named symbols.
2098 // (We don't need to do this for hashed64Def case, as there the hash
2099 // function is simply the identity function, which doesn't depend on
2104 start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2105 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
2107 panic("preloadSyms: bad kind")
2109 l.growAttrBitmaps(len(l.objSyms) + int(end-start))
2110 needNameExpansion := r.NeedNameExpansion()
2111 loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
2112 for i := start; i < end; i++ {
2116 if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
2117 name = osym.Name(r.Reader)
2118 if needNameExpansion {
2119 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2121 v = abiToVer(osym.ABI(), r.version)
2123 gi := st.addSym(name, v, r, i, kind, osym)
2125 if osym.TopFrame() {
2126 l.SetAttrTopFrame(gi, true)
2129 l.SetAttrLocal(gi, true)
2131 if osym.UsedInIface() {
2132 l.SetAttrUsedInIface(gi, true)
2134 if strings.HasPrefix(name, "runtime.") ||
2135 (loadingRuntimePkg && strings.HasPrefix(name, "type.")) {
2136 if bi := goobj.BuiltinIdx(name, v); bi != -1 {
2137 // This is a definition of a builtin symbol. Record where it is.
2138 l.builtinSyms[bi] = gi
2141 if a := int32(osym.Align()); a != 0 && a > l.SymAlign(gi) {
2142 l.SetSymAlign(gi, a)
2147 // Add hashed (content-addressable) symbols, non-package symbols, and
2148 // references to external symbols (which are always named).
2149 func (l *Loader) LoadNonpkgSyms(arch *sys.Arch) {
2150 l.npkgsyms = l.NSym()
2151 // Preallocate some space (a few hundreds KB) for some symbols.
2152 // As of Go 1.15, linking cmd/compile has ~8000 hashed64 symbols and
2153 // ~13000 hashed symbols.
2156 hashed64Syms: make(map[uint64]symAndSize, 10000),
2157 hashedSyms: make(map[goobj.HashType]symAndSize, 15000),
2159 for _, o := range l.objs[goObjStart:] {
2160 st.preloadSyms(o.r, hashed64Def)
2161 st.preloadSyms(o.r, hashedDef)
2162 st.preloadSyms(o.r, nonPkgDef)
2164 l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
2165 for _, o := range l.objs[goObjStart:] {
2166 loadObjRefs(l, o.r, arch)
2168 l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2171 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2172 // load non-package refs
2173 ndef := uint32(r.NAlldef())
2174 needNameExpansion := r.NeedNameExpansion()
2175 for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2176 osym := r.Sym(ndef + i)
2177 name := osym.Name(r.Reader)
2178 if needNameExpansion {
2179 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2181 v := abiToVer(osym.ABI(), r.version)
2182 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2183 gi := r.syms[ndef+i]
2185 l.SetAttrLocal(gi, true)
2187 if osym.UsedInIface() {
2188 l.SetAttrUsedInIface(gi, true)
2192 // load flags of package refs
2193 for i, n := 0, r.NRefFlags(); i < n; i++ {
2195 gi := l.resolve(r, rf.Sym())
2196 if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
2197 l.SetAttrUsedInIface(gi, true)
2202 func abiToVer(abi uint16, localSymVersion int) int {
2204 if abi == goobj.SymABIstatic {
2207 } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2208 // Note that data symbols are "ABI0", which maps to version 0.
2211 log.Fatalf("invalid symbol ABI: %d", abi)
2216 // ResolveABIAlias given a symbol returns the ABI alias target of that
2217 // symbol. If the sym in question is not an alias, the sym itself is
2219 func (l *Loader) ResolveABIAlias(s Sym) Sym {
2223 if l.SymType(s) != sym.SABIALIAS {
2226 relocs := l.Relocs(s)
2227 target := relocs.At(0).Sym()
2228 if l.SymType(target) == sym.SABIALIAS {
2229 panic(fmt.Sprintf("ABI alias %s references another ABI alias %s", l.SymName(s), l.SymName(target)))
2234 // TopLevelSym tests a symbol (by name and kind) to determine whether
2235 // the symbol first class sym (participating in the link) or is an
2236 // anonymous aux or sub-symbol containing some sub-part or payload of
2238 func (l *Loader) TopLevelSym(s Sym) bool {
2239 return topLevelSym(l.RawSymName(s), l.SymType(s))
2242 // topLevelSym tests a symbol name and kind to determine whether
2243 // the symbol first class sym (participating in the link) or is an
2244 // anonymous aux or sub-symbol containing some sub-part or payload of
2246 func topLevelSym(sname string, skind sym.SymKind) bool {
2251 case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2258 // cloneToExternal takes the existing object file symbol (symIdx)
2259 // and creates a new external symbol payload that is a clone with
2260 // respect to name, version, type, relocations, etc. The idea here
2261 // is that if the linker decides it wants to update the contents of
2262 // a symbol originally discovered as part of an object file, it's
2263 // easier to do this if we make the updates to an external symbol
2265 func (l *Loader) cloneToExternal(symIdx Sym) {
2266 if l.IsExternal(symIdx) {
2267 panic("sym is already external, no need for clone")
2270 // Read the particulars from object.
2271 r, li := l.toLocal(symIdx)
2273 sname := osym.Name(r.Reader)
2274 if r.NeedNameExpansion() {
2275 sname = strings.Replace(sname, "\"\".", r.pkgprefix, -1)
2277 sver := abiToVer(osym.ABI(), r.version)
2278 skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2280 // Create new symbol, update version and kind.
2281 pi := l.newPayload(sname, sver)
2282 pp := l.payloads[pi]
2285 pp.size = int64(osym.Siz())
2286 pp.objidx = r.objidx
2288 // If this is a def, then copy the guts. We expect this case
2289 // to be very rare (one case it may come up is with -X).
2290 if li < uint32(r.NAlldef()) {
2293 relocs := l.Relocs(symIdx)
2294 pp.relocs = make([]goobj.Reloc, relocs.Count())
2295 pp.reltypes = make([]objabi.RelocType, relocs.Count())
2296 for i := range pp.relocs {
2297 // Copy the relocs slice.
2298 // Convert local reference to global reference.
2300 pp.relocs[i].Set(rel.Off(), rel.Siz(), 0, rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2301 pp.reltypes[i] = rel.Type()
2305 pp.data = r.Data(li)
2308 // If we're overriding a data symbol, collect the associated
2309 // Gotype, so as to propagate it to the new symbol.
2313 // Install new payload to global index space.
2314 // (This needs to happen at the end, as the accessors above
2315 // need to access the old symbol content.)
2316 l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2317 l.extReader.syms = append(l.extReader.syms, symIdx)
2320 // Copy the payload of symbol src to dst. Both src and dst must be external
2322 // The intended use case is that when building/linking against a shared library,
2323 // where we do symbol name mangling, the Go object file may have reference to
2324 // the original symbol name whereas the shared library provides a symbol with
2325 // the mangled name. When we do mangling, we copy payload of mangled to original.
2326 func (l *Loader) CopySym(src, dst Sym) {
2327 if !l.IsExternal(dst) {
2328 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2330 if !l.IsExternal(src) {
2331 panic("src is not external") //l.cloneToExternal(src)
2333 l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2334 l.SetSymPkg(dst, l.SymPkg(src))
2335 // TODO: other attributes?
2338 // CopyAttributes copies over all of the attributes of symbol 'src' to
2340 func (l *Loader) CopyAttributes(src Sym, dst Sym) {
2341 l.SetAttrReachable(dst, l.AttrReachable(src))
2342 l.SetAttrOnList(dst, l.AttrOnList(src))
2343 l.SetAttrLocal(dst, l.AttrLocal(src))
2344 l.SetAttrNotInSymbolTable(dst, l.AttrNotInSymbolTable(src))
2345 if l.IsExternal(dst) {
2346 l.SetAttrVisibilityHidden(dst, l.AttrVisibilityHidden(src))
2347 l.SetAttrDuplicateOK(dst, l.AttrDuplicateOK(src))
2348 l.SetAttrShared(dst, l.AttrShared(src))
2349 l.SetAttrExternal(dst, l.AttrExternal(src))
2351 // Some attributes are modifiable only for external symbols.
2352 // In such cases, don't try to transfer over the attribute
2353 // from the source even if there is a clash. This comes up
2354 // when copying attributes from a dupOK ABI wrapper symbol to
2355 // the real target symbol (which may not be marked dupOK).
2357 l.SetAttrTopFrame(dst, l.AttrTopFrame(src))
2358 l.SetAttrSpecial(dst, l.AttrSpecial(src))
2359 l.SetAttrCgoExportDynamic(dst, l.AttrCgoExportDynamic(src))
2360 l.SetAttrCgoExportStatic(dst, l.AttrCgoExportStatic(src))
2361 l.SetAttrReadOnly(dst, l.AttrReadOnly(src))
2364 // CreateExtSym creates a new external symbol with the specified name
2365 // without adding it to any lookup tables, returning a Sym index for it.
2366 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2367 return l.newExtSym(name, ver)
2370 // CreateStaticSym creates a new static symbol with the specified name
2371 // without adding it to any lookup tables, returning a Sym index for it.
2372 func (l *Loader) CreateStaticSym(name string) Sym {
2373 // Assign a new unique negative version -- this is to mark the
2374 // symbol so that it is not included in the name lookup table.
2376 return l.newExtSym(name, l.anonVersion)
2379 func (l *Loader) FreeSym(i Sym) {
2380 if l.IsExternal(i) {
2381 pp := l.getPayload(i)
2382 *pp = extSymPayload{}
2386 // relocId is essentially a <S,R> tuple identifying the Rth
2387 // relocation of symbol S.
2388 type relocId struct {
2393 // SetRelocVariant sets the 'variant' property of a relocation on
2394 // some specific symbol.
2395 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2397 if relocs := l.Relocs(s); ri >= relocs.Count() {
2398 panic("invalid relocation ID")
2400 if l.relocVariant == nil {
2401 l.relocVariant = make(map[relocId]sym.RelocVariant)
2404 l.relocVariant[relocId{s, ri}] = v
2406 delete(l.relocVariant, relocId{s, ri})
2410 // RelocVariant returns the 'variant' property of a relocation on
2411 // some specific symbol.
2412 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2413 return l.relocVariant[relocId{s, ri}]
2416 // UndefinedRelocTargets iterates through the global symbol index
2417 // space, looking for symbols with relocations targeting undefined
2418 // references. The linker's loadlib method uses this to determine if
2419 // there are unresolved references to functions in system libraries
2420 // (for example, libgcc.a), presumably due to CGO code. Return
2421 // value is a list of loader.Sym's corresponding to the undefined
2422 // cross-refs. The "limit" param controls the maximum number of
2423 // results returned; if "limit" is -1, then all undefs are returned.
2424 func (l *Loader) UndefinedRelocTargets(limit int) []Sym {
2426 for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2427 relocs := l.Relocs(si)
2428 for ri := 0; ri < relocs.Count(); ri++ {
2431 if rs != 0 && l.SymType(rs) == sym.SXREF && l.RawSymName(rs) != ".got" {
2432 result = append(result, rs)
2433 if limit != -1 && len(result) >= limit {
2442 // AssignTextSymbolOrder populates the Textp slices within each
2443 // library and compilation unit, insuring that packages are laid down
2444 // in dependency order (internal first, then everything else). Return value
2445 // is a slice of all text syms.
2446 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2448 // Library Textp lists should be empty at this point.
2449 for _, lib := range libs {
2450 if len(lib.Textp) != 0 {
2451 panic("expected empty Textp slice for library")
2453 if len(lib.DupTextSyms) != 0 {
2454 panic("expected empty DupTextSyms slice for library")
2458 // Used to record which dupok symbol we've assigned to a unit.
2459 // Can't use the onlist attribute here because it will need to
2460 // clear for the later assignment of the sym.Symbol to a unit.
2461 // NB: we can convert to using onList once we no longer have to
2462 // call the regular addToTextp.
2463 assignedToUnit := MakeBitmap(l.NSym() + 1)
2465 // Start off textp with reachable external syms.
2467 for _, sym := range extsyms {
2468 if !l.attrReachable.Has(sym) {
2471 textp = append(textp, sym)
2474 // Walk through all text symbols from Go object files and append
2475 // them to their corresponding library's textp list.
2476 for _, o := range l.objs[goObjStart:] {
2479 for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
2480 gi := l.toGlobal(r, i)
2481 if !l.attrReachable.Has(gi) {
2485 st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2486 if st != sym.STEXT {
2489 dupok := osym.Dupok()
2490 if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2491 // A dupok text symbol is resolved to another package.
2492 // We still need to record its presence in the current
2493 // package, as the trampoline pass expects packages
2494 // are laid out in dependency order.
2495 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2496 continue // symbol in different object
2499 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2503 lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2507 // Now assemble global textp, and assign text symbols to units.
2508 for _, doInternal := range [2]bool{true, false} {
2509 for idx, lib := range libs {
2510 if intlibs[idx] != doInternal {
2513 lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2514 for i, list := range lists {
2515 for _, s := range list {
2517 if l.attrReachable.Has(sym) && !assignedToUnit.Has(sym) {
2518 textp = append(textp, sym)
2519 unit := l.SymUnit(sym)
2521 unit.Textp = append(unit.Textp, s)
2522 assignedToUnit.Set(sym)
2524 // Dupok symbols may be defined in multiple packages; the
2525 // associated package for a dupok sym is chosen sort of
2526 // arbitrarily (the first containing package that the linker
2527 // loads). Canonicalizes its Pkg to the package with which
2528 // it will be laid down in text.
2529 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2530 l.SetSymPkg(sym, lib.Pkg)
2536 lib.DupTextSyms = nil
2543 // ErrorReporter is a helper class for reporting errors.
2544 type ErrorReporter struct {
2546 AfterErrorAction func()
2549 // Errorf method logs an error message.
2551 // After each error, the error actions function will be invoked; this
2552 // will either terminate the link immediately (if -h option given)
2553 // or it will keep a count and exit if more than 20 errors have been printed.
2555 // Logging an error means that on exit cmd/link will delete any
2556 // output file and return a non-zero error code.
2558 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2559 if s != 0 && reporter.ldr.SymName(s) != "" {
2560 format = reporter.ldr.SymName(s) + ": " + format
2562 format = fmt.Sprintf("sym %d: %s", s, format)
2565 fmt.Fprintf(os.Stderr, format, args...)
2566 reporter.AfterErrorAction()
2569 // GetErrorReporter returns the loader's associated error reporter.
2570 func (l *Loader) GetErrorReporter() *ErrorReporter {
2571 return l.errorReporter
2574 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2575 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2576 l.errorReporter.Errorf(s, format, args...)
2579 // Symbol statistics.
2580 func (l *Loader) Stat() string {
2581 s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
2582 s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
2583 l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
2588 func (l *Loader) Dump() {
2590 for _, obj := range l.objs[goObjStart:] {
2592 fmt.Println(obj.i, obj.r.unit.Lib)
2595 fmt.Println("extStart:", l.extStart)
2596 fmt.Println("Nsyms:", len(l.objSyms))
2598 for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2599 pi := interface{}("")
2600 if l.IsExternal(i) {
2601 pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2603 fmt.Println(i, l.SymName(i), l.SymType(i), pi)
2605 fmt.Println("symsByName")
2606 for name, i := range l.symsByName[0] {
2607 fmt.Println(i, name, 0)
2609 for name, i := range l.symsByName[1] {
2610 fmt.Println(i, name, 1)
2612 fmt.Println("payloads:")
2613 for i := range l.payloads {
2615 fmt.Println(i, pp.name, pp.ver, pp.kind)