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
56 func (rel Reloc) Type() objabi.RelocType { return objabi.RelocType(rel.Reloc.Type()) &^ objabi.R_WEAK }
57 func (rel Reloc) Weak() bool { return objabi.RelocType(rel.Reloc.Type())&objabi.R_WEAK != 0 }
58 func (rel Reloc) SetType(t objabi.RelocType) { rel.Reloc.SetType(uint16(t)) }
59 func (rel Reloc) Sym() Sym { return rel.l.resolve(rel.r, rel.Reloc.Sym()) }
60 func (rel Reloc) SetSym(s Sym) { rel.Reloc.SetSym(goobj.SymRef{PkgIdx: 0, SymIdx: uint32(s)}) }
61 func (rel Reloc) IsMarker() bool { return rel.Siz() == 0 }
63 // Aux holds a "handle" to access an aux symbol record from an
71 func (a Aux) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
73 // oReader is a wrapper type of obj.Reader, along with some
77 unit *sym.CompilationUnit
78 version int // version of static symbol
80 syms []Sym // Sym's global index, indexed by local index
81 pkg []uint32 // indices of referenced package by PkgIdx (index into loader.objs array)
82 ndef int // cache goobj.Reader.NSym()
83 nhashed64def int // cache goobj.Reader.NHashed64Def()
84 nhasheddef int // cache goobj.Reader.NHashedDef()
85 objidx uint32 // index of this reader in the objs slice
88 // Total number of defined symbols (package symbols, hashed symbols, and
89 // non-package symbols).
90 func (r *oReader) NAlldef() int { return r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef() }
97 // objSym represents a symbol in an object file. It is a tuple of
98 // the object and the symbol's local index.
99 // For external symbols, objidx is the index of l.extReader (extObj),
100 // s is its index into the payload array.
101 // {0, 0} represents the nil symbol.
103 objidx uint32 // index of the object (in l.objs array)
104 s uint32 // local index
107 type nameVer struct {
115 func (bm Bitmap) Set(i Sym) {
116 n, r := uint(i)/32, uint(i)%32
120 // unset the i-th bit.
121 func (bm Bitmap) Unset(i Sym) {
122 n, r := uint(i)/32, uint(i)%32
126 // whether the i-th bit is set.
127 func (bm Bitmap) Has(i Sym) bool {
128 n, r := uint(i)/32, uint(i)%32
129 return bm[n]&(1<<r) != 0
132 // return current length of bitmap in bits.
133 func (bm Bitmap) Len() int {
137 // return the number of bits set.
138 func (bm Bitmap) Count() int {
140 for _, x := range bm {
141 s += bits.OnesCount32(x)
146 func MakeBitmap(n int) Bitmap {
147 return make(Bitmap, (n+31)/32)
150 // growBitmap insures that the specified bitmap has enough capacity,
151 // reallocating (doubling the size) if needed.
152 func growBitmap(reqLen int, b Bitmap) Bitmap {
155 b = append(b, MakeBitmap(reqLen+1-curLen)...)
160 type symAndSize struct {
165 // A Loader loads new object files and resolves indexed symbol references.
167 // Notes on the layout of global symbol index space:
169 // - Go object files are read before host object files; each Go object
170 // read adds its defined package symbols to the global index space.
171 // Nonpackage symbols are not yet added.
173 // - In loader.LoadNonpkgSyms, add non-package defined symbols and
174 // references in all object files to the global index space.
176 // - Host object file loading happens; the host object loader does a
177 // name/version lookup for each symbol it finds; this can wind up
178 // extending the external symbol index space range. The host object
179 // loader stores symbol payloads in loader.payloads using SymbolBuilder.
181 // - Each symbol gets a unique global index. For duplicated and
182 // overwriting/overwritten symbols, the second (or later) appearance
183 // of the symbol gets the same global index as the first appearance.
185 start map[*oReader]Sym // map from object file to its start index
186 objs []objIdx // sorted by start index (i.e. objIdx.i)
187 extStart Sym // from this index on, the symbols are externally defined
188 builtinSyms []Sym // global index of builtin symbols
190 objSyms []objSym // global index mapping to local index
192 symsByName [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
193 extStaticSyms map[nameVer]Sym // externally defined static symbols, keyed by name
195 extReader *oReader // a dummy oReader, for external symbols
196 payloadBatch []extSymPayload
197 payloads []*extSymPayload // contents of linker-materialized external syms
198 values []int64 // symbol values, indexed by global sym index
200 sects []*sym.Section // sections
201 symSects []uint16 // symbol's section, index to sects array
203 align []uint8 // symbol 2^N alignment, indexed by global index
205 deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
207 objByPkg map[string]uint32 // map package path to the index of its Go object reader
209 anonVersion int // most recently assigned ext static sym pseudo-version
211 // Bitmaps and other side structures used to store data used to store
212 // symbol flags/attributes; these are to be accessed via the
213 // corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
214 // visit the comments on these methods for more details on the
215 // semantics / interpretation of the specific flags or attribute.
216 attrReachable Bitmap // reachable symbols, indexed by global index
217 attrOnList Bitmap // "on list" symbols, indexed by global index
218 attrLocal Bitmap // "local" symbols, indexed by global index
219 attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by global idx
220 attrUsedInIface Bitmap // "used in interface" symbols, indexed by global idx
221 attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
222 attrDuplicateOK Bitmap // dupOK symbols, indexed by ext sym index
223 attrShared Bitmap // shared symbols, indexed by ext sym index
224 attrExternal Bitmap // external symbols, indexed by ext sym index
226 attrReadOnly map[Sym]bool // readonly data for this sym
227 attrSpecial map[Sym]struct{} // "special" frame symbols
228 attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
229 attrCgoExportStatic map[Sym]struct{} // "cgo_export_static" symbols
230 generatedSyms map[Sym]struct{} // symbols that generate their content
232 // Outer and Sub relations for symbols.
233 // TODO: figure out whether it's more efficient to just have these
234 // as fields on extSymPayload (note that this won't be a viable
235 // strategy if somewhere in the linker we set sub/outer for a
236 // non-external sym).
240 dynimplib map[Sym]string // stores Dynimplib symbol attribute
241 dynimpvers map[Sym]string // stores Dynimpvers symbol attribute
242 localentry map[Sym]uint8 // stores Localentry symbol attribute
243 extname map[Sym]string // stores Extname symbol attribute
244 elfType map[Sym]elf.SymType // stores elf type symbol property
245 elfSym map[Sym]int32 // stores elf sym symbol property
246 localElfSym map[Sym]int32 // stores "local" elf sym symbol property
247 symPkg map[Sym]string // stores package for symbol, or library for shlib-derived syms
248 plt map[Sym]int32 // stores dynimport for pe objects
249 got map[Sym]int32 // stores got for pe objects
250 dynid map[Sym]int32 // stores Dynid for symbol
252 relocVariant map[relocId]sym.RelocVariant // stores variant relocs
254 // Used to implement field tracking; created during deadcode if
255 // field tracking is enabled. Reachparent[K] contains the index of
256 // the symbol that triggered the marking of symbol K as live.
259 // CgoExports records cgo-exported symbols by SymName.
260 CgoExports map[string]Sym
264 strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
266 elfsetstring elfsetstringFunc
268 errorReporter *ErrorReporter
270 npkgsyms int // number of package symbols, for accounting
271 nhashedsyms int // number of hashed symbols, for accounting
289 type elfsetstringFunc func(str string, off int)
291 // extSymPayload holds the payload (data + relocations) for linker-synthesized
292 // external symbols (note that symbol value is stored in a separate slice).
293 type extSymPayload struct {
294 name string // TODO: would this be better as offset into str table?
298 objidx uint32 // index of original object if sym made by cloneToExternal
306 FlagStrictDups = 1 << iota
309 func NewLoader(flags uint32, elfsetstring elfsetstringFunc, reporter *ErrorReporter) *Loader {
310 nbuiltin := goobj.NBuiltin()
311 extReader := &oReader{objidx: extObj}
313 start: make(map[*oReader]Sym),
314 objs: []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
315 objSyms: make([]objSym, 1, 1), // This will get overwritten later.
316 extReader: extReader,
317 symsByName: [2]map[string]Sym{make(map[string]Sym, 80000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
318 objByPkg: make(map[string]uint32),
319 outer: make(map[Sym]Sym),
320 sub: make(map[Sym]Sym),
321 dynimplib: make(map[Sym]string),
322 dynimpvers: make(map[Sym]string),
323 localentry: make(map[Sym]uint8),
324 extname: make(map[Sym]string),
325 attrReadOnly: make(map[Sym]bool),
326 elfType: make(map[Sym]elf.SymType),
327 elfSym: make(map[Sym]int32),
328 localElfSym: make(map[Sym]int32),
329 symPkg: make(map[Sym]string),
330 plt: make(map[Sym]int32),
331 got: make(map[Sym]int32),
332 dynid: make(map[Sym]int32),
333 attrSpecial: make(map[Sym]struct{}),
334 attrCgoExportDynamic: make(map[Sym]struct{}),
335 attrCgoExportStatic: make(map[Sym]struct{}),
336 generatedSyms: make(map[Sym]struct{}),
337 deferReturnTramp: make(map[Sym]bool),
338 extStaticSyms: make(map[nameVer]Sym),
339 builtinSyms: make([]Sym, nbuiltin),
341 elfsetstring: elfsetstring,
342 errorReporter: reporter,
343 sects: []*sym.Section{nil}, // reserve index 0 for nil section
349 // Add object file r, return the start index.
350 func (l *Loader) addObj(pkg string, r *oReader) Sym {
351 if _, ok := l.start[r]; ok {
352 panic("already added")
354 pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
355 if _, ok := l.objByPkg[pkg]; !ok {
356 l.objByPkg[pkg] = r.objidx
358 i := Sym(len(l.objSyms))
360 l.objs = append(l.objs, objIdx{r, i})
364 // Add a symbol from an object file, return the global index.
365 // If the symbol already exist, it returns the index of that symbol.
366 func (st *loadState) addSym(name string, ver int, r *oReader, li uint32, kind int, osym *goobj.Sym) Sym {
369 panic("addSym called after external symbol is created")
371 i := Sym(len(l.objSyms))
372 addToGlobal := func() {
373 l.objSyms = append(l.objSyms, objSym{r.objidx, li})
375 if name == "" && kind != hashed64Def && kind != hashedDef {
377 return i // unnamed aux symbol
379 if ver == r.version {
380 // Static symbol. Add its global index but don't
381 // add to name lookup table, as it cannot be
382 // referenced by name.
388 // Defined package symbols cannot be dup to each other.
389 // We load all the package symbols first, so we don't need
390 // to check dup here.
391 // We still add it to the lookup table, as it may still be
392 // referenced by name (e.g. through linkname).
393 l.symsByName[ver][name] = i
396 case hashed64Def, hashedDef:
397 // Hashed (content-addressable) symbol. Check the hash
398 // but don't add to name lookup table, as they are not
399 // referenced by name. Also no need to do overwriting
400 // check, as same hash indicates same content.
401 var checkHash func() (symAndSize, bool)
402 var addToHashMap func(symAndSize)
403 var h64 uint64 // only used for hashed64Def
404 var h *goobj.HashType // only used for hashedDef
405 if kind == hashed64Def {
406 checkHash = func() (symAndSize, bool) {
407 h64 = r.Hash64(li - uint32(r.ndef))
408 s, existed := st.hashed64Syms[h64]
411 addToHashMap = func(ss symAndSize) { st.hashed64Syms[h64] = ss }
413 checkHash = func() (symAndSize, bool) {
414 h = r.Hash(li - uint32(r.ndef+r.nhashed64def))
415 s, existed := st.hashedSyms[*h]
418 addToHashMap = func(ss symAndSize) { st.hashedSyms[*h] = ss }
421 if s, existed := checkHash(); existed {
422 // The content hash is built from symbol data and relocations. In the
423 // object file, the symbol data may not always contain trailing zeros,
424 // e.g. for [5]int{1,2,3} and [100]int{1,2,3}, the data is same
425 // (although the size is different).
426 // Also, for short symbols, the content hash is the identity function of
427 // the 8 bytes, and trailing zeros doesn't change the hash value, e.g.
428 // hash("A") == hash("A\0\0\0").
429 // So when two symbols have the same hash, we need to use the one with
432 // New symbol has larger size, use the new one. Rewrite the index mapping.
433 l.objSyms[s.sym] = objSym{r.objidx, li}
434 addToHashMap(symAndSize{s.sym, siz})
438 addToHashMap(symAndSize{i, siz})
443 // Non-package (named) symbol. Check if it already exists.
444 oldi, existed := l.symsByName[ver][name]
446 l.symsByName[ver][name] = i
450 // symbol already exists
452 if l.flags&FlagStrictDups != 0 {
453 l.checkdup(name, r, li, oldi)
455 // Fix for issue #47185 -- given two dupok symbols with
456 // different sizes, favor symbol with larger size. See
457 // also issue #46653.
458 szdup := l.SymSize(oldi)
459 sz := int64(r.Sym(li).Siz())
461 // new symbol overwrites old symbol.
462 l.objSyms[oldi] = objSym{r.objidx, li}
466 oldr, oldli := l.toLocal(oldi)
467 oldsym := oldr.Sym(oldli)
471 overwrite := r.DataSize(li) != 0
473 // new symbol overwrites old symbol.
474 oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
475 if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
476 log.Fatalf("duplicated definition of symbol %s, from %s and %s", name, r.unit.Lib.Pkg, oldr.unit.Lib.Pkg)
478 l.objSyms[oldi] = objSym{r.objidx, li}
480 // old symbol overwrites new symbol.
481 typ := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
482 if !typ.IsData() { // only allow overwriting data symbol
483 log.Fatalf("duplicated definition of symbol %s, from %s and %s", name, r.unit.Lib.Pkg, oldr.unit.Lib.Pkg)
489 // newExtSym creates a new external sym with the specified
491 func (l *Loader) newExtSym(name string, ver int) Sym {
492 i := Sym(len(l.objSyms))
496 l.growValues(int(i) + 1)
497 l.growAttrBitmaps(int(i) + 1)
498 pi := l.newPayload(name, ver)
499 l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
500 l.extReader.syms = append(l.extReader.syms, i)
504 // LookupOrCreateSym looks up the symbol with the specified name/version,
505 // returning its Sym index if found. If the lookup fails, a new external
506 // Sym will be created, entered into the lookup tables, and returned.
507 func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
508 i := l.Lookup(name, ver)
512 i = l.newExtSym(name, ver)
513 static := ver >= sym.SymVerStatic || ver < 0
515 l.extStaticSyms[nameVer{name, ver}] = i
517 l.symsByName[ver][name] = i
522 // AddCgoExport records a cgo-exported symbol in l.CgoExports.
523 // This table is used to identify the correct Go symbol ABI to use
524 // to resolve references from host objects (which don't have ABIs).
525 func (l *Loader) AddCgoExport(s Sym) {
526 if l.CgoExports == nil {
527 l.CgoExports = make(map[string]Sym)
529 l.CgoExports[l.SymName(s)] = s
532 // LookupOrCreateCgoExport is like LookupOrCreateSym, but if ver
533 // indicates a global symbol, it uses the CgoExport table to determine
534 // the appropriate symbol version (ABI) to use. ver must be either 0
535 // or a static symbol version.
536 func (l *Loader) LookupOrCreateCgoExport(name string, ver int) Sym {
537 if ver >= sym.SymVerStatic {
538 return l.LookupOrCreateSym(name, ver)
541 panic("ver must be 0 or a static version")
543 // Look for a cgo-exported symbol from Go.
544 if s, ok := l.CgoExports[name]; ok {
547 // Otherwise, this must just be a symbol in the host object.
548 // Create a version 0 symbol for it.
549 return l.LookupOrCreateSym(name, 0)
552 func (l *Loader) IsExternal(i Sym) bool {
554 return l.isExtReader(r)
557 func (l *Loader) isExtReader(r *oReader) bool {
558 return r == l.extReader
561 // For external symbol, return its index in the payloads array.
562 // XXX result is actually not a global index. We (ab)use the Sym type
563 // so we don't need conversion for accessing bitmaps.
564 func (l *Loader) extIndex(i Sym) Sym {
565 _, li := l.toLocal(i)
569 // Get a new payload for external symbol, return its index in
570 // the payloads array.
571 func (l *Loader) newPayload(name string, ver int) int {
572 pi := len(l.payloads)
573 pp := l.allocPayload()
576 l.payloads = append(l.payloads, pp)
577 l.growExtAttrBitmaps()
581 // getPayload returns a pointer to the extSymPayload struct for an
582 // external symbol if the symbol has a payload. Will panic if the
583 // symbol in question is bogus (zero or not an external sym).
584 func (l *Loader) getPayload(i Sym) *extSymPayload {
585 if !l.IsExternal(i) {
586 panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
589 return l.payloads[pi]
592 // allocPayload allocates a new payload.
593 func (l *Loader) allocPayload() *extSymPayload {
594 batch := l.payloadBatch
596 batch = make([]extSymPayload, 1000)
599 l.payloadBatch = batch[1:]
603 func (ms *extSymPayload) Grow(siz int64) {
604 if int64(int(siz)) != siz {
605 log.Fatalf("symgrow size %d too long", siz)
607 if int64(len(ms.data)) >= siz {
610 if cap(ms.data) < int(siz) {
612 ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
613 ms.data = ms.data[0:cl]
615 ms.data = ms.data[:siz]
618 // Convert a local index to a global index.
619 func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
623 // Convert a global index to a local index.
624 func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
625 return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
628 // Resolve a local symbol reference. Return global index.
629 func (l *Loader) resolve(r *oReader, s goobj.SymRef) Sym {
631 switch p := s.PkgIdx; p {
632 case goobj.PkgIdxInvalid:
633 // {0, X} with non-zero X is never a valid sym reference from a Go object.
634 // We steal this space for symbol references from external objects.
635 // In this case, X is just the global index.
636 if l.isExtReader(r) {
643 case goobj.PkgIdxHashed64:
644 i := int(s.SymIdx) + r.ndef
646 case goobj.PkgIdxHashed:
647 i := int(s.SymIdx) + r.ndef + r.nhashed64def
649 case goobj.PkgIdxNone:
650 i := int(s.SymIdx) + r.ndef + r.nhashed64def + r.nhasheddef
652 case goobj.PkgIdxBuiltin:
653 if bi := l.builtinSyms[s.SymIdx]; bi != 0 {
656 l.reportMissingBuiltin(int(s.SymIdx), r.unit.Lib.Pkg)
658 case goobj.PkgIdxSelf:
661 rr = l.objs[r.pkg[p]].r
663 return l.toGlobal(rr, s.SymIdx)
666 // reportMissingBuiltin issues an error in the case where we have a
667 // relocation against a runtime builtin whose definition is not found
668 // when the runtime package is built. The canonical example is
669 // "runtime.racefuncenter" -- currently if you do something like
671 // go build -gcflags=-race myprogram.go
673 // the compiler will insert calls to the builtin runtime.racefuncenter,
674 // but the version of the runtime used for linkage won't actually contain
675 // definitions of that symbol. See issue #42396 for details.
677 // As currently implemented, this is a fatal error. This has drawbacks
678 // in that if there are multiple missing builtins, the error will only
679 // cite the first one. On the plus side, terminating the link here has
680 // advantages in that we won't run the risk of panics or crashes later
681 // on in the linker due to R_CALL relocations with 0-valued target
683 func (l *Loader) reportMissingBuiltin(bsym int, reflib string) {
684 bname, _ := goobj.BuiltinName(bsym)
685 log.Fatalf("reference to undefined builtin %q from package %q",
689 // Look up a symbol by name, return global index, or 0 if not found.
690 // This is more like Syms.ROLookup than Lookup -- it doesn't create
692 func (l *Loader) Lookup(name string, ver int) Sym {
693 if ver >= sym.SymVerStatic || ver < 0 {
694 return l.extStaticSyms[nameVer{name, ver}]
696 return l.symsByName[ver][name]
699 // Check that duplicate symbols have same contents.
700 func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
702 rdup, ldup := l.toLocal(dup)
703 pdup := rdup.Data(ldup)
704 reason := "same length but different contents"
705 if len(p) != len(pdup) {
706 reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
707 } else if bytes.Equal(p, pdup) {
708 // For BSS symbols, we need to check size as well, see issue 46653.
709 szdup := l.SymSize(dup)
710 sz := int64(r.Sym(li).Siz())
714 reason = fmt.Sprintf("different sizes: new size %d != old size %d",
717 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)
719 // For the moment, allow DWARF subprogram DIEs for
720 // auto-generated wrapper functions. What seems to happen
721 // here is that we get different line numbers on formal
722 // params; I am guessing that the pos is being inherited
723 // from the spot where the wrapper is needed.
724 allowed := strings.HasPrefix(name, "go.info.go.interface") ||
725 strings.HasPrefix(name, "go.info.go.builtin") ||
726 strings.HasPrefix(name, "go.debuglines")
732 func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
734 // Number of total symbols.
735 func (l *Loader) NSym() int {
736 return len(l.objSyms)
739 // Number of defined Go symbols.
740 func (l *Loader) NDef() int {
741 return int(l.extStart)
744 // Number of reachable symbols.
745 func (l *Loader) NReachableSym() int {
746 return l.attrReachable.Count()
749 // Returns the name of the i-th symbol.
750 func (l *Loader) SymName(i Sym) string {
752 pp := l.getPayload(i)
755 r, li := l.toLocal(i)
759 return r.Sym(li).Name(r.Reader)
762 // Returns the version of the i-th symbol.
763 func (l *Loader) SymVersion(i Sym) int {
765 pp := l.getPayload(i)
768 r, li := l.toLocal(i)
769 return int(abiToVer(r.Sym(li).ABI(), r.version))
772 func (l *Loader) IsFileLocal(i Sym) bool {
773 return l.SymVersion(i) >= sym.SymVerStatic
776 // IsFromAssembly returns true if this symbol is derived from an
777 // object file generated by the Go assembler.
778 func (l *Loader) IsFromAssembly(i Sym) bool {
783 return r.FromAssembly()
786 // Returns the type of the i-th symbol.
787 func (l *Loader) SymType(i Sym) sym.SymKind {
789 pp := l.getPayload(i)
795 r, li := l.toLocal(i)
796 return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
799 // Returns the attributes of the i-th symbol.
800 func (l *Loader) SymAttr(i Sym) uint8 {
802 // TODO: do something? External symbols have different representation of attributes.
803 // For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
804 // set by external symbol.
807 r, li := l.toLocal(i)
808 return r.Sym(li).Flag()
811 // Returns the size of the i-th symbol.
812 func (l *Loader) SymSize(i Sym) int64 {
814 pp := l.getPayload(i)
817 r, li := l.toLocal(i)
818 return int64(r.Sym(li).Siz())
821 // AttrReachable returns true for symbols that are transitively
822 // referenced from the entry points. Unreachable symbols are not
823 // written to the output.
824 func (l *Loader) AttrReachable(i Sym) bool {
825 return l.attrReachable.Has(i)
828 // SetAttrReachable sets the reachability property for a symbol (see
830 func (l *Loader) SetAttrReachable(i Sym, v bool) {
832 l.attrReachable.Set(i)
834 l.attrReachable.Unset(i)
838 // AttrOnList returns true for symbols that are on some list (such as
839 // the list of all text symbols, or one of the lists of data symbols)
840 // and is consulted to avoid bugs where a symbol is put on a list
842 func (l *Loader) AttrOnList(i Sym) bool {
843 return l.attrOnList.Has(i)
846 // SetAttrOnList sets the "on list" property for a symbol (see
848 func (l *Loader) SetAttrOnList(i Sym, v bool) {
852 l.attrOnList.Unset(i)
856 // AttrLocal returns true for symbols that are only visible within the
857 // module (executable or shared library) being linked. This attribute
858 // is applied to thunks and certain other linker-generated symbols.
859 func (l *Loader) AttrLocal(i Sym) bool {
860 return l.attrLocal.Has(i)
863 // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
864 func (l *Loader) SetAttrLocal(i Sym, v bool) {
872 // AttrUsedInIface returns true for a type symbol that is used in
874 func (l *Loader) AttrUsedInIface(i Sym) bool {
875 return l.attrUsedInIface.Has(i)
878 func (l *Loader) SetAttrUsedInIface(i Sym, v bool) {
880 l.attrUsedInIface.Set(i)
882 l.attrUsedInIface.Unset(i)
886 // SymAddr checks that a symbol is reachable, and returns its value.
887 func (l *Loader) SymAddr(i Sym) int64 {
888 if !l.AttrReachable(i) {
889 panic("unreachable symbol in symaddr")
894 // AttrNotInSymbolTable returns true for symbols that should not be
895 // added to the symbol table of the final generated load module.
896 func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
897 return l.attrNotInSymbolTable.Has(i)
900 // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
901 // (see AttrNotInSymbolTable above).
902 func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
904 l.attrNotInSymbolTable.Set(i)
906 l.attrNotInSymbolTable.Unset(i)
910 // AttrVisibilityHidden symbols returns true for ELF symbols with
911 // visibility set to STV_HIDDEN. They become local symbols in
912 // the final executable. Only relevant when internally linking
913 // on an ELF platform.
914 func (l *Loader) AttrVisibilityHidden(i Sym) bool {
915 if !l.IsExternal(i) {
918 return l.attrVisibilityHidden.Has(l.extIndex(i))
921 // SetAttrVisibilityHidden sets the "hidden visibility" property for a
922 // symbol (see AttrVisibilityHidden).
923 func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
924 if !l.IsExternal(i) {
925 panic("tried to set visibility attr on non-external symbol")
928 l.attrVisibilityHidden.Set(l.extIndex(i))
930 l.attrVisibilityHidden.Unset(l.extIndex(i))
934 // AttrDuplicateOK returns true for a symbol that can be present in
935 // multiple object files.
936 func (l *Loader) AttrDuplicateOK(i Sym) bool {
937 if !l.IsExternal(i) {
938 // TODO: if this path winds up being taken frequently, it
939 // might make more sense to copy the flag value out of the object
940 // into a larger bitmap during preload.
941 r, li := l.toLocal(i)
942 return r.Sym(li).Dupok()
944 return l.attrDuplicateOK.Has(l.extIndex(i))
947 // SetAttrDuplicateOK sets the "duplicate OK" property for an external
948 // symbol (see AttrDuplicateOK).
949 func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
950 if !l.IsExternal(i) {
951 panic("tried to set dupok attr on non-external symbol")
954 l.attrDuplicateOK.Set(l.extIndex(i))
956 l.attrDuplicateOK.Unset(l.extIndex(i))
960 // AttrShared returns true for symbols compiled with the -shared option.
961 func (l *Loader) AttrShared(i Sym) bool {
962 if !l.IsExternal(i) {
963 // TODO: if this path winds up being taken frequently, it
964 // might make more sense to copy the flag value out of the
965 // object into a larger bitmap during preload.
969 return l.attrShared.Has(l.extIndex(i))
972 // SetAttrShared sets the "shared" property for an external
973 // symbol (see AttrShared).
974 func (l *Loader) SetAttrShared(i Sym, v bool) {
975 if !l.IsExternal(i) {
976 panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
979 l.attrShared.Set(l.extIndex(i))
981 l.attrShared.Unset(l.extIndex(i))
985 // AttrExternal returns true for function symbols loaded from host
987 func (l *Loader) AttrExternal(i Sym) bool {
988 if !l.IsExternal(i) {
991 return l.attrExternal.Has(l.extIndex(i))
994 // SetAttrExternal sets the "external" property for an host object
995 // symbol (see AttrExternal).
996 func (l *Loader) SetAttrExternal(i Sym, v bool) {
997 if !l.IsExternal(i) {
998 panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.SymName(i)))
1001 l.attrExternal.Set(l.extIndex(i))
1003 l.attrExternal.Unset(l.extIndex(i))
1007 // AttrSpecial returns true for a symbols that do not have their
1008 // address (i.e. Value) computed by the usual mechanism of
1009 // data.go:dodata() & data.go:address().
1010 func (l *Loader) AttrSpecial(i Sym) bool {
1011 _, ok := l.attrSpecial[i]
1015 // SetAttrSpecial sets the "special" property for a symbol (see
1017 func (l *Loader) SetAttrSpecial(i Sym, v bool) {
1019 l.attrSpecial[i] = struct{}{}
1021 delete(l.attrSpecial, i)
1025 // AttrCgoExportDynamic returns true for a symbol that has been
1026 // specially marked via the "cgo_export_dynamic" compiler directive
1027 // written by cgo (in response to //export directives in the source).
1028 func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
1029 _, ok := l.attrCgoExportDynamic[i]
1033 // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
1034 // (see AttrCgoExportDynamic).
1035 func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
1037 l.attrCgoExportDynamic[i] = struct{}{}
1039 delete(l.attrCgoExportDynamic, i)
1043 // AttrCgoExportStatic returns true for a symbol that has been
1044 // specially marked via the "cgo_export_static" directive
1046 func (l *Loader) AttrCgoExportStatic(i Sym) bool {
1047 _, ok := l.attrCgoExportStatic[i]
1051 // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
1052 // (see AttrCgoExportStatic).
1053 func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
1055 l.attrCgoExportStatic[i] = struct{}{}
1057 delete(l.attrCgoExportStatic, i)
1061 // IsGeneratedSym returns true if a symbol's been previously marked as a
1062 // generator symbol through the SetIsGeneratedSym. The functions for generator
1063 // symbols are kept in the Link context.
1064 func (l *Loader) IsGeneratedSym(i Sym) bool {
1065 _, ok := l.generatedSyms[i]
1069 // SetIsGeneratedSym marks symbols as generated symbols. Data shouldn't be
1070 // stored in generated symbols, and a function is registered and called for
1071 // each of these symbols.
1072 func (l *Loader) SetIsGeneratedSym(i Sym, v bool) {
1073 if !l.IsExternal(i) {
1074 panic("only external symbols can be generated")
1077 l.generatedSyms[i] = struct{}{}
1079 delete(l.generatedSyms, i)
1083 func (l *Loader) AttrCgoExport(i Sym) bool {
1084 return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
1087 // AttrReadOnly returns true for a symbol whose underlying data
1088 // is stored via a read-only mmap.
1089 func (l *Loader) AttrReadOnly(i Sym) bool {
1090 if v, ok := l.attrReadOnly[i]; ok {
1093 if l.IsExternal(i) {
1094 pp := l.getPayload(i)
1096 return l.objs[pp.objidx].r.ReadOnly()
1100 r, _ := l.toLocal(i)
1104 // SetAttrReadOnly sets the "data is read only" property for a symbol
1105 // (see AttrReadOnly).
1106 func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
1107 l.attrReadOnly[i] = v
1110 // AttrSubSymbol returns true for symbols that are listed as a
1111 // sub-symbol of some other outer symbol. The sub/outer mechanism is
1112 // used when loading host objects (sections from the host object
1113 // become regular linker symbols and symbols go on the Sub list of
1114 // their section) and for constructing the global offset table when
1115 // internally linking a dynamic executable.
1117 // Note that in later stages of the linker, we set Outer(S) to some
1118 // container symbol C, but don't set Sub(C). Thus we have two
1119 // distinct scenarios:
1121 // - Outer symbol covers the address ranges of its sub-symbols.
1122 // Outer.Sub is set in this case.
1123 // - Outer symbol doesn't conver the address ranges. It is zero-sized
1124 // and doesn't have sub-symbols. In the case, the inner symbol is
1125 // not actually a "SubSymbol". (Tricky!)
1127 // This method returns TRUE only for sub-symbols in the first scenario.
1129 // FIXME: would be better to do away with this and have a better way
1130 // to represent container symbols.
1132 func (l *Loader) AttrSubSymbol(i Sym) bool {
1133 // we don't explicitly store this attribute any more -- return
1134 // a value based on the sub-symbol setting.
1139 return l.SubSym(o) != 0
1142 // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
1143 // clients should instead use the AddInteriorSym method to establish
1144 // containment relationships for host object symbols.
1146 // Returns whether the i-th symbol has ReflectMethod attribute set.
1147 func (l *Loader) IsReflectMethod(i Sym) bool {
1148 return l.SymAttr(i)&goobj.SymFlagReflectMethod != 0
1151 // Returns whether the i-th symbol is nosplit.
1152 func (l *Loader) IsNoSplit(i Sym) bool {
1153 return l.SymAttr(i)&goobj.SymFlagNoSplit != 0
1156 // Returns whether this is a Go type symbol.
1157 func (l *Loader) IsGoType(i Sym) bool {
1158 return l.SymAttr(i)&goobj.SymFlagGoType != 0
1161 // Returns whether this symbol should be included in typelink.
1162 func (l *Loader) IsTypelink(i Sym) bool {
1163 return l.SymAttr(i)&goobj.SymFlagTypelink != 0
1166 // Returns whether this symbol is an itab symbol.
1167 func (l *Loader) IsItab(i Sym) bool {
1168 if l.IsExternal(i) {
1171 r, li := l.toLocal(i)
1172 return r.Sym(li).IsItab()
1175 // Returns whether this symbol is a dictionary symbol.
1176 func (l *Loader) IsDict(i Sym) bool {
1177 if l.IsExternal(i) {
1180 r, li := l.toLocal(i)
1181 return r.Sym(li).IsDict()
1184 // Return whether this is a trampoline of a deferreturn call.
1185 func (l *Loader) IsDeferReturnTramp(i Sym) bool {
1186 return l.deferReturnTramp[i]
1189 // Set that i is a trampoline of a deferreturn call.
1190 func (l *Loader) SetIsDeferReturnTramp(i Sym, v bool) {
1191 l.deferReturnTramp[i] = v
1194 // growValues grows the slice used to store symbol values.
1195 func (l *Loader) growValues(reqLen int) {
1196 curLen := len(l.values)
1197 if reqLen > curLen {
1198 l.values = append(l.values, make([]int64, reqLen+1-curLen)...)
1202 // SymValue returns the value of the i-th symbol. i is global index.
1203 func (l *Loader) SymValue(i Sym) int64 {
1207 // SetSymValue sets the value of the i-th symbol. i is global index.
1208 func (l *Loader) SetSymValue(i Sym, val int64) {
1212 // AddToSymValue adds to the value of the i-th symbol. i is the global index.
1213 func (l *Loader) AddToSymValue(i Sym, val int64) {
1217 // Returns the symbol content of the i-th symbol. i is global index.
1218 func (l *Loader) Data(i Sym) []byte {
1219 if l.IsExternal(i) {
1220 pp := l.getPayload(i)
1226 r, li := l.toLocal(i)
1230 // FreeData clears the symbol data of an external symbol, allowing the memory
1231 // to be freed earlier. No-op for non-external symbols.
1232 // i is global index.
1233 func (l *Loader) FreeData(i Sym) {
1234 if l.IsExternal(i) {
1235 pp := l.getPayload(i)
1242 // SymAlign returns the alignment for a symbol.
1243 func (l *Loader) SymAlign(i Sym) int32 {
1244 if int(i) >= len(l.align) {
1245 // align is extended lazily -- it the sym in question is
1246 // outside the range of the existing slice, then we assume its
1247 // alignment has not yet been set.
1250 // TODO: would it make sense to return an arch-specific
1251 // alignment depending on section type? E.g. STEXT => 32,
1257 return int32(1 << (abits - 1))
1260 // SetSymAlign sets the alignment for a symbol.
1261 func (l *Loader) SetSymAlign(i Sym, align int32) {
1262 // Reject nonsense alignments.
1263 if align < 0 || align&(align-1) != 0 {
1264 panic("bad alignment value")
1266 if int(i) >= len(l.align) {
1267 l.align = append(l.align, make([]uint8, l.NSym()-len(l.align))...)
1272 l.align[i] = uint8(bits.Len32(uint32(align)))
1275 // SymValue returns the section of the i-th symbol. i is global index.
1276 func (l *Loader) SymSect(i Sym) *sym.Section {
1277 if int(i) >= len(l.symSects) {
1278 // symSects is extended lazily -- it the sym in question is
1279 // outside the range of the existing slice, then we assume its
1280 // section has not yet been set.
1283 return l.sects[l.symSects[i]]
1286 // SetSymSect sets the section of the i-th symbol. i is global index.
1287 func (l *Loader) SetSymSect(i Sym, sect *sym.Section) {
1288 if int(i) >= len(l.symSects) {
1289 l.symSects = append(l.symSects, make([]uint16, l.NSym()-len(l.symSects))...)
1291 l.symSects[i] = sect.Index
1294 // growSects grows the slice used to store symbol sections.
1295 func (l *Loader) growSects(reqLen int) {
1296 curLen := len(l.symSects)
1297 if reqLen > curLen {
1298 l.symSects = append(l.symSects, make([]uint16, reqLen+1-curLen)...)
1302 // NewSection creates a new (output) section.
1303 func (l *Loader) NewSection() *sym.Section {
1304 sect := new(sym.Section)
1306 if idx != int(uint16(idx)) {
1307 panic("too many sections created")
1309 sect.Index = uint16(idx)
1310 l.sects = append(l.sects, sect)
1314 // SymDynImplib returns the "dynimplib" attribute for the specified
1315 // symbol, making up a portion of the info for a symbol specified
1316 // on a "cgo_import_dynamic" compiler directive.
1317 func (l *Loader) SymDynimplib(i Sym) string {
1318 return l.dynimplib[i]
1321 // SetSymDynimplib sets the "dynimplib" attribute for a symbol.
1322 func (l *Loader) SetSymDynimplib(i Sym, value string) {
1323 // reject bad symbols
1324 if i >= Sym(len(l.objSyms)) || i == 0 {
1325 panic("bad symbol index in SetDynimplib")
1328 delete(l.dynimplib, i)
1330 l.dynimplib[i] = value
1334 // SymDynimpvers returns the "dynimpvers" attribute for the specified
1335 // symbol, making up a portion of the info for a symbol specified
1336 // on a "cgo_import_dynamic" compiler directive.
1337 func (l *Loader) SymDynimpvers(i Sym) string {
1338 return l.dynimpvers[i]
1341 // SetSymDynimpvers sets the "dynimpvers" attribute for a symbol.
1342 func (l *Loader) SetSymDynimpvers(i Sym, value string) {
1343 // reject bad symbols
1344 if i >= Sym(len(l.objSyms)) || i == 0 {
1345 panic("bad symbol index in SetDynimpvers")
1348 delete(l.dynimpvers, i)
1350 l.dynimpvers[i] = value
1354 // SymExtname returns the "extname" value for the specified
1356 func (l *Loader) SymExtname(i Sym) string {
1357 if s, ok := l.extname[i]; ok {
1363 // SetSymExtname sets the "extname" attribute for a symbol.
1364 func (l *Loader) SetSymExtname(i Sym, value string) {
1365 // reject bad symbols
1366 if i >= Sym(len(l.objSyms)) || i == 0 {
1367 panic("bad symbol index in SetExtname")
1370 delete(l.extname, i)
1372 l.extname[i] = value
1376 // SymElfType returns the previously recorded ELF type for a symbol
1377 // (used only for symbols read from shared libraries by ldshlibsyms).
1378 // It is not set for symbols defined by the packages being linked or
1379 // by symbols read by ldelf (and so is left as elf.STT_NOTYPE).
1380 func (l *Loader) SymElfType(i Sym) elf.SymType {
1381 if et, ok := l.elfType[i]; ok {
1384 return elf.STT_NOTYPE
1387 // SetSymElfType sets the elf type attribute for a symbol.
1388 func (l *Loader) SetSymElfType(i Sym, et elf.SymType) {
1389 // reject bad symbols
1390 if i >= Sym(len(l.objSyms)) || i == 0 {
1391 panic("bad symbol index in SetSymElfType")
1393 if et == elf.STT_NOTYPE {
1394 delete(l.elfType, i)
1400 // SymElfSym returns the ELF symbol index for a given loader
1401 // symbol, assigned during ELF symtab generation.
1402 func (l *Loader) SymElfSym(i Sym) int32 {
1406 // SetSymElfSym sets the elf symbol index for a symbol.
1407 func (l *Loader) SetSymElfSym(i Sym, es int32) {
1409 panic("bad sym index")
1418 // SymLocalElfSym returns the "local" ELF symbol index for a given loader
1419 // symbol, assigned during ELF symtab generation.
1420 func (l *Loader) SymLocalElfSym(i Sym) int32 {
1421 return l.localElfSym[i]
1424 // SetSymLocalElfSym sets the "local" elf symbol index for a symbol.
1425 func (l *Loader) SetSymLocalElfSym(i Sym, es int32) {
1427 panic("bad sym index")
1430 delete(l.localElfSym, i)
1432 l.localElfSym[i] = es
1436 // SymPlt returns the PLT offset of symbol s.
1437 func (l *Loader) SymPlt(s Sym) int32 {
1438 if v, ok := l.plt[s]; ok {
1444 // SetPlt sets the PLT offset of symbol i.
1445 func (l *Loader) SetPlt(i Sym, v int32) {
1446 if i >= Sym(len(l.objSyms)) || i == 0 {
1447 panic("bad symbol for SetPlt")
1456 // SymGot returns the GOT offset of symbol s.
1457 func (l *Loader) SymGot(s Sym) int32 {
1458 if v, ok := l.got[s]; ok {
1464 // SetGot sets the GOT offset of symbol i.
1465 func (l *Loader) SetGot(i Sym, v int32) {
1466 if i >= Sym(len(l.objSyms)) || i == 0 {
1467 panic("bad symbol for SetGot")
1476 // SymDynid returns the "dynid" property for the specified symbol.
1477 func (l *Loader) SymDynid(i Sym) int32 {
1478 if s, ok := l.dynid[i]; ok {
1484 // SetSymDynid sets the "dynid" property for a symbol.
1485 func (l *Loader) SetSymDynid(i Sym, val int32) {
1486 // reject bad symbols
1487 if i >= Sym(len(l.objSyms)) || i == 0 {
1488 panic("bad symbol index in SetSymDynid")
1497 // DynIdSyms returns the set of symbols for which dynID is set to an
1498 // interesting (non-default) value. This is expected to be a fairly
1500 func (l *Loader) DynidSyms() []Sym {
1501 sl := make([]Sym, 0, len(l.dynid))
1502 for s := range l.dynid {
1505 sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
1509 // SymGoType returns the 'Gotype' property for a given symbol (set by
1510 // the Go compiler for variable symbols). This version relies on
1511 // reading aux symbols for the target sym -- it could be that a faster
1512 // approach would be to check for gotype during preload and copy the
1513 // results in to a map (might want to try this at some point and see
1514 // if it helps speed things up).
1515 func (l *Loader) SymGoType(i Sym) Sym { return l.aux1(i, goobj.AuxGotype) }
1517 // SymUnit returns the compilation unit for a given symbol (which will
1518 // typically be nil for external or linker-manufactured symbols).
1519 func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
1520 if l.IsExternal(i) {
1521 pp := l.getPayload(i)
1523 r := l.objs[pp.objidx].r
1528 r, _ := l.toLocal(i)
1532 // SymPkg returns the package where the symbol came from (for
1533 // regular compiler-generated Go symbols), but in the case of
1534 // building with "-linkshared" (when a symbol is read from a
1535 // shared library), will hold the library name.
1536 // NOTE: this corresponds to sym.Symbol.File field.
1537 func (l *Loader) SymPkg(i Sym) string {
1538 if f, ok := l.symPkg[i]; ok {
1541 if l.IsExternal(i) {
1542 pp := l.getPayload(i)
1544 r := l.objs[pp.objidx].r
1545 return r.unit.Lib.Pkg
1549 r, _ := l.toLocal(i)
1550 return r.unit.Lib.Pkg
1553 // SetSymPkg sets the package/library for a symbol. This is
1554 // needed mainly for external symbols, specifically those imported
1555 // from shared libraries.
1556 func (l *Loader) SetSymPkg(i Sym, pkg string) {
1557 // reject bad symbols
1558 if i >= Sym(len(l.objSyms)) || i == 0 {
1559 panic("bad symbol index in SetSymPkg")
1564 // SymLocalentry returns the "local entry" value for the specified
1566 func (l *Loader) SymLocalentry(i Sym) uint8 {
1567 return l.localentry[i]
1570 // SetSymLocalentry sets the "local entry" attribute for a symbol.
1571 func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
1572 // reject bad symbols
1573 if i >= Sym(len(l.objSyms)) || i == 0 {
1574 panic("bad symbol index in SetSymLocalentry")
1577 delete(l.localentry, i)
1579 l.localentry[i] = value
1583 // Returns the number of aux symbols given a global index.
1584 func (l *Loader) NAux(i Sym) int {
1585 if l.IsExternal(i) {
1588 r, li := l.toLocal(i)
1592 // Returns the "handle" to the j-th aux symbol of the i-th symbol.
1593 func (l *Loader) Aux(i Sym, j int) Aux {
1594 if l.IsExternal(i) {
1597 r, li := l.toLocal(i)
1598 if j >= r.NAux(li) {
1601 return Aux{r.Aux(li, j), r, l}
1604 // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
1605 // symbols associated with a given function symbol. Prior to the
1606 // introduction of the loader, this was done purely using name
1607 // lookups, e.f. for function with name XYZ we would then look up
1608 // go.info.XYZ, etc.
1609 func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
1610 if l.SymType(fnSymIdx) != sym.STEXT {
1611 log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1613 if l.IsExternal(fnSymIdx) {
1614 // Current expectation is that any external function will
1615 // not have auxsyms.
1618 r, li := l.toLocal(fnSymIdx)
1620 for i := range auxs {
1623 case goobj.AuxDwarfInfo:
1624 auxDwarfInfo = l.resolve(r, a.Sym())
1625 if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
1626 panic("aux dwarf info sym with wrong type")
1628 case goobj.AuxDwarfLoc:
1629 auxDwarfLoc = l.resolve(r, a.Sym())
1630 if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
1631 panic("aux dwarf loc sym with wrong type")
1633 case goobj.AuxDwarfRanges:
1634 auxDwarfRanges = l.resolve(r, a.Sym())
1635 if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
1636 panic("aux dwarf ranges sym with wrong type")
1638 case goobj.AuxDwarfLines:
1639 auxDwarfLines = l.resolve(r, a.Sym())
1640 if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
1641 panic("aux dwarf lines sym with wrong type")
1648 // AddInteriorSym sets up 'interior' as an interior symbol of
1649 // container/payload symbol 'container'. An interior symbol does not
1650 // itself have data, but gives a name to a subrange of the data in its
1651 // container symbol. The container itself may or may not have a name.
1652 // This method is intended primarily for use in the host object
1653 // loaders, to capture the semantics of symbols and sections in an
1654 // object file. When reading a host object file, we'll typically
1655 // encounter a static section symbol (ex: ".text") containing content
1656 // for a collection of functions, then a series of ELF (or macho, etc)
1657 // symbol table entries each of which points into a sub-section
1658 // (offset and length) of its corresponding container symbol. Within
1659 // the go linker we create a loader.Sym for the container (which is
1660 // expected to have the actual content/payload) and then a set of
1661 // interior loader.Sym's that point into a portion of the container.
1662 func (l *Loader) AddInteriorSym(container Sym, interior Sym) {
1663 // Container symbols are expected to have content/data.
1664 // NB: this restriction may turn out to be too strict (it's possible
1665 // to imagine a zero-sized container with an interior symbol pointing
1666 // into it); it's ok to relax or remove it if we counter an
1667 // oddball host object that triggers this.
1668 if l.SymSize(container) == 0 && len(l.Data(container)) == 0 {
1669 panic("unexpected empty container symbol")
1671 // The interior symbols for a container are not expected to have
1672 // content/data or relocations.
1673 if len(l.Data(interior)) != 0 {
1674 panic("unexpected non-empty interior symbol")
1676 // Interior symbol is expected to be in the symbol table.
1677 if l.AttrNotInSymbolTable(interior) {
1678 panic("interior symbol must be in symtab")
1680 // Only a single level of containment is allowed.
1681 if l.OuterSym(container) != 0 {
1682 panic("outer has outer itself")
1684 // Interior sym should not already have a sibling.
1685 if l.SubSym(interior) != 0 {
1686 panic("sub set for subsym")
1688 // Interior sym should not already point at a container.
1689 if l.OuterSym(interior) != 0 {
1690 panic("outer already set for subsym")
1692 l.sub[interior] = l.sub[container]
1693 l.sub[container] = interior
1694 l.outer[interior] = container
1697 // OuterSym gets the outer symbol for host object loaded symbols.
1698 func (l *Loader) OuterSym(i Sym) Sym {
1699 // FIXME: add check for isExternal?
1703 // SubSym gets the subsymbol for host object loaded symbols.
1704 func (l *Loader) SubSym(i Sym) Sym {
1705 // NB: note -- no check for l.isExternal(), since I am pretty sure
1706 // that later phases in the linker set subsym for "type." syms
1710 // SetCarrierSym declares that 'c' is the carrier or container symbol
1711 // for 's'. Carrier symbols are used in the linker to as a container
1712 // for a collection of sub-symbols where the content of the
1713 // sub-symbols is effectively concatenated to form the content of the
1714 // carrier. The carrier is given a name in the output symbol table
1715 // while the sub-symbol names are not. For example, the Go compiler
1716 // emits named string symbols (type SGOSTRING) when compiling a
1717 // package; after being deduplicated, these symbols are collected into
1718 // a single unit by assigning them a new carrier symbol named
1719 // "go.string.*" (which appears in the final symbol table for the
1720 // output load module).
1721 func (l *Loader) SetCarrierSym(s Sym, c Sym) {
1723 panic("invalid carrier in SetCarrierSym")
1726 panic("invalid sub-symbol in SetCarrierSym")
1728 // Carrier symbols are not expected to have content/data. It is
1729 // ok for them to have non-zero size (to allow for use of generator
1731 if len(l.Data(c)) != 0 {
1732 panic("unexpected non-empty carrier symbol")
1735 // relocsym's foldSubSymbolOffset requires that we only
1736 // have a single level of containment-- enforce here.
1737 if l.outer[c] != 0 {
1738 panic("invalid nested carrier sym")
1742 // Initialize Reachable bitmap and its siblings for running deadcode pass.
1743 func (l *Loader) InitReachable() {
1744 l.growAttrBitmaps(l.NSym() + 1)
1747 type symWithVal struct {
1751 type bySymValue []symWithVal
1753 func (s bySymValue) Len() int { return len(s) }
1754 func (s bySymValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1755 func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
1757 // SortSub walks through the sub-symbols for 's' and sorts them
1758 // in place by increasing value. Return value is the new
1759 // sub symbol for the specified outer symbol.
1760 func (l *Loader) SortSub(s Sym) Sym {
1762 if s == 0 || l.sub[s] == 0 {
1766 // Sort symbols using a slice first. Use a stable sort on the off
1767 // chance that there's more than once symbol with the same value,
1768 // so as to preserve reproducible builds.
1769 sl := []symWithVal{}
1770 for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
1771 sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
1773 sort.Stable(bySymValue(sl))
1775 // Then apply any changes needed to the sub map.
1777 for i := len(sl) - 1; i >= 0; i-- {
1783 // Update sub for outer symbol, then return
1788 // SortSyms sorts a list of symbols by their value.
1789 func (l *Loader) SortSyms(ss []Sym) {
1790 sort.SliceStable(ss, func(i, j int) bool { return l.SymValue(ss[i]) < l.SymValue(ss[j]) })
1793 // Insure that reachable bitmap and its siblings have enough size.
1794 func (l *Loader) growAttrBitmaps(reqLen int) {
1795 if reqLen > l.attrReachable.Len() {
1796 // These are indexed by global symbol
1797 l.attrReachable = growBitmap(reqLen, l.attrReachable)
1798 l.attrOnList = growBitmap(reqLen, l.attrOnList)
1799 l.attrLocal = growBitmap(reqLen, l.attrLocal)
1800 l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
1801 l.attrUsedInIface = growBitmap(reqLen, l.attrUsedInIface)
1803 l.growExtAttrBitmaps()
1806 func (l *Loader) growExtAttrBitmaps() {
1807 // These are indexed by external symbol index (e.g. l.extIndex(i))
1808 extReqLen := len(l.payloads)
1809 if extReqLen > l.attrVisibilityHidden.Len() {
1810 l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
1811 l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
1812 l.attrShared = growBitmap(extReqLen, l.attrShared)
1813 l.attrExternal = growBitmap(extReqLen, l.attrExternal)
1817 func (relocs *Relocs) Count() int { return len(relocs.rs) }
1819 // At returns the j-th reloc for a global symbol.
1820 func (relocs *Relocs) At(j int) Reloc {
1821 if relocs.l.isExtReader(relocs.r) {
1822 return Reloc{&relocs.rs[j], relocs.r, relocs.l}
1824 return Reloc{&relocs.rs[j], relocs.r, relocs.l}
1827 // Relocs returns a Relocs object for the given global sym.
1828 func (l *Loader) Relocs(i Sym) Relocs {
1829 r, li := l.toLocal(i)
1831 panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
1833 return l.relocs(r, li)
1836 // Relocs returns a Relocs object given a local sym index and reader.
1837 func (l *Loader) relocs(r *oReader, li uint32) Relocs {
1838 var rs []goobj.Reloc
1839 if l.isExtReader(r) {
1840 pp := l.payloads[li]
1853 func (l *Loader) auxs(i Sym) (*oReader, []goobj.Aux) {
1854 if l.IsExternal(i) {
1855 pp := l.getPayload(i)
1856 return l.objs[pp.objidx].r, pp.auxs
1858 r, li := l.toLocal(i)
1859 return r, r.Auxs(li)
1863 // Returns a specific aux symbol of type t for symbol i.
1864 func (l *Loader) aux1(i Sym, t uint8) Sym {
1865 r, auxs := l.auxs(i)
1866 for j := range auxs {
1869 return l.resolve(r, a.Sym())
1875 func (l *Loader) Pcsp(i Sym) Sym { return l.aux1(i, goobj.AuxPcsp) }
1877 // Returns all aux symbols of per-PC data for symbol i.
1878 // tmp is a scratch space for the pcdata slice.
1879 func (l *Loader) PcdataAuxs(i Sym, tmp []Sym) (pcsp, pcfile, pcline, pcinline Sym, pcdata []Sym) {
1881 r, auxs := l.auxs(i)
1882 for j := range auxs {
1886 pcsp = l.resolve(r, a.Sym())
1887 case goobj.AuxPcline:
1888 pcline = l.resolve(r, a.Sym())
1889 case goobj.AuxPcfile:
1890 pcfile = l.resolve(r, a.Sym())
1891 case goobj.AuxPcinline:
1892 pcinline = l.resolve(r, a.Sym())
1893 case goobj.AuxPcdata:
1894 pcdata = append(pcdata, l.resolve(r, a.Sym()))
1900 // Returns the number of pcdata for symbol i.
1901 func (l *Loader) NumPcdata(i Sym) int {
1903 _, auxs := l.auxs(i)
1904 for j := range auxs {
1906 if a.Type() == goobj.AuxPcdata {
1913 // Returns all funcdata symbols of symbol i.
1914 // tmp is a scratch space.
1915 func (l *Loader) Funcdata(i Sym, tmp []Sym) []Sym {
1917 r, auxs := l.auxs(i)
1918 for j := range auxs {
1920 if a.Type() == goobj.AuxFuncdata {
1921 fd = append(fd, l.resolve(r, a.Sym()))
1927 // Returns the number of funcdata for symbol i.
1928 func (l *Loader) NumFuncdata(i Sym) int {
1930 _, auxs := l.auxs(i)
1931 for j := range auxs {
1933 if a.Type() == goobj.AuxFuncdata {
1940 // FuncInfo provides hooks to access goobj.FuncInfo in the objects.
1941 type FuncInfo struct {
1945 lengths goobj.FuncInfoLengths
1948 func (fi *FuncInfo) Valid() bool { return fi.r != nil }
1950 func (fi *FuncInfo) Args() int {
1951 return int((*goobj.FuncInfo)(nil).ReadArgs(fi.data))
1954 func (fi *FuncInfo) Locals() int {
1955 return int((*goobj.FuncInfo)(nil).ReadLocals(fi.data))
1958 func (fi *FuncInfo) FuncID() objabi.FuncID {
1959 return (*goobj.FuncInfo)(nil).ReadFuncID(fi.data)
1962 func (fi *FuncInfo) FuncFlag() objabi.FuncFlag {
1963 return (*goobj.FuncInfo)(nil).ReadFuncFlag(fi.data)
1966 // Preload has to be called prior to invoking the various methods
1967 // below related to pcdata, funcdataoff, files, and inltree nodes.
1968 func (fi *FuncInfo) Preload() {
1969 fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
1972 func (fi *FuncInfo) NumFile() uint32 {
1973 if !fi.lengths.Initialized {
1974 panic("need to call Preload first")
1976 return fi.lengths.NumFile
1979 func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
1980 if !fi.lengths.Initialized {
1981 panic("need to call Preload first")
1983 return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
1986 // TopFrame returns true if the function associated with this FuncInfo
1987 // is an entry point, meaning that unwinders should stop when they hit
1989 func (fi *FuncInfo) TopFrame() bool {
1990 return (fi.FuncFlag() & objabi.FuncFlag_TOPFRAME) != 0
1993 type InlTreeNode struct {
1995 File goobj.CUFileIndex
2001 func (fi *FuncInfo) NumInlTree() uint32 {
2002 if !fi.lengths.Initialized {
2003 panic("need to call Preload first")
2005 return fi.lengths.NumInlTree
2008 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
2009 if !fi.lengths.Initialized {
2010 panic("need to call Preload first")
2012 node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
2014 Parent: node.Parent,
2017 Func: fi.l.resolve(fi.r, node.Func),
2018 ParentPC: node.ParentPC,
2022 func (l *Loader) FuncInfo(i Sym) FuncInfo {
2023 r, auxs := l.auxs(i)
2024 for j := range auxs {
2026 if a.Type() == goobj.AuxFuncInfo {
2027 b := r.Data(a.Sym().SymIdx)
2028 return FuncInfo{l, r, b, goobj.FuncInfoLengths{}}
2034 // Preload a package: adds autolib.
2035 // Does not add defined package or non-packaged symbols to the symbol table.
2036 // These are done in LoadSyms.
2037 // Does not read symbol data.
2038 // Returns the fingerprint of the object.
2039 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
2040 roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
2042 log.Fatal("cannot read object file:", err)
2044 r := goobj.NewReaderFromBytes(roObject, readonly)
2046 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
2047 log.Fatalf("found object file %s in old format", f.File().Name())
2049 panic("cannot read object file")
2051 pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
2053 nhashed64def := r.NHashed64def()
2054 nhasheddef := r.NHasheddef()
2058 version: localSymVersion,
2059 pkgprefix: pkgprefix,
2060 syms: make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
2062 nhasheddef: nhasheddef,
2063 nhashed64def: nhashed64def,
2064 objidx: uint32(len(l.objs)),
2068 log.Fatalf("link: unlinkable object (from package %s) - compiler requires -p flag", lib.Pkg)
2072 lib.Autolib = append(lib.Autolib, r.Autolib()...)
2076 unit.FileTable = make([]string, nfile)
2077 for i := range unit.FileTable {
2078 unit.FileTable[i] = r.File(i)
2081 l.addObj(lib.Pkg, or)
2083 // The caller expects us consuming all the data
2084 f.MustSeek(length, os.SEEK_CUR)
2086 return r.Fingerprint()
2089 // Holds the loader along with temporary states for loading symbols.
2090 type loadState struct {
2092 hashed64Syms map[uint64]symAndSize // short hashed (content-addressable) symbols, keyed by content hash
2093 hashedSyms map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
2096 // Preload symbols of given kind from an object.
2097 func (st *loadState) preloadSyms(r *oReader, kind int) {
2099 var start, end uint32
2103 end = uint32(r.ndef)
2105 start = uint32(r.ndef)
2106 end = uint32(r.ndef + r.nhashed64def)
2108 start = uint32(r.ndef + r.nhashed64def)
2109 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2111 start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2112 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
2114 panic("preloadSyms: bad kind")
2116 l.growAttrBitmaps(len(l.objSyms) + int(end-start))
2117 loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
2118 for i := start; i < end; i++ {
2122 if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
2123 name = osym.Name(r.Reader)
2124 v = abiToVer(osym.ABI(), r.version)
2126 gi := st.addSym(name, v, r, i, kind, osym)
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, int(osym.ABI())); 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 syms, hashed (content-addressable) symbols, non-package symbols, and
2148 // references to external symbols (which are always named).
2149 func (l *Loader) LoadSyms(arch *sys.Arch) {
2150 // Allocate space for symbols, making a guess as to how much space we need.
2151 // This function was determined empirically by looking at the cmd/compile on
2152 // Darwin, and picking factors for hashed and hashed64 syms.
2153 var symSize, hashedSize, hashed64Size int
2154 for _, o := range l.objs[goObjStart:] {
2155 symSize += o.r.ndef + o.r.nhasheddef/2 + o.r.nhashed64def/2 + o.r.NNonpkgdef()
2156 hashedSize += o.r.nhasheddef / 2
2157 hashed64Size += o.r.nhashed64def / 2
2159 // Index 0 is invalid for symbols.
2160 l.objSyms = make([]objSym, 1, symSize)
2164 hashed64Syms: make(map[uint64]symAndSize, hashed64Size),
2165 hashedSyms: make(map[goobj.HashType]symAndSize, hashedSize),
2168 for _, o := range l.objs[goObjStart:] {
2169 st.preloadSyms(o.r, pkgDef)
2171 l.npkgsyms = l.NSym()
2172 for _, o := range l.objs[goObjStart:] {
2173 st.preloadSyms(o.r, hashed64Def)
2174 st.preloadSyms(o.r, hashedDef)
2175 st.preloadSyms(o.r, nonPkgDef)
2177 l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
2178 for _, o := range l.objs[goObjStart:] {
2179 loadObjRefs(l, o.r, arch)
2181 l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2184 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2185 // load non-package refs
2186 ndef := uint32(r.NAlldef())
2187 for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2188 osym := r.Sym(ndef + i)
2189 name := osym.Name(r.Reader)
2190 v := abiToVer(osym.ABI(), r.version)
2191 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2192 gi := r.syms[ndef+i]
2194 l.SetAttrLocal(gi, true)
2196 if osym.UsedInIface() {
2197 l.SetAttrUsedInIface(gi, true)
2201 // referenced packages
2203 r.pkg = make([]uint32, npkg)
2204 for i := 1; i < npkg; i++ { // PkgIdx 0 is a dummy invalid package
2206 objidx, ok := l.objByPkg[pkg]
2208 log.Fatalf("%v: reference to nonexistent package %s", r.unit.Lib, pkg)
2213 // load flags of package refs
2214 for i, n := 0, r.NRefFlags(); i < n; i++ {
2216 gi := l.resolve(r, rf.Sym())
2217 if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
2218 l.SetAttrUsedInIface(gi, true)
2223 func abiToVer(abi uint16, localSymVersion int) int {
2225 if abi == goobj.SymABIstatic {
2228 } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2229 // Note that data symbols are "ABI0", which maps to version 0.
2232 log.Fatalf("invalid symbol ABI: %d", abi)
2237 // TopLevelSym tests a symbol (by name and kind) to determine whether
2238 // the symbol first class sym (participating in the link) or is an
2239 // anonymous aux or sub-symbol containing some sub-part or payload of
2241 func (l *Loader) TopLevelSym(s Sym) bool {
2242 return topLevelSym(l.SymName(s), l.SymType(s))
2245 // topLevelSym tests a symbol name and kind to determine whether
2246 // the symbol first class sym (participating in the link) or is an
2247 // anonymous aux or sub-symbol containing some sub-part or payload of
2249 func topLevelSym(sname string, skind sym.SymKind) bool {
2254 case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2261 // cloneToExternal takes the existing object file symbol (symIdx)
2262 // and creates a new external symbol payload that is a clone with
2263 // respect to name, version, type, relocations, etc. The idea here
2264 // is that if the linker decides it wants to update the contents of
2265 // a symbol originally discovered as part of an object file, it's
2266 // easier to do this if we make the updates to an external symbol
2268 func (l *Loader) cloneToExternal(symIdx Sym) {
2269 if l.IsExternal(symIdx) {
2270 panic("sym is already external, no need for clone")
2273 // Read the particulars from object.
2274 r, li := l.toLocal(symIdx)
2276 sname := osym.Name(r.Reader)
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 for i := range pp.relocs {
2296 // Copy the relocs slice.
2297 // Convert local reference to global reference.
2299 pp.relocs[i].Set(rel.Off(), rel.Siz(), uint16(rel.Type()), rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2303 pp.data = r.Data(li)
2306 // If we're overriding a data symbol, collect the associated
2307 // Gotype, so as to propagate it to the new symbol.
2311 // Install new payload to global index space.
2312 // (This needs to happen at the end, as the accessors above
2313 // need to access the old symbol content.)
2314 l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2315 l.extReader.syms = append(l.extReader.syms, symIdx)
2317 // Some attributes were encoded in the object file. Copy them over.
2318 l.SetAttrDuplicateOK(symIdx, r.Sym(li).Dupok())
2319 l.SetAttrShared(symIdx, r.Shared())
2322 // Copy the payload of symbol src to dst. Both src and dst must be external
2324 // The intended use case is that when building/linking against a shared library,
2325 // where we do symbol name mangling, the Go object file may have reference to
2326 // the original symbol name whereas the shared library provides a symbol with
2327 // the mangled name. When we do mangling, we copy payload of mangled to original.
2328 func (l *Loader) CopySym(src, dst Sym) {
2329 if !l.IsExternal(dst) {
2330 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2332 if !l.IsExternal(src) {
2333 panic("src is not external") //l.cloneToExternal(src)
2335 l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2336 l.SetSymPkg(dst, l.SymPkg(src))
2337 // TODO: other attributes?
2340 // CreateExtSym creates a new external symbol with the specified name
2341 // without adding it to any lookup tables, returning a Sym index for it.
2342 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2343 return l.newExtSym(name, ver)
2346 // CreateStaticSym creates a new static symbol with the specified name
2347 // without adding it to any lookup tables, returning a Sym index for it.
2348 func (l *Loader) CreateStaticSym(name string) Sym {
2349 // Assign a new unique negative version -- this is to mark the
2350 // symbol so that it is not included in the name lookup table.
2352 return l.newExtSym(name, l.anonVersion)
2355 func (l *Loader) FreeSym(i Sym) {
2356 if l.IsExternal(i) {
2357 pp := l.getPayload(i)
2358 *pp = extSymPayload{}
2362 // relocId is essentially a <S,R> tuple identifying the Rth
2363 // relocation of symbol S.
2364 type relocId struct {
2369 // SetRelocVariant sets the 'variant' property of a relocation on
2370 // some specific symbol.
2371 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2373 if relocs := l.Relocs(s); ri >= relocs.Count() {
2374 panic("invalid relocation ID")
2376 if l.relocVariant == nil {
2377 l.relocVariant = make(map[relocId]sym.RelocVariant)
2380 l.relocVariant[relocId{s, ri}] = v
2382 delete(l.relocVariant, relocId{s, ri})
2386 // RelocVariant returns the 'variant' property of a relocation on
2387 // some specific symbol.
2388 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2389 return l.relocVariant[relocId{s, ri}]
2392 // UndefinedRelocTargets iterates through the global symbol index
2393 // space, looking for symbols with relocations targeting undefined
2394 // references. The linker's loadlib method uses this to determine if
2395 // there are unresolved references to functions in system libraries
2396 // (for example, libgcc.a), presumably due to CGO code. Return
2397 // value is a list of loader.Sym's corresponding to the undefined
2398 // cross-refs. The "limit" param controls the maximum number of
2399 // results returned; if "limit" is -1, then all undefs are returned.
2400 func (l *Loader) UndefinedRelocTargets(limit int) []Sym {
2402 for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2403 relocs := l.Relocs(si)
2404 for ri := 0; ri < relocs.Count(); ri++ {
2407 if rs != 0 && l.SymType(rs) == sym.SXREF && l.SymName(rs) != ".got" {
2408 result = append(result, rs)
2409 if limit != -1 && len(result) >= limit {
2418 // AssignTextSymbolOrder populates the Textp slices within each
2419 // library and compilation unit, insuring that packages are laid down
2420 // in dependency order (internal first, then everything else). Return value
2421 // is a slice of all text syms.
2422 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2424 // Library Textp lists should be empty at this point.
2425 for _, lib := range libs {
2426 if len(lib.Textp) != 0 {
2427 panic("expected empty Textp slice for library")
2429 if len(lib.DupTextSyms) != 0 {
2430 panic("expected empty DupTextSyms slice for library")
2434 // Used to record which dupok symbol we've assigned to a unit.
2435 // Can't use the onlist attribute here because it will need to
2436 // clear for the later assignment of the sym.Symbol to a unit.
2437 // NB: we can convert to using onList once we no longer have to
2438 // call the regular addToTextp.
2439 assignedToUnit := MakeBitmap(l.NSym() + 1)
2441 // Start off textp with reachable external syms.
2443 for _, sym := range extsyms {
2444 if !l.attrReachable.Has(sym) {
2447 textp = append(textp, sym)
2450 // Walk through all text symbols from Go object files and append
2451 // them to their corresponding library's textp list.
2452 for _, o := range l.objs[goObjStart:] {
2455 for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
2456 gi := l.toGlobal(r, i)
2457 if !l.attrReachable.Has(gi) {
2461 st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2462 if st != sym.STEXT {
2465 dupok := osym.Dupok()
2466 if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2467 // A dupok text symbol is resolved to another package.
2468 // We still need to record its presence in the current
2469 // package, as the trampoline pass expects packages
2470 // are laid out in dependency order.
2471 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2472 continue // symbol in different object
2475 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2479 lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2483 // Now assemble global textp, and assign text symbols to units.
2484 for _, doInternal := range [2]bool{true, false} {
2485 for idx, lib := range libs {
2486 if intlibs[idx] != doInternal {
2489 lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2490 for i, list := range lists {
2491 for _, s := range list {
2493 if !assignedToUnit.Has(sym) {
2494 textp = append(textp, sym)
2495 unit := l.SymUnit(sym)
2497 unit.Textp = append(unit.Textp, s)
2498 assignedToUnit.Set(sym)
2500 // Dupok symbols may be defined in multiple packages; the
2501 // associated package for a dupok sym is chosen sort of
2502 // arbitrarily (the first containing package that the linker
2503 // loads). Canonicalizes its Pkg to the package with which
2504 // it will be laid down in text.
2505 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2506 l.SetSymPkg(sym, lib.Pkg)
2512 lib.DupTextSyms = nil
2519 // ErrorReporter is a helper class for reporting errors.
2520 type ErrorReporter struct {
2522 AfterErrorAction func()
2525 // Errorf method logs an error message.
2527 // After each error, the error actions function will be invoked; this
2528 // will either terminate the link immediately (if -h option given)
2529 // or it will keep a count and exit if more than 20 errors have been printed.
2531 // Logging an error means that on exit cmd/link will delete any
2532 // output file and return a non-zero error code.
2533 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2534 if s != 0 && reporter.ldr.SymName(s) != "" {
2535 // Note: Replace is needed here because symbol names might have % in them,
2536 // due to the use of LinkString for names of instantiating types.
2537 format = strings.Replace(reporter.ldr.SymName(s), "%", "%%", -1) + ": " + format
2539 format = fmt.Sprintf("sym %d: %s", s, format)
2542 fmt.Fprintf(os.Stderr, format, args...)
2543 reporter.AfterErrorAction()
2546 // GetErrorReporter returns the loader's associated error reporter.
2547 func (l *Loader) GetErrorReporter() *ErrorReporter {
2548 return l.errorReporter
2551 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2552 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2553 l.errorReporter.Errorf(s, format, args...)
2556 // Symbol statistics.
2557 func (l *Loader) Stat() string {
2558 s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
2559 s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
2560 l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
2565 func (l *Loader) Dump() {
2567 for _, obj := range l.objs[goObjStart:] {
2569 fmt.Println(obj.i, obj.r.unit.Lib)
2572 fmt.Println("extStart:", l.extStart)
2573 fmt.Println("Nsyms:", len(l.objSyms))
2575 for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2577 if l.IsExternal(i) {
2578 pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2581 if l.SymSect(i) != nil {
2582 sect = l.SymSect(i).Name
2584 fmt.Printf("%v %v %v %v %x %v\n", i, l.SymName(i), l.SymType(i), pi, l.SymValue(i), sect)
2586 fmt.Println("symsByName")
2587 for name, i := range l.symsByName[0] {
2588 fmt.Println(i, name, 0)
2590 for name, i := range l.symsByName[1] {
2591 fmt.Println(i, name, 1)
2593 fmt.Println("payloads:")
2594 for i := range l.payloads {
2596 fmt.Println(i, pp.name, pp.ver, pp.kind)