1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 "cmd/link/internal/sym"
26 // Sym encapsulates a global symbol index, used to identify a specific
27 // Go symbol. The 0-valued Sym is corresponds to an invalid symbol.
30 // Relocs encapsulates the set of relocations on a given symbol; an
31 // instance of this type is returned by the Loader Relocs() method.
35 li uint32 // local index of symbol whose relocs we're examining
36 r *oReader // object reader for containing package
40 // ExtReloc contains the payload for an external relocation.
41 type ExtReloc struct {
48 // Reloc holds a "handle" to access a relocation record from an
55 // External reloc types may not fit into a uint8 which the Go object file uses.
56 // Store it here, instead of in the byte of goobj.Reloc.
57 // For Go symbols this will always be zero.
58 // goobj.Reloc.Type() + typ is always the right type, for both Go and external
63 func (rel Reloc) Type() objabi.RelocType { return objabi.RelocType(rel.Reloc.Type()) + rel.typ }
64 func (rel Reloc) Sym() Sym { return rel.l.resolve(rel.r, rel.Reloc.Sym()) }
65 func (rel Reloc) SetSym(s Sym) { rel.Reloc.SetSym(goobj.SymRef{PkgIdx: 0, SymIdx: uint32(s)}) }
66 func (rel Reloc) IsMarker() bool { return rel.Siz() == 0 }
68 func (rel Reloc) SetType(t objabi.RelocType) {
69 if t != objabi.RelocType(uint8(t)) {
70 panic("SetType: type doesn't fit into Reloc")
72 rel.Reloc.SetType(uint8(t))
74 // should use SymbolBuilder.SetRelocType
75 panic("wrong method to set reloc type")
79 // Aux holds a "handle" to access an aux symbol record from an
87 func (a Aux) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
89 // oReader is a wrapper type of obj.Reader, along with some
93 unit *sym.CompilationUnit
94 version int // version of static symbol
95 flags uint32 // read from object file
97 syms []Sym // Sym's global index, indexed by local index
98 pkg []uint32 // indices of referenced package by PkgIdx (index into loader.objs array)
99 ndef int // cache goobj.Reader.NSym()
100 nhashed64def int // cache goobj.Reader.NHashed64Def()
101 nhasheddef int // cache goobj.Reader.NHashedDef()
102 objidx uint32 // index of this reader in the objs slice
105 // Total number of defined symbols (package symbols, hashed symbols, and
106 // non-package symbols).
107 func (r *oReader) NAlldef() int { return r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef() }
114 // objSym represents a symbol in an object file. It is a tuple of
115 // the object and the symbol's local index.
116 // For external symbols, objidx is the index of l.extReader (extObj),
117 // s is its index into the payload array.
118 // {0, 0} represents the nil symbol.
120 objidx uint32 // index of the object (in l.objs array)
121 s uint32 // local index
124 type nameVer struct {
132 func (bm Bitmap) Set(i Sym) {
133 n, r := uint(i)/32, uint(i)%32
137 // unset the i-th bit.
138 func (bm Bitmap) Unset(i Sym) {
139 n, r := uint(i)/32, uint(i)%32
143 // whether the i-th bit is set.
144 func (bm Bitmap) Has(i Sym) bool {
145 n, r := uint(i)/32, uint(i)%32
146 return bm[n]&(1<<r) != 0
149 // return current length of bitmap in bits.
150 func (bm Bitmap) Len() int {
154 // return the number of bits set.
155 func (bm Bitmap) Count() int {
157 for _, x := range bm {
158 s += bits.OnesCount32(x)
163 func MakeBitmap(n int) Bitmap {
164 return make(Bitmap, (n+31)/32)
167 // growBitmap insures that the specified bitmap has enough capacity,
168 // reallocating (doubling the size) if needed.
169 func growBitmap(reqLen int, b Bitmap) Bitmap {
172 b = append(b, MakeBitmap(reqLen+1-curLen)...)
177 type symAndSize struct {
182 // A Loader loads new object files and resolves indexed symbol references.
184 // Notes on the layout of global symbol index space:
186 // - Go object files are read before host object files; each Go object
187 // read adds its defined package symbols to the global index space.
188 // Nonpackage symbols are not yet added.
190 // - In loader.LoadNonpkgSyms, add non-package defined symbols and
191 // references in all object files to the global index space.
193 // - Host object file loading happens; the host object loader does a
194 // name/version lookup for each symbol it finds; this can wind up
195 // extending the external symbol index space range. The host object
196 // loader stores symbol payloads in loader.payloads using SymbolBuilder.
198 // - Each symbol gets a unique global index. For duplicated and
199 // overwriting/overwritten symbols, the second (or later) appearance
200 // of the symbol gets the same global index as the first appearance.
202 start map[*oReader]Sym // map from object file to its start index
203 objs []objIdx // sorted by start index (i.e. objIdx.i)
204 extStart Sym // from this index on, the symbols are externally defined
205 builtinSyms []Sym // global index of builtin symbols
207 objSyms []objSym // global index mapping to local index
209 symsByName [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
210 extStaticSyms map[nameVer]Sym // externally defined static symbols, keyed by name
212 extReader *oReader // a dummy oReader, for external symbols
213 payloadBatch []extSymPayload
214 payloads []*extSymPayload // contents of linker-materialized external syms
215 values []int64 // symbol values, indexed by global sym index
217 sects []*sym.Section // sections
218 symSects []uint16 // symbol's section, index to sects array
220 align []uint8 // symbol 2^N alignment, indexed by global index
222 deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
224 objByPkg map[string]uint32 // map package path to the index of its Go object reader
226 anonVersion int // most recently assigned ext static sym pseudo-version
228 // Bitmaps and other side structures used to store data used to store
229 // symbol flags/attributes; these are to be accessed via the
230 // corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
231 // visit the comments on these methods for more details on the
232 // semantics / interpretation of the specific flags or attribute.
233 attrReachable Bitmap // reachable symbols, indexed by global index
234 attrOnList Bitmap // "on list" symbols, indexed by global index
235 attrLocal Bitmap // "local" symbols, indexed by global index
236 attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by global idx
237 attrUsedInIface Bitmap // "used in interface" symbols, indexed by global idx
238 attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
239 attrDuplicateOK Bitmap // dupOK symbols, indexed by ext sym index
240 attrShared Bitmap // shared symbols, indexed by ext sym index
241 attrExternal Bitmap // external symbols, indexed by ext sym index
243 attrReadOnly map[Sym]bool // readonly data for this sym
244 attrSpecial map[Sym]struct{} // "special" frame symbols
245 attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
246 attrCgoExportStatic map[Sym]struct{} // "cgo_export_static" symbols
247 generatedSyms map[Sym]struct{} // symbols that generate their content
249 // Outer and Sub relations for symbols.
250 // TODO: figure out whether it's more efficient to just have these
251 // as fields on extSymPayload (note that this won't be a viable
252 // strategy if somewhere in the linker we set sub/outer for a
253 // non-external sym).
257 dynimplib map[Sym]string // stores Dynimplib symbol attribute
258 dynimpvers map[Sym]string // stores Dynimpvers symbol attribute
259 localentry map[Sym]uint8 // stores Localentry symbol attribute
260 extname map[Sym]string // stores Extname symbol attribute
261 elfType map[Sym]elf.SymType // stores elf type symbol property
262 elfSym map[Sym]int32 // stores elf sym symbol property
263 localElfSym map[Sym]int32 // stores "local" elf sym symbol property
264 symPkg map[Sym]string // stores package for symbol, or library for shlib-derived syms
265 plt map[Sym]int32 // stores dynimport for pe objects
266 got map[Sym]int32 // stores got for pe objects
267 dynid map[Sym]int32 // stores Dynid for symbol
269 relocVariant map[relocId]sym.RelocVariant // stores variant relocs
271 // Used to implement field tracking; created during deadcode if
272 // field tracking is enabled. Reachparent[K] contains the index of
273 // the symbol that triggered the marking of symbol K as live.
278 hasUnknownPkgPath bool // if any Go object has unknown package path
280 strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
282 elfsetstring elfsetstringFunc
284 errorReporter *ErrorReporter
286 npkgsyms int // number of package symbols, for accounting
287 nhashedsyms int // number of hashed symbols, for accounting
305 type elfsetstringFunc func(str string, off int)
307 // extSymPayload holds the payload (data + relocations) for linker-synthesized
308 // external symbols (note that symbol value is stored in a separate slice).
309 type extSymPayload struct {
310 name string // TODO: would this be better as offset into str table?
314 objidx uint32 // index of original object if sym made by cloneToExternal
316 reltypes []objabi.RelocType // relocation types
323 FlagStrictDups = 1 << iota
327 func NewLoader(flags uint32, elfsetstring elfsetstringFunc, reporter *ErrorReporter) *Loader {
328 nbuiltin := goobj.NBuiltin()
329 extReader := &oReader{objidx: extObj}
331 start: make(map[*oReader]Sym),
332 objs: []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
333 objSyms: make([]objSym, 1, 1), // This will get overwritten later.
334 extReader: extReader,
335 symsByName: [2]map[string]Sym{make(map[string]Sym, 80000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
336 objByPkg: make(map[string]uint32),
337 outer: make(map[Sym]Sym),
338 sub: make(map[Sym]Sym),
339 dynimplib: make(map[Sym]string),
340 dynimpvers: make(map[Sym]string),
341 localentry: make(map[Sym]uint8),
342 extname: make(map[Sym]string),
343 attrReadOnly: make(map[Sym]bool),
344 elfType: make(map[Sym]elf.SymType),
345 elfSym: make(map[Sym]int32),
346 localElfSym: make(map[Sym]int32),
347 symPkg: make(map[Sym]string),
348 plt: make(map[Sym]int32),
349 got: make(map[Sym]int32),
350 dynid: make(map[Sym]int32),
351 attrSpecial: make(map[Sym]struct{}),
352 attrCgoExportDynamic: make(map[Sym]struct{}),
353 attrCgoExportStatic: make(map[Sym]struct{}),
354 generatedSyms: make(map[Sym]struct{}),
355 deferReturnTramp: make(map[Sym]bool),
356 extStaticSyms: make(map[nameVer]Sym),
357 builtinSyms: make([]Sym, nbuiltin),
359 elfsetstring: elfsetstring,
360 errorReporter: reporter,
361 sects: []*sym.Section{nil}, // reserve index 0 for nil section
367 // Add object file r, return the start index.
368 func (l *Loader) addObj(pkg string, r *oReader) Sym {
369 if _, ok := l.start[r]; ok {
370 panic("already added")
372 pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
373 if _, ok := l.objByPkg[pkg]; !ok {
374 l.objByPkg[pkg] = r.objidx
376 i := Sym(len(l.objSyms))
378 l.objs = append(l.objs, objIdx{r, i})
379 if r.NeedNameExpansion() && !r.FromAssembly() {
380 l.hasUnknownPkgPath = true
385 // Add a symbol from an object file, return the global index.
386 // If the symbol already exist, it returns the index of that symbol.
387 func (st *loadState) addSym(name string, ver int, r *oReader, li uint32, kind int, osym *goobj.Sym) Sym {
390 panic("addSym called after external symbol is created")
392 i := Sym(len(l.objSyms))
393 addToGlobal := func() {
394 l.objSyms = append(l.objSyms, objSym{r.objidx, li})
396 if name == "" && kind != hashed64Def && kind != hashedDef {
398 return i // unnamed aux symbol
400 if ver == r.version {
401 // Static symbol. Add its global index but don't
402 // add to name lookup table, as it cannot be
403 // referenced by name.
409 // Defined package symbols cannot be dup to each other.
410 // We load all the package symbols first, so we don't need
411 // to check dup here.
412 // We still add it to the lookup table, as it may still be
413 // referenced by name (e.g. through linkname).
414 l.symsByName[ver][name] = i
417 case hashed64Def, hashedDef:
418 // Hashed (content-addressable) symbol. Check the hash
419 // but don't add to name lookup table, as they are not
420 // referenced by name. Also no need to do overwriting
421 // check, as same hash indicates same content.
422 var checkHash func() (symAndSize, bool)
423 var addToHashMap func(symAndSize)
424 var h64 uint64 // only used for hashed64Def
425 var h *goobj.HashType // only used for hashedDef
426 if kind == hashed64Def {
427 checkHash = func() (symAndSize, bool) {
428 h64 = r.Hash64(li - uint32(r.ndef))
429 s, existed := st.hashed64Syms[h64]
432 addToHashMap = func(ss symAndSize) { st.hashed64Syms[h64] = ss }
434 checkHash = func() (symAndSize, bool) {
435 h = r.Hash(li - uint32(r.ndef+r.nhashed64def))
436 s, existed := st.hashedSyms[*h]
439 addToHashMap = func(ss symAndSize) { st.hashedSyms[*h] = ss }
442 if s, existed := checkHash(); existed {
443 // The content hash is built from symbol data and relocations. In the
444 // object file, the symbol data may not always contain trailing zeros,
445 // e.g. for [5]int{1,2,3} and [100]int{1,2,3}, the data is same
446 // (although the size is different).
447 // Also, for short symbols, the content hash is the identity function of
448 // the 8 bytes, and trailing zeros doesn't change the hash value, e.g.
449 // hash("A") == hash("A\0\0\0").
450 // So when two symbols have the same hash, we need to use the one with
453 // New symbol has larger size, use the new one. Rewrite the index mapping.
454 l.objSyms[s.sym] = objSym{r.objidx, li}
455 addToHashMap(symAndSize{s.sym, siz})
459 addToHashMap(symAndSize{i, siz})
464 // Non-package (named) symbol. Check if it already exists.
465 oldi, existed := l.symsByName[ver][name]
467 l.symsByName[ver][name] = i
471 // symbol already exists
473 if l.flags&FlagStrictDups != 0 {
474 l.checkdup(name, r, li, oldi)
478 oldr, oldli := l.toLocal(oldi)
479 oldsym := oldr.Sym(oldli)
483 overwrite := r.DataSize(li) != 0
485 // new symbol overwrites old symbol.
486 oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
487 if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
488 log.Fatalf("duplicated definition of symbol " + name)
490 l.objSyms[oldi] = objSym{r.objidx, li}
492 // old symbol overwrites new symbol.
493 typ := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
494 if !typ.IsData() { // only allow overwriting data symbol
495 log.Fatalf("duplicated definition of symbol " + name)
501 // newExtSym creates a new external sym with the specified
503 func (l *Loader) newExtSym(name string, ver int) Sym {
504 i := Sym(len(l.objSyms))
508 l.growValues(int(i) + 1)
509 l.growAttrBitmaps(int(i) + 1)
510 pi := l.newPayload(name, ver)
511 l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
512 l.extReader.syms = append(l.extReader.syms, i)
516 // LookupOrCreateSym looks up the symbol with the specified name/version,
517 // returning its Sym index if found. If the lookup fails, a new external
518 // Sym will be created, entered into the lookup tables, and returned.
519 func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
520 i := l.Lookup(name, ver)
524 i = l.newExtSym(name, ver)
525 static := ver >= sym.SymVerStatic || ver < 0
527 l.extStaticSyms[nameVer{name, ver}] = i
529 l.symsByName[ver][name] = i
534 func (l *Loader) IsExternal(i Sym) bool {
536 return l.isExtReader(r)
539 func (l *Loader) isExtReader(r *oReader) bool {
540 return r == l.extReader
543 // For external symbol, return its index in the payloads array.
544 // XXX result is actually not a global index. We (ab)use the Sym type
545 // so we don't need conversion for accessing bitmaps.
546 func (l *Loader) extIndex(i Sym) Sym {
547 _, li := l.toLocal(i)
551 // Get a new payload for external symbol, return its index in
552 // the payloads array.
553 func (l *Loader) newPayload(name string, ver int) int {
554 pi := len(l.payloads)
555 pp := l.allocPayload()
558 l.payloads = append(l.payloads, pp)
559 l.growExtAttrBitmaps()
563 // getPayload returns a pointer to the extSymPayload struct for an
564 // external symbol if the symbol has a payload. Will panic if the
565 // symbol in question is bogus (zero or not an external sym).
566 func (l *Loader) getPayload(i Sym) *extSymPayload {
567 if !l.IsExternal(i) {
568 panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
571 return l.payloads[pi]
574 // allocPayload allocates a new payload.
575 func (l *Loader) allocPayload() *extSymPayload {
576 batch := l.payloadBatch
578 batch = make([]extSymPayload, 1000)
581 l.payloadBatch = batch[1:]
585 func (ms *extSymPayload) Grow(siz int64) {
586 if int64(int(siz)) != siz {
587 log.Fatalf("symgrow size %d too long", siz)
589 if int64(len(ms.data)) >= siz {
592 if cap(ms.data) < int(siz) {
594 ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
595 ms.data = ms.data[0:cl]
597 ms.data = ms.data[:siz]
600 // Convert a local index to a global index.
601 func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
605 // Convert a global index to a local index.
606 func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
607 return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
610 // Resolve a local symbol reference. Return global index.
611 func (l *Loader) resolve(r *oReader, s goobj.SymRef) Sym {
613 switch p := s.PkgIdx; p {
614 case goobj.PkgIdxInvalid:
615 // {0, X} with non-zero X is never a valid sym reference from a Go object.
616 // We steal this space for symbol references from external objects.
617 // In this case, X is just the global index.
618 if l.isExtReader(r) {
625 case goobj.PkgIdxHashed64:
626 i := int(s.SymIdx) + r.ndef
628 case goobj.PkgIdxHashed:
629 i := int(s.SymIdx) + r.ndef + r.nhashed64def
631 case goobj.PkgIdxNone:
632 i := int(s.SymIdx) + r.ndef + r.nhashed64def + r.nhasheddef
634 case goobj.PkgIdxBuiltin:
635 if bi := l.builtinSyms[s.SymIdx]; bi != 0 {
638 l.reportMissingBuiltin(int(s.SymIdx), r.unit.Lib.Pkg)
640 case goobj.PkgIdxSelf:
643 rr = l.objs[r.pkg[p]].r
645 return l.toGlobal(rr, s.SymIdx)
648 // reportMissingBuiltin issues an error in the case where we have a
649 // relocation against a runtime builtin whose definition is not found
650 // when the runtime package is built. The canonical example is
651 // "runtime.racefuncenter" -- currently if you do something like
653 // go build -gcflags=-race myprogram.go
655 // the compiler will insert calls to the builtin runtime.racefuncenter,
656 // but the version of the runtime used for linkage won't actually contain
657 // definitions of that symbol. See issue #42396 for details.
659 // As currently implemented, this is a fatal error. This has drawbacks
660 // in that if there are multiple missing builtins, the error will only
661 // cite the first one. On the plus side, terminating the link here has
662 // advantages in that we won't run the risk of panics or crashes later
663 // on in the linker due to R_CALL relocations with 0-valued target
665 func (l *Loader) reportMissingBuiltin(bsym int, reflib string) {
666 bname, _ := goobj.BuiltinName(bsym)
667 log.Fatalf("reference to undefined builtin %q from package %q",
671 // Look up a symbol by name, return global index, or 0 if not found.
672 // This is more like Syms.ROLookup than Lookup -- it doesn't create
674 func (l *Loader) Lookup(name string, ver int) Sym {
675 if ver >= sym.SymVerStatic || ver < 0 {
676 return l.extStaticSyms[nameVer{name, ver}]
678 return l.symsByName[ver][name]
681 // Check that duplicate symbols have same contents.
682 func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
684 rdup, ldup := l.toLocal(dup)
685 pdup := rdup.Data(ldup)
686 if bytes.Equal(p, pdup) {
689 reason := "same length but different contents"
690 if len(p) != len(pdup) {
691 reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
693 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)
695 // For the moment, allow DWARF subprogram DIEs for
696 // auto-generated wrapper functions. What seems to happen
697 // here is that we get different line numbers on formal
698 // params; I am guessing that the pos is being inherited
699 // from the spot where the wrapper is needed.
700 allowed := strings.HasPrefix(name, "go.info.go.interface") ||
701 strings.HasPrefix(name, "go.info.go.builtin") ||
702 strings.HasPrefix(name, "go.debuglines")
708 func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
710 // Number of total symbols.
711 func (l *Loader) NSym() int {
712 return len(l.objSyms)
715 // Number of defined Go symbols.
716 func (l *Loader) NDef() int {
717 return int(l.extStart)
720 // Number of reachable symbols.
721 func (l *Loader) NReachableSym() int {
722 return l.attrReachable.Count()
725 // SymNameLen returns the length of the symbol name, trying hard not to load
727 func (l *Loader) SymNameLen(i Sym) int {
728 // Not much we can do about external symbols.
730 return len(l.SymName(i))
732 r, li := l.toLocal(i)
733 le := r.Sym(li).NameLen(r.Reader)
734 if !r.NeedNameExpansion() {
737 // Just load the symbol name. We don't know how expanded it'll be.
738 return len(l.SymName(i))
741 // Returns the raw (unpatched) name of the i-th symbol.
742 func (l *Loader) RawSymName(i Sym) string {
744 pp := l.getPayload(i)
747 r, li := l.toLocal(i)
748 return r.Sym(li).Name(r.Reader)
751 // Returns the (patched) name of the i-th symbol.
752 func (l *Loader) SymName(i Sym) string {
754 pp := l.getPayload(i)
757 r, li := l.toLocal(i)
758 name := r.Sym(li).Name(r.Reader)
759 if !r.NeedNameExpansion() {
762 return strings.Replace(name, "\"\".", r.pkgprefix, -1)
765 // Returns the version of the i-th symbol.
766 func (l *Loader) SymVersion(i Sym) int {
768 pp := l.getPayload(i)
771 r, li := l.toLocal(i)
772 return int(abiToVer(r.Sym(li).ABI(), r.version))
775 func (l *Loader) IsFileLocal(i Sym) bool {
776 return l.SymVersion(i) >= sym.SymVerStatic
779 // IsFromAssembly returns true if this symbol is derived from an
780 // object file generated by the Go assembler.
781 func (l *Loader) IsFromAssembly(i Sym) bool {
786 return r.FromAssembly()
789 // Returns the type of the i-th symbol.
790 func (l *Loader) SymType(i Sym) sym.SymKind {
792 pp := l.getPayload(i)
798 r, li := l.toLocal(i)
799 return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
802 // Returns the attributes of the i-th symbol.
803 func (l *Loader) SymAttr(i Sym) uint8 {
805 // TODO: do something? External symbols have different representation of attributes.
806 // For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
807 // set by external symbol.
810 r, li := l.toLocal(i)
811 return r.Sym(li).Flag()
814 // Returns the size of the i-th symbol.
815 func (l *Loader) SymSize(i Sym) int64 {
817 pp := l.getPayload(i)
820 r, li := l.toLocal(i)
821 return int64(r.Sym(li).Siz())
824 // AttrReachable returns true for symbols that are transitively
825 // referenced from the entry points. Unreachable symbols are not
826 // written to the output.
827 func (l *Loader) AttrReachable(i Sym) bool {
828 return l.attrReachable.Has(i)
831 // SetAttrReachable sets the reachability property for a symbol (see
833 func (l *Loader) SetAttrReachable(i Sym, v bool) {
835 l.attrReachable.Set(i)
837 l.attrReachable.Unset(i)
841 // AttrOnList returns true for symbols that are on some list (such as
842 // the list of all text symbols, or one of the lists of data symbols)
843 // and is consulted to avoid bugs where a symbol is put on a list
845 func (l *Loader) AttrOnList(i Sym) bool {
846 return l.attrOnList.Has(i)
849 // SetAttrOnList sets the "on list" property for a symbol (see
851 func (l *Loader) SetAttrOnList(i Sym, v bool) {
855 l.attrOnList.Unset(i)
859 // AttrLocal returns true for symbols that are only visible within the
860 // module (executable or shared library) being linked. This attribute
861 // is applied to thunks and certain other linker-generated symbols.
862 func (l *Loader) AttrLocal(i Sym) bool {
863 return l.attrLocal.Has(i)
866 // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
867 func (l *Loader) SetAttrLocal(i Sym, v bool) {
875 // AttrUsedInIface returns true for a type symbol that is used in
877 func (l *Loader) AttrUsedInIface(i Sym) bool {
878 return l.attrUsedInIface.Has(i)
881 func (l *Loader) SetAttrUsedInIface(i Sym, v bool) {
883 l.attrUsedInIface.Set(i)
885 l.attrUsedInIface.Unset(i)
889 // SymAddr checks that a symbol is reachable, and returns its value.
890 func (l *Loader) SymAddr(i Sym) int64 {
891 if !l.AttrReachable(i) {
892 panic("unreachable symbol in symaddr")
897 // AttrNotInSymbolTable returns true for symbols that should not be
898 // added to the symbol table of the final generated load module.
899 func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
900 return l.attrNotInSymbolTable.Has(i)
903 // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
904 // (see AttrNotInSymbolTable above).
905 func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
907 l.attrNotInSymbolTable.Set(i)
909 l.attrNotInSymbolTable.Unset(i)
913 // AttrVisibilityHidden symbols returns true for ELF symbols with
914 // visibility set to STV_HIDDEN. They become local symbols in
915 // the final executable. Only relevant when internally linking
916 // on an ELF platform.
917 func (l *Loader) AttrVisibilityHidden(i Sym) bool {
918 if !l.IsExternal(i) {
921 return l.attrVisibilityHidden.Has(l.extIndex(i))
924 // SetAttrVisibilityHidden sets the "hidden visibility" property for a
925 // symbol (see AttrVisibilityHidden).
926 func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
927 if !l.IsExternal(i) {
928 panic("tried to set visibility attr on non-external symbol")
931 l.attrVisibilityHidden.Set(l.extIndex(i))
933 l.attrVisibilityHidden.Unset(l.extIndex(i))
937 // AttrDuplicateOK returns true for a symbol that can be present in
938 // multiple object files.
939 func (l *Loader) AttrDuplicateOK(i Sym) bool {
940 if !l.IsExternal(i) {
941 // TODO: if this path winds up being taken frequently, it
942 // might make more sense to copy the flag value out of the object
943 // into a larger bitmap during preload.
944 r, li := l.toLocal(i)
945 return r.Sym(li).Dupok()
947 return l.attrDuplicateOK.Has(l.extIndex(i))
950 // SetAttrDuplicateOK sets the "duplicate OK" property for an external
951 // symbol (see AttrDuplicateOK).
952 func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
953 if !l.IsExternal(i) {
954 panic("tried to set dupok attr on non-external symbol")
957 l.attrDuplicateOK.Set(l.extIndex(i))
959 l.attrDuplicateOK.Unset(l.extIndex(i))
963 // AttrShared returns true for symbols compiled with the -shared option.
964 func (l *Loader) AttrShared(i Sym) bool {
965 if !l.IsExternal(i) {
966 // TODO: if this path winds up being taken frequently, it
967 // might make more sense to copy the flag value out of the
968 // object into a larger bitmap during preload.
972 return l.attrShared.Has(l.extIndex(i))
975 // SetAttrShared sets the "shared" property for an external
976 // symbol (see AttrShared).
977 func (l *Loader) SetAttrShared(i Sym, v bool) {
978 if !l.IsExternal(i) {
979 panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
982 l.attrShared.Set(l.extIndex(i))
984 l.attrShared.Unset(l.extIndex(i))
988 // AttrExternal returns true for function symbols loaded from host
990 func (l *Loader) AttrExternal(i Sym) bool {
991 if !l.IsExternal(i) {
994 return l.attrExternal.Has(l.extIndex(i))
997 // SetAttrExternal sets the "external" property for an host object
998 // symbol (see AttrExternal).
999 func (l *Loader) SetAttrExternal(i Sym, v bool) {
1000 if !l.IsExternal(i) {
1001 panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.RawSymName(i)))
1004 l.attrExternal.Set(l.extIndex(i))
1006 l.attrExternal.Unset(l.extIndex(i))
1010 // AttrSpecial returns true for a symbols that do not have their
1011 // address (i.e. Value) computed by the usual mechanism of
1012 // data.go:dodata() & data.go:address().
1013 func (l *Loader) AttrSpecial(i Sym) bool {
1014 _, ok := l.attrSpecial[i]
1018 // SetAttrSpecial sets the "special" property for a symbol (see
1020 func (l *Loader) SetAttrSpecial(i Sym, v bool) {
1022 l.attrSpecial[i] = struct{}{}
1024 delete(l.attrSpecial, i)
1028 // AttrCgoExportDynamic returns true for a symbol that has been
1029 // specially marked via the "cgo_export_dynamic" compiler directive
1030 // written by cgo (in response to //export directives in the source).
1031 func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
1032 _, ok := l.attrCgoExportDynamic[i]
1036 // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
1037 // (see AttrCgoExportDynamic).
1038 func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
1040 l.attrCgoExportDynamic[i] = struct{}{}
1042 delete(l.attrCgoExportDynamic, i)
1046 // AttrCgoExportStatic returns true for a symbol that has been
1047 // specially marked via the "cgo_export_static" directive
1049 func (l *Loader) AttrCgoExportStatic(i Sym) bool {
1050 _, ok := l.attrCgoExportStatic[i]
1054 // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
1055 // (see AttrCgoExportStatic).
1056 func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
1058 l.attrCgoExportStatic[i] = struct{}{}
1060 delete(l.attrCgoExportStatic, i)
1064 // IsGeneratedSym returns true if a symbol's been previously marked as a
1065 // generator symbol through the SetIsGeneratedSym. The functions for generator
1066 // symbols are kept in the Link context.
1067 func (l *Loader) IsGeneratedSym(i Sym) bool {
1068 _, ok := l.generatedSyms[i]
1072 // SetIsGeneratedSym marks symbols as generated symbols. Data shouldn't be
1073 // stored in generated symbols, and a function is registered and called for
1074 // each of these symbols.
1075 func (l *Loader) SetIsGeneratedSym(i Sym, v bool) {
1076 if !l.IsExternal(i) {
1077 panic("only external symbols can be generated")
1080 l.generatedSyms[i] = struct{}{}
1082 delete(l.generatedSyms, i)
1086 func (l *Loader) AttrCgoExport(i Sym) bool {
1087 return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
1090 // AttrReadOnly returns true for a symbol whose underlying data
1091 // is stored via a read-only mmap.
1092 func (l *Loader) AttrReadOnly(i Sym) bool {
1093 if v, ok := l.attrReadOnly[i]; ok {
1096 if l.IsExternal(i) {
1097 pp := l.getPayload(i)
1099 return l.objs[pp.objidx].r.ReadOnly()
1103 r, _ := l.toLocal(i)
1107 // SetAttrReadOnly sets the "data is read only" property for a symbol
1108 // (see AttrReadOnly).
1109 func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
1110 l.attrReadOnly[i] = v
1113 // AttrSubSymbol returns true for symbols that are listed as a
1114 // sub-symbol of some other outer symbol. The sub/outer mechanism is
1115 // used when loading host objects (sections from the host object
1116 // become regular linker symbols and symbols go on the Sub list of
1117 // their section) and for constructing the global offset table when
1118 // internally linking a dynamic executable.
1120 // Note that in later stages of the linker, we set Outer(S) to some
1121 // container symbol C, but don't set Sub(C). Thus we have two
1122 // distinct scenarios:
1124 // - Outer symbol covers the address ranges of its sub-symbols.
1125 // Outer.Sub is set in this case.
1126 // - Outer symbol doesn't conver the address ranges. It is zero-sized
1127 // and doesn't have sub-symbols. In the case, the inner symbol is
1128 // not actually a "SubSymbol". (Tricky!)
1130 // This method returns TRUE only for sub-symbols in the first scenario.
1132 // FIXME: would be better to do away with this and have a better way
1133 // to represent container symbols.
1135 func (l *Loader) AttrSubSymbol(i Sym) bool {
1136 // we don't explicitly store this attribute any more -- return
1137 // a value based on the sub-symbol setting.
1142 return l.SubSym(o) != 0
1145 // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
1146 // clients should instead use the AddInteriorSym method to establish
1147 // containment relationships for host object symbols.
1149 // Returns whether the i-th symbol has ReflectMethod attribute set.
1150 func (l *Loader) IsReflectMethod(i Sym) bool {
1151 return l.SymAttr(i)&goobj.SymFlagReflectMethod != 0
1154 // Returns whether the i-th symbol is nosplit.
1155 func (l *Loader) IsNoSplit(i Sym) bool {
1156 return l.SymAttr(i)&goobj.SymFlagNoSplit != 0
1159 // Returns whether this is a Go type symbol.
1160 func (l *Loader) IsGoType(i Sym) bool {
1161 return l.SymAttr(i)&goobj.SymFlagGoType != 0
1164 // Returns whether this symbol should be included in typelink.
1165 func (l *Loader) IsTypelink(i Sym) bool {
1166 return l.SymAttr(i)&goobj.SymFlagTypelink != 0
1169 // Returns whether this symbol is an itab symbol.
1170 func (l *Loader) IsItab(i Sym) bool {
1171 if l.IsExternal(i) {
1174 r, li := l.toLocal(i)
1175 return r.Sym(li).IsItab()
1178 // Return whether this is a trampoline of a deferreturn call.
1179 func (l *Loader) IsDeferReturnTramp(i Sym) bool {
1180 return l.deferReturnTramp[i]
1183 // Set that i is a trampoline of a deferreturn call.
1184 func (l *Loader) SetIsDeferReturnTramp(i Sym, v bool) {
1185 l.deferReturnTramp[i] = v
1188 // growValues grows the slice used to store symbol values.
1189 func (l *Loader) growValues(reqLen int) {
1190 curLen := len(l.values)
1191 if reqLen > curLen {
1192 l.values = append(l.values, make([]int64, reqLen+1-curLen)...)
1196 // SymValue returns the value of the i-th symbol. i is global index.
1197 func (l *Loader) SymValue(i Sym) int64 {
1201 // SetSymValue sets the value of the i-th symbol. i is global index.
1202 func (l *Loader) SetSymValue(i Sym, val int64) {
1206 // AddToSymValue adds to the value of the i-th symbol. i is the global index.
1207 func (l *Loader) AddToSymValue(i Sym, val int64) {
1211 // Returns the symbol content of the i-th symbol. i is global index.
1212 func (l *Loader) Data(i Sym) []byte {
1213 if l.IsExternal(i) {
1214 pp := l.getPayload(i)
1220 r, li := l.toLocal(i)
1224 // FreeData clears the symbol data of an external symbol, allowing the memory
1225 // to be freed earlier. No-op for non-external symbols.
1226 // i is global index.
1227 func (l *Loader) FreeData(i Sym) {
1228 if l.IsExternal(i) {
1229 pp := l.getPayload(i)
1236 // SymAlign returns the alignment for a symbol.
1237 func (l *Loader) SymAlign(i Sym) int32 {
1238 if int(i) >= len(l.align) {
1239 // align is extended lazily -- it the sym in question is
1240 // outside the range of the existing slice, then we assume its
1241 // alignment has not yet been set.
1244 // TODO: would it make sense to return an arch-specific
1245 // alignment depending on section type? E.g. STEXT => 32,
1251 return int32(1 << (abits - 1))
1254 // SetSymAlign sets the alignment for a symbol.
1255 func (l *Loader) SetSymAlign(i Sym, align int32) {
1256 // Reject nonsense alignments.
1257 if align < 0 || align&(align-1) != 0 {
1258 panic("bad alignment value")
1260 if int(i) >= len(l.align) {
1261 l.align = append(l.align, make([]uint8, l.NSym()-len(l.align))...)
1266 l.align[i] = uint8(bits.Len32(uint32(align)))
1269 // SymValue returns the section of the i-th symbol. i is global index.
1270 func (l *Loader) SymSect(i Sym) *sym.Section {
1271 if int(i) >= len(l.symSects) {
1272 // symSects is extended lazily -- it the sym in question is
1273 // outside the range of the existing slice, then we assume its
1274 // section has not yet been set.
1277 return l.sects[l.symSects[i]]
1280 // SetSymSect sets the section of the i-th symbol. i is global index.
1281 func (l *Loader) SetSymSect(i Sym, sect *sym.Section) {
1282 if int(i) >= len(l.symSects) {
1283 l.symSects = append(l.symSects, make([]uint16, l.NSym()-len(l.symSects))...)
1285 l.symSects[i] = sect.Index
1288 // growSects grows the slice used to store symbol sections.
1289 func (l *Loader) growSects(reqLen int) {
1290 curLen := len(l.symSects)
1291 if reqLen > curLen {
1292 l.symSects = append(l.symSects, make([]uint16, reqLen+1-curLen)...)
1296 // NewSection creates a new (output) section.
1297 func (l *Loader) NewSection() *sym.Section {
1298 sect := new(sym.Section)
1300 if idx != int(uint16(idx)) {
1301 panic("too many sections created")
1303 sect.Index = uint16(idx)
1304 l.sects = append(l.sects, sect)
1308 // SymDynImplib returns the "dynimplib" attribute for the specified
1309 // symbol, making up a portion of the info for a symbol specified
1310 // on a "cgo_import_dynamic" compiler directive.
1311 func (l *Loader) SymDynimplib(i Sym) string {
1312 return l.dynimplib[i]
1315 // SetSymDynimplib sets the "dynimplib" attribute for a symbol.
1316 func (l *Loader) SetSymDynimplib(i Sym, value string) {
1317 // reject bad symbols
1318 if i >= Sym(len(l.objSyms)) || i == 0 {
1319 panic("bad symbol index in SetDynimplib")
1322 delete(l.dynimplib, i)
1324 l.dynimplib[i] = value
1328 // SymDynimpvers returns the "dynimpvers" attribute for the specified
1329 // symbol, making up a portion of the info for a symbol specified
1330 // on a "cgo_import_dynamic" compiler directive.
1331 func (l *Loader) SymDynimpvers(i Sym) string {
1332 return l.dynimpvers[i]
1335 // SetSymDynimpvers sets the "dynimpvers" attribute for a symbol.
1336 func (l *Loader) SetSymDynimpvers(i Sym, value string) {
1337 // reject bad symbols
1338 if i >= Sym(len(l.objSyms)) || i == 0 {
1339 panic("bad symbol index in SetDynimpvers")
1342 delete(l.dynimpvers, i)
1344 l.dynimpvers[i] = value
1348 // SymExtname returns the "extname" value for the specified
1350 func (l *Loader) SymExtname(i Sym) string {
1351 if s, ok := l.extname[i]; ok {
1357 // SetSymExtname sets the "extname" attribute for a symbol.
1358 func (l *Loader) SetSymExtname(i Sym, value string) {
1359 // reject bad symbols
1360 if i >= Sym(len(l.objSyms)) || i == 0 {
1361 panic("bad symbol index in SetExtname")
1364 delete(l.extname, i)
1366 l.extname[i] = value
1370 // SymElfType returns the previously recorded ELF type for a symbol
1371 // (used only for symbols read from shared libraries by ldshlibsyms).
1372 // It is not set for symbols defined by the packages being linked or
1373 // by symbols read by ldelf (and so is left as elf.STT_NOTYPE).
1374 func (l *Loader) SymElfType(i Sym) elf.SymType {
1375 if et, ok := l.elfType[i]; ok {
1378 return elf.STT_NOTYPE
1381 // SetSymElfType sets the elf type attribute for a symbol.
1382 func (l *Loader) SetSymElfType(i Sym, et elf.SymType) {
1383 // reject bad symbols
1384 if i >= Sym(len(l.objSyms)) || i == 0 {
1385 panic("bad symbol index in SetSymElfType")
1387 if et == elf.STT_NOTYPE {
1388 delete(l.elfType, i)
1394 // SymElfSym returns the ELF symbol index for a given loader
1395 // symbol, assigned during ELF symtab generation.
1396 func (l *Loader) SymElfSym(i Sym) int32 {
1400 // SetSymElfSym sets the elf symbol index for a symbol.
1401 func (l *Loader) SetSymElfSym(i Sym, es int32) {
1403 panic("bad sym index")
1412 // SymLocalElfSym returns the "local" ELF symbol index for a given loader
1413 // symbol, assigned during ELF symtab generation.
1414 func (l *Loader) SymLocalElfSym(i Sym) int32 {
1415 return l.localElfSym[i]
1418 // SetSymLocalElfSym sets the "local" elf symbol index for a symbol.
1419 func (l *Loader) SetSymLocalElfSym(i Sym, es int32) {
1421 panic("bad sym index")
1424 delete(l.localElfSym, i)
1426 l.localElfSym[i] = es
1430 // SymPlt returns the plt value for pe symbols.
1431 func (l *Loader) SymPlt(s Sym) int32 {
1432 if v, ok := l.plt[s]; ok {
1438 // SetPlt sets the plt value for pe symbols.
1439 func (l *Loader) SetPlt(i Sym, v int32) {
1440 if i >= Sym(len(l.objSyms)) || i == 0 {
1441 panic("bad symbol for SetPlt")
1450 // SymGot returns the got value for pe symbols.
1451 func (l *Loader) SymGot(s Sym) int32 {
1452 if v, ok := l.got[s]; ok {
1458 // SetGot sets the got value for pe symbols.
1459 func (l *Loader) SetGot(i Sym, v int32) {
1460 if i >= Sym(len(l.objSyms)) || i == 0 {
1461 panic("bad symbol for SetGot")
1470 // SymDynid returns the "dynid" property for the specified symbol.
1471 func (l *Loader) SymDynid(i Sym) int32 {
1472 if s, ok := l.dynid[i]; ok {
1478 // SetSymDynid sets the "dynid" property for a symbol.
1479 func (l *Loader) SetSymDynid(i Sym, val int32) {
1480 // reject bad symbols
1481 if i >= Sym(len(l.objSyms)) || i == 0 {
1482 panic("bad symbol index in SetSymDynid")
1491 // DynIdSyms returns the set of symbols for which dynID is set to an
1492 // interesting (non-default) value. This is expected to be a fairly
1494 func (l *Loader) DynidSyms() []Sym {
1495 sl := make([]Sym, 0, len(l.dynid))
1496 for s := range l.dynid {
1499 sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
1503 // SymGoType returns the 'Gotype' property for a given symbol (set by
1504 // the Go compiler for variable symbols). This version relies on
1505 // reading aux symbols for the target sym -- it could be that a faster
1506 // approach would be to check for gotype during preload and copy the
1507 // results in to a map (might want to try this at some point and see
1508 // if it helps speed things up).
1509 func (l *Loader) SymGoType(i Sym) Sym {
1511 var auxs []goobj.Aux
1512 if l.IsExternal(i) {
1513 pp := l.getPayload(i)
1514 r = l.objs[pp.objidx].r
1518 r, li = l.toLocal(i)
1521 for j := range auxs {
1524 case goobj.AuxGotype:
1525 return l.resolve(r, a.Sym())
1531 // SymUnit returns the compilation unit for a given symbol (which will
1532 // typically be nil for external or linker-manufactured symbols).
1533 func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
1534 if l.IsExternal(i) {
1535 pp := l.getPayload(i)
1537 r := l.objs[pp.objidx].r
1542 r, _ := l.toLocal(i)
1546 // SymPkg returns the package where the symbol came from (for
1547 // regular compiler-generated Go symbols), but in the case of
1548 // building with "-linkshared" (when a symbol is read from a
1549 // shared library), will hold the library name.
1550 // NOTE: this correspondes to sym.Symbol.File field.
1551 func (l *Loader) SymPkg(i Sym) string {
1552 if f, ok := l.symPkg[i]; ok {
1555 if l.IsExternal(i) {
1556 pp := l.getPayload(i)
1558 r := l.objs[pp.objidx].r
1559 return r.unit.Lib.Pkg
1563 r, _ := l.toLocal(i)
1564 return r.unit.Lib.Pkg
1567 // SetSymPkg sets the package/library for a symbol. This is
1568 // needed mainly for external symbols, specifically those imported
1569 // from shared libraries.
1570 func (l *Loader) SetSymPkg(i Sym, pkg string) {
1571 // reject bad symbols
1572 if i >= Sym(len(l.objSyms)) || i == 0 {
1573 panic("bad symbol index in SetSymPkg")
1578 // SymLocalentry returns the "local entry" value for the specified
1580 func (l *Loader) SymLocalentry(i Sym) uint8 {
1581 return l.localentry[i]
1584 // SetSymLocalentry sets the "local entry" attribute for a symbol.
1585 func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
1586 // reject bad symbols
1587 if i >= Sym(len(l.objSyms)) || i == 0 {
1588 panic("bad symbol index in SetSymLocalentry")
1591 delete(l.localentry, i)
1593 l.localentry[i] = value
1597 // Returns the number of aux symbols given a global index.
1598 func (l *Loader) NAux(i Sym) int {
1599 if l.IsExternal(i) {
1602 r, li := l.toLocal(i)
1606 // Returns the "handle" to the j-th aux symbol of the i-th symbol.
1607 func (l *Loader) Aux(i Sym, j int) Aux {
1608 if l.IsExternal(i) {
1611 r, li := l.toLocal(i)
1612 if j >= r.NAux(li) {
1615 return Aux{r.Aux(li, j), r, l}
1618 // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
1619 // symbols associated with a given function symbol. Prior to the
1620 // introduction of the loader, this was done purely using name
1621 // lookups, e.f. for function with name XYZ we would then look up
1622 // go.info.XYZ, etc.
1623 func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
1624 if l.SymType(fnSymIdx) != sym.STEXT {
1625 log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1627 if l.IsExternal(fnSymIdx) {
1628 // Current expectation is that any external function will
1629 // not have auxsyms.
1632 r, li := l.toLocal(fnSymIdx)
1634 for i := range auxs {
1637 case goobj.AuxDwarfInfo:
1638 auxDwarfInfo = l.resolve(r, a.Sym())
1639 if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
1640 panic("aux dwarf info sym with wrong type")
1642 case goobj.AuxDwarfLoc:
1643 auxDwarfLoc = l.resolve(r, a.Sym())
1644 if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
1645 panic("aux dwarf loc sym with wrong type")
1647 case goobj.AuxDwarfRanges:
1648 auxDwarfRanges = l.resolve(r, a.Sym())
1649 if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
1650 panic("aux dwarf ranges sym with wrong type")
1652 case goobj.AuxDwarfLines:
1653 auxDwarfLines = l.resolve(r, a.Sym())
1654 if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
1655 panic("aux dwarf lines sym with wrong type")
1662 // AddInteriorSym sets up 'interior' as an interior symbol of
1663 // container/payload symbol 'container'. An interior symbol does not
1664 // itself have data, but gives a name to a subrange of the data in its
1665 // container symbol. The container itself may or may not have a name.
1666 // This method is intended primarily for use in the host object
1667 // loaders, to capture the semantics of symbols and sections in an
1668 // object file. When reading a host object file, we'll typically
1669 // encounter a static section symbol (ex: ".text") containing content
1670 // for a collection of functions, then a series of ELF (or macho, etc)
1671 // symbol table entries each of which points into a sub-section
1672 // (offset and length) of its corresponding container symbol. Within
1673 // the go linker we create a loader.Sym for the container (which is
1674 // expected to have the actual content/payload) and then a set of
1675 // interior loader.Sym's that point into a portion of the container.
1676 func (l *Loader) AddInteriorSym(container Sym, interior Sym) {
1677 // Container symbols are expected to have content/data.
1678 // NB: this restriction may turn out to be too strict (it's possible
1679 // to imagine a zero-sized container with an interior symbol pointing
1680 // into it); it's ok to relax or remove it if we counter an
1681 // oddball host object that triggers this.
1682 if l.SymSize(container) == 0 && len(l.Data(container)) == 0 {
1683 panic("unexpected empty container symbol")
1685 // The interior symbols for a container are not expected to have
1686 // content/data or relocations.
1687 if len(l.Data(interior)) != 0 {
1688 panic("unexpected non-empty interior symbol")
1690 // Interior symbol is expected to be in the symbol table.
1691 if l.AttrNotInSymbolTable(interior) {
1692 panic("interior symbol must be in symtab")
1694 // Only a single level of containment is allowed.
1695 if l.OuterSym(container) != 0 {
1696 panic("outer has outer itself")
1698 // Interior sym should not already have a sibling.
1699 if l.SubSym(interior) != 0 {
1700 panic("sub set for subsym")
1702 // Interior sym should not already point at a container.
1703 if l.OuterSym(interior) != 0 {
1704 panic("outer already set for subsym")
1706 l.sub[interior] = l.sub[container]
1707 l.sub[container] = interior
1708 l.outer[interior] = container
1711 // OuterSym gets the outer symbol for host object loaded symbols.
1712 func (l *Loader) OuterSym(i Sym) Sym {
1713 // FIXME: add check for isExternal?
1717 // SubSym gets the subsymbol for host object loaded symbols.
1718 func (l *Loader) SubSym(i Sym) Sym {
1719 // NB: note -- no check for l.isExternal(), since I am pretty sure
1720 // that later phases in the linker set subsym for "type." syms
1724 // SetCarrierSym declares that 'c' is the carrier or container symbol
1725 // for 's'. Carrier symbols are used in the linker to as a container
1726 // for a collection of sub-symbols where the content of the
1727 // sub-symbols is effectively concatenated to form the content of the
1728 // carrier. The carrier is given a name in the output symbol table
1729 // while the sub-symbol names are not. For example, the Go compiler
1730 // emits named string symbols (type SGOSTRING) when compiling a
1731 // package; after being deduplicated, these symbols are collected into
1732 // a single unit by assigning them a new carrier symbol named
1733 // "go.string.*" (which appears in the final symbol table for the
1734 // output load module).
1735 func (l *Loader) SetCarrierSym(s Sym, c Sym) {
1737 panic("invalid carrier in SetCarrierSym")
1740 panic("invalid sub-symbol in SetCarrierSym")
1742 // Carrier symbols are not expected to have content/data. It is
1743 // ok for them to have non-zero size (to allow for use of generator
1745 if len(l.Data(c)) != 0 {
1746 panic("unexpected non-empty carrier symbol")
1749 // relocsym's foldSubSymbolOffset requires that we only
1750 // have a single level of containment-- enforce here.
1751 if l.outer[c] != 0 {
1752 panic("invalid nested carrier sym")
1756 // Initialize Reachable bitmap and its siblings for running deadcode pass.
1757 func (l *Loader) InitReachable() {
1758 l.growAttrBitmaps(l.NSym() + 1)
1761 type symWithVal struct {
1765 type bySymValue []symWithVal
1767 func (s bySymValue) Len() int { return len(s) }
1768 func (s bySymValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1769 func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
1771 // SortSub walks through the sub-symbols for 's' and sorts them
1772 // in place by increasing value. Return value is the new
1773 // sub symbol for the specified outer symbol.
1774 func (l *Loader) SortSub(s Sym) Sym {
1776 if s == 0 || l.sub[s] == 0 {
1780 // Sort symbols using a slice first. Use a stable sort on the off
1781 // chance that there's more than once symbol with the same value,
1782 // so as to preserve reproducible builds.
1783 sl := []symWithVal{}
1784 for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
1785 sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
1787 sort.Stable(bySymValue(sl))
1789 // Then apply any changes needed to the sub map.
1791 for i := len(sl) - 1; i >= 0; i-- {
1797 // Update sub for outer symbol, then return
1802 // SortSyms sorts a list of symbols by their value.
1803 func (l *Loader) SortSyms(ss []Sym) {
1804 sort.SliceStable(ss, func(i, j int) bool { return l.SymValue(ss[i]) < l.SymValue(ss[j]) })
1807 // Insure that reachable bitmap and its siblings have enough size.
1808 func (l *Loader) growAttrBitmaps(reqLen int) {
1809 if reqLen > l.attrReachable.Len() {
1810 // These are indexed by global symbol
1811 l.attrReachable = growBitmap(reqLen, l.attrReachable)
1812 l.attrOnList = growBitmap(reqLen, l.attrOnList)
1813 l.attrLocal = growBitmap(reqLen, l.attrLocal)
1814 l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
1815 l.attrUsedInIface = growBitmap(reqLen, l.attrUsedInIface)
1817 l.growExtAttrBitmaps()
1820 func (l *Loader) growExtAttrBitmaps() {
1821 // These are indexed by external symbol index (e.g. l.extIndex(i))
1822 extReqLen := len(l.payloads)
1823 if extReqLen > l.attrVisibilityHidden.Len() {
1824 l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
1825 l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
1826 l.attrShared = growBitmap(extReqLen, l.attrShared)
1827 l.attrExternal = growBitmap(extReqLen, l.attrExternal)
1831 func (relocs *Relocs) Count() int { return len(relocs.rs) }
1833 // At returns the j-th reloc for a global symbol.
1834 func (relocs *Relocs) At(j int) Reloc {
1835 if relocs.l.isExtReader(relocs.r) {
1836 pp := relocs.l.payloads[relocs.li]
1837 return Reloc{&relocs.rs[j], relocs.r, relocs.l, pp.reltypes[j]}
1839 return Reloc{&relocs.rs[j], relocs.r, relocs.l, 0}
1842 // Relocs returns a Relocs object for the given global sym.
1843 func (l *Loader) Relocs(i Sym) Relocs {
1844 r, li := l.toLocal(i)
1846 panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
1848 return l.relocs(r, li)
1851 // Relocs returns a Relocs object given a local sym index and reader.
1852 func (l *Loader) relocs(r *oReader, li uint32) Relocs {
1853 var rs []goobj.Reloc
1854 if l.isExtReader(r) {
1855 pp := l.payloads[li]
1868 // FuncInfo provides hooks to access goobj.FuncInfo in the objects.
1869 type FuncInfo struct {
1874 lengths goobj.FuncInfoLengths
1877 func (fi *FuncInfo) Valid() bool { return fi.r != nil }
1879 func (fi *FuncInfo) Args() int {
1880 return int((*goobj.FuncInfo)(nil).ReadArgs(fi.data))
1883 func (fi *FuncInfo) Locals() int {
1884 return int((*goobj.FuncInfo)(nil).ReadLocals(fi.data))
1887 func (fi *FuncInfo) FuncID() objabi.FuncID {
1888 return (*goobj.FuncInfo)(nil).ReadFuncID(fi.data)
1891 func (fi *FuncInfo) FuncFlag() objabi.FuncFlag {
1892 return (*goobj.FuncInfo)(nil).ReadFuncFlag(fi.data)
1895 func (fi *FuncInfo) Pcsp() Sym {
1896 sym := (*goobj.FuncInfo)(nil).ReadPcsp(fi.data)
1897 return fi.l.resolve(fi.r, sym)
1900 func (fi *FuncInfo) Pcfile() Sym {
1901 sym := (*goobj.FuncInfo)(nil).ReadPcfile(fi.data)
1902 return fi.l.resolve(fi.r, sym)
1905 func (fi *FuncInfo) Pcline() Sym {
1906 sym := (*goobj.FuncInfo)(nil).ReadPcline(fi.data)
1907 return fi.l.resolve(fi.r, sym)
1910 func (fi *FuncInfo) Pcinline() Sym {
1911 sym := (*goobj.FuncInfo)(nil).ReadPcinline(fi.data)
1912 return fi.l.resolve(fi.r, sym)
1915 // Preload has to be called prior to invoking the various methods
1916 // below related to pcdata, funcdataoff, files, and inltree nodes.
1917 func (fi *FuncInfo) Preload() {
1918 fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
1921 func (fi *FuncInfo) Pcdata() []Sym {
1922 if !fi.lengths.Initialized {
1923 panic("need to call Preload first")
1925 syms := (*goobj.FuncInfo)(nil).ReadPcdata(fi.data)
1926 ret := make([]Sym, len(syms))
1927 for i := range ret {
1928 ret[i] = fi.l.resolve(fi.r, syms[i])
1933 func (fi *FuncInfo) NumFuncdataoff() uint32 {
1934 if !fi.lengths.Initialized {
1935 panic("need to call Preload first")
1937 return fi.lengths.NumFuncdataoff
1940 func (fi *FuncInfo) Funcdataoff(k int) int64 {
1941 if !fi.lengths.Initialized {
1942 panic("need to call Preload first")
1944 return (*goobj.FuncInfo)(nil).ReadFuncdataoff(fi.data, fi.lengths.FuncdataoffOff, uint32(k))
1947 func (fi *FuncInfo) Funcdata(syms []Sym) []Sym {
1948 if !fi.lengths.Initialized {
1949 panic("need to call Preload first")
1951 if int(fi.lengths.NumFuncdataoff) > cap(syms) {
1952 syms = make([]Sym, 0, fi.lengths.NumFuncdataoff)
1956 for j := range fi.auxs {
1958 if a.Type() == goobj.AuxFuncdata {
1959 syms = append(syms, fi.l.resolve(fi.r, a.Sym()))
1965 func (fi *FuncInfo) NumFile() uint32 {
1966 if !fi.lengths.Initialized {
1967 panic("need to call Preload first")
1969 return fi.lengths.NumFile
1972 func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
1973 if !fi.lengths.Initialized {
1974 panic("need to call Preload first")
1976 return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
1979 // TopFrame returns true if the function associated with this FuncInfo
1980 // is an entry point, meaning that unwinders should stop when they hit
1982 func (fi *FuncInfo) TopFrame() bool {
1983 return (fi.FuncFlag() & objabi.FuncFlag_TOPFRAME) != 0
1986 type InlTreeNode struct {
1988 File goobj.CUFileIndex
1994 func (fi *FuncInfo) NumInlTree() uint32 {
1995 if !fi.lengths.Initialized {
1996 panic("need to call Preload first")
1998 return fi.lengths.NumInlTree
2001 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
2002 if !fi.lengths.Initialized {
2003 panic("need to call Preload first")
2005 node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
2007 Parent: node.Parent,
2010 Func: fi.l.resolve(fi.r, node.Func),
2011 ParentPC: node.ParentPC,
2015 func (l *Loader) FuncInfo(i Sym) FuncInfo {
2017 var auxs []goobj.Aux
2018 if l.IsExternal(i) {
2019 pp := l.getPayload(i)
2023 r = l.objs[pp.objidx].r
2027 r, li = l.toLocal(i)
2030 for j := range auxs {
2032 if a.Type() == goobj.AuxFuncInfo {
2033 b := r.Data(a.Sym().SymIdx)
2034 return FuncInfo{l, r, b, auxs, goobj.FuncInfoLengths{}}
2040 // Preload a package: adds autolib.
2041 // Does not add defined package or non-packaged symbols to the symbol table.
2042 // These are done in LoadSyms.
2043 // Does not read symbol data.
2044 // Returns the fingerprint of the object.
2045 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
2046 roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
2048 log.Fatal("cannot read object file:", err)
2050 r := goobj.NewReaderFromBytes(roObject, readonly)
2052 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
2053 log.Fatalf("found object file %s in old format", f.File().Name())
2055 panic("cannot read object file")
2057 pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
2059 nhashed64def := r.NHashed64def()
2060 nhasheddef := r.NHasheddef()
2064 version: localSymVersion,
2066 pkgprefix: pkgprefix,
2067 syms: make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
2069 nhasheddef: nhasheddef,
2070 nhashed64def: nhashed64def,
2071 objidx: uint32(len(l.objs)),
2075 lib.Autolib = append(lib.Autolib, r.Autolib()...)
2079 unit.FileTable = make([]string, nfile)
2080 for i := range unit.FileTable {
2081 unit.FileTable[i] = r.File(i)
2084 l.addObj(lib.Pkg, or)
2086 // The caller expects us consuming all the data
2087 f.MustSeek(length, os.SEEK_CUR)
2089 return r.Fingerprint()
2092 // Holds the loader along with temporary states for loading symbols.
2093 type loadState struct {
2095 hashed64Syms map[uint64]symAndSize // short hashed (content-addressable) symbols, keyed by content hash
2096 hashedSyms map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
2099 // Preload symbols of given kind from an object.
2100 func (st *loadState) preloadSyms(r *oReader, kind int) {
2102 var start, end uint32
2106 end = uint32(r.ndef)
2108 start = uint32(r.ndef)
2109 end = uint32(r.ndef + r.nhashed64def)
2111 start = uint32(r.ndef + r.nhashed64def)
2112 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2113 if l.hasUnknownPkgPath {
2114 // The content hash depends on symbol name expansion. If any package is
2115 // built without fully expanded names, the content hash is unreliable.
2116 // Treat them as named symbols.
2118 // (We don't need to do this for hashed64Def case, as there the hash
2119 // function is simply the identity function, which doesn't depend on
2124 start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2125 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
2127 panic("preloadSyms: bad kind")
2129 l.growAttrBitmaps(len(l.objSyms) + int(end-start))
2130 needNameExpansion := r.NeedNameExpansion()
2131 loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
2132 for i := start; i < end; i++ {
2136 if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
2137 name = osym.Name(r.Reader)
2138 if needNameExpansion {
2139 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2141 v = abiToVer(osym.ABI(), r.version)
2143 gi := st.addSym(name, v, r, i, kind, osym)
2146 l.SetAttrLocal(gi, true)
2148 if osym.UsedInIface() {
2149 l.SetAttrUsedInIface(gi, true)
2151 if strings.HasPrefix(name, "runtime.") ||
2152 (loadingRuntimePkg && strings.HasPrefix(name, "type.")) {
2153 if bi := goobj.BuiltinIdx(name, v); bi != -1 {
2154 // This is a definition of a builtin symbol. Record where it is.
2155 l.builtinSyms[bi] = gi
2158 if a := int32(osym.Align()); a != 0 && a > l.SymAlign(gi) {
2159 l.SetSymAlign(gi, a)
2164 // Add syms, hashed (content-addressable) symbols, non-package symbols, and
2165 // references to external symbols (which are always named).
2166 func (l *Loader) LoadSyms(arch *sys.Arch) {
2167 // Allocate space for symbols, making a guess as to how much space we need.
2168 // This function was determined empirically by looking at the cmd/compile on
2169 // Darwin, and picking factors for hashed and hashed64 syms.
2170 var symSize, hashedSize, hashed64Size int
2171 for _, o := range l.objs[goObjStart:] {
2172 symSize += o.r.ndef + o.r.nhasheddef/2 + o.r.nhashed64def/2 + o.r.NNonpkgdef()
2173 hashedSize += o.r.nhasheddef / 2
2174 hashed64Size += o.r.nhashed64def / 2
2176 // Index 0 is invalid for symbols.
2177 l.objSyms = make([]objSym, 1, symSize)
2179 l.npkgsyms = l.NSym()
2182 hashed64Syms: make(map[uint64]symAndSize, hashed64Size),
2183 hashedSyms: make(map[goobj.HashType]symAndSize, hashedSize),
2186 for _, o := range l.objs[goObjStart:] {
2187 st.preloadSyms(o.r, pkgDef)
2189 for _, o := range l.objs[goObjStart:] {
2190 st.preloadSyms(o.r, hashed64Def)
2191 st.preloadSyms(o.r, hashedDef)
2192 st.preloadSyms(o.r, nonPkgDef)
2194 l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
2195 for _, o := range l.objs[goObjStart:] {
2196 loadObjRefs(l, o.r, arch)
2198 l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2201 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2202 // load non-package refs
2203 ndef := uint32(r.NAlldef())
2204 needNameExpansion := r.NeedNameExpansion()
2205 for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2206 osym := r.Sym(ndef + i)
2207 name := osym.Name(r.Reader)
2208 if needNameExpansion {
2209 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2211 v := abiToVer(osym.ABI(), r.version)
2212 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2213 gi := r.syms[ndef+i]
2215 l.SetAttrLocal(gi, true)
2217 if osym.UsedInIface() {
2218 l.SetAttrUsedInIface(gi, true)
2222 // referenced packages
2224 r.pkg = make([]uint32, npkg)
2225 for i := 1; i < npkg; i++ { // PkgIdx 0 is a dummy invalid package
2227 objidx, ok := l.objByPkg[pkg]
2229 log.Fatalf("reference of nonexisted package %s, from %v", pkg, r.unit.Lib)
2234 // load flags of package refs
2235 for i, n := 0, r.NRefFlags(); i < n; i++ {
2237 gi := l.resolve(r, rf.Sym())
2238 if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
2239 l.SetAttrUsedInIface(gi, true)
2244 func abiToVer(abi uint16, localSymVersion int) int {
2246 if abi == goobj.SymABIstatic {
2249 } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2250 // Note that data symbols are "ABI0", which maps to version 0.
2253 log.Fatalf("invalid symbol ABI: %d", abi)
2258 // ResolveABIAlias given a symbol returns the ABI alias target of that
2259 // symbol. If the sym in question is not an alias, the sym itself is
2261 func (l *Loader) ResolveABIAlias(s Sym) Sym {
2262 if l.flags&FlagUseABIAlias == 0 {
2268 if l.SymType(s) != sym.SABIALIAS {
2271 relocs := l.Relocs(s)
2272 target := relocs.At(0).Sym()
2273 if l.SymType(target) == sym.SABIALIAS {
2274 panic(fmt.Sprintf("ABI alias %s references another ABI alias %s", l.SymName(s), l.SymName(target)))
2279 // TopLevelSym tests a symbol (by name and kind) to determine whether
2280 // the symbol first class sym (participating in the link) or is an
2281 // anonymous aux or sub-symbol containing some sub-part or payload of
2283 func (l *Loader) TopLevelSym(s Sym) bool {
2284 return topLevelSym(l.RawSymName(s), l.SymType(s))
2287 // topLevelSym tests a symbol name and kind to determine whether
2288 // the symbol first class sym (participating in the link) or is an
2289 // anonymous aux or sub-symbol containing some sub-part or payload of
2291 func topLevelSym(sname string, skind sym.SymKind) bool {
2296 case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2303 // cloneToExternal takes the existing object file symbol (symIdx)
2304 // and creates a new external symbol payload that is a clone with
2305 // respect to name, version, type, relocations, etc. The idea here
2306 // is that if the linker decides it wants to update the contents of
2307 // a symbol originally discovered as part of an object file, it's
2308 // easier to do this if we make the updates to an external symbol
2310 func (l *Loader) cloneToExternal(symIdx Sym) {
2311 if l.IsExternal(symIdx) {
2312 panic("sym is already external, no need for clone")
2315 // Read the particulars from object.
2316 r, li := l.toLocal(symIdx)
2318 sname := osym.Name(r.Reader)
2319 if r.NeedNameExpansion() {
2320 sname = strings.Replace(sname, "\"\".", r.pkgprefix, -1)
2322 sver := abiToVer(osym.ABI(), r.version)
2323 skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2325 // Create new symbol, update version and kind.
2326 pi := l.newPayload(sname, sver)
2327 pp := l.payloads[pi]
2330 pp.size = int64(osym.Siz())
2331 pp.objidx = r.objidx
2333 // If this is a def, then copy the guts. We expect this case
2334 // to be very rare (one case it may come up is with -X).
2335 if li < uint32(r.NAlldef()) {
2338 relocs := l.Relocs(symIdx)
2339 pp.relocs = make([]goobj.Reloc, relocs.Count())
2340 pp.reltypes = make([]objabi.RelocType, relocs.Count())
2341 for i := range pp.relocs {
2342 // Copy the relocs slice.
2343 // Convert local reference to global reference.
2345 pp.relocs[i].Set(rel.Off(), rel.Siz(), 0, rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2346 pp.reltypes[i] = rel.Type()
2350 pp.data = r.Data(li)
2353 // If we're overriding a data symbol, collect the associated
2354 // Gotype, so as to propagate it to the new symbol.
2358 // Install new payload to global index space.
2359 // (This needs to happen at the end, as the accessors above
2360 // need to access the old symbol content.)
2361 l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2362 l.extReader.syms = append(l.extReader.syms, symIdx)
2365 // Copy the payload of symbol src to dst. Both src and dst must be external
2367 // The intended use case is that when building/linking against a shared library,
2368 // where we do symbol name mangling, the Go object file may have reference to
2369 // the original symbol name whereas the shared library provides a symbol with
2370 // the mangled name. When we do mangling, we copy payload of mangled to original.
2371 func (l *Loader) CopySym(src, dst Sym) {
2372 if !l.IsExternal(dst) {
2373 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2375 if !l.IsExternal(src) {
2376 panic("src is not external") //l.cloneToExternal(src)
2378 l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2379 l.SetSymPkg(dst, l.SymPkg(src))
2380 // TODO: other attributes?
2383 // CopyAttributes copies over all of the attributes of symbol 'src' to
2385 func (l *Loader) CopyAttributes(src Sym, dst Sym) {
2386 l.SetAttrReachable(dst, l.AttrReachable(src))
2387 l.SetAttrOnList(dst, l.AttrOnList(src))
2388 l.SetAttrLocal(dst, l.AttrLocal(src))
2389 l.SetAttrNotInSymbolTable(dst, l.AttrNotInSymbolTable(src))
2390 if l.IsExternal(dst) {
2391 l.SetAttrVisibilityHidden(dst, l.AttrVisibilityHidden(src))
2392 l.SetAttrDuplicateOK(dst, l.AttrDuplicateOK(src))
2393 l.SetAttrShared(dst, l.AttrShared(src))
2394 l.SetAttrExternal(dst, l.AttrExternal(src))
2396 // Some attributes are modifiable only for external symbols.
2397 // In such cases, don't try to transfer over the attribute
2398 // from the source even if there is a clash. This comes up
2399 // when copying attributes from a dupOK ABI wrapper symbol to
2400 // the real target symbol (which may not be marked dupOK).
2402 l.SetAttrSpecial(dst, l.AttrSpecial(src))
2403 l.SetAttrCgoExportDynamic(dst, l.AttrCgoExportDynamic(src))
2404 l.SetAttrCgoExportStatic(dst, l.AttrCgoExportStatic(src))
2405 l.SetAttrReadOnly(dst, l.AttrReadOnly(src))
2408 // CreateExtSym creates a new external symbol with the specified name
2409 // without adding it to any lookup tables, returning a Sym index for it.
2410 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2411 return l.newExtSym(name, ver)
2414 // CreateStaticSym creates a new static symbol with the specified name
2415 // without adding it to any lookup tables, returning a Sym index for it.
2416 func (l *Loader) CreateStaticSym(name string) Sym {
2417 // Assign a new unique negative version -- this is to mark the
2418 // symbol so that it is not included in the name lookup table.
2420 return l.newExtSym(name, l.anonVersion)
2423 func (l *Loader) FreeSym(i Sym) {
2424 if l.IsExternal(i) {
2425 pp := l.getPayload(i)
2426 *pp = extSymPayload{}
2430 // relocId is essentially a <S,R> tuple identifying the Rth
2431 // relocation of symbol S.
2432 type relocId struct {
2437 // SetRelocVariant sets the 'variant' property of a relocation on
2438 // some specific symbol.
2439 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2441 if relocs := l.Relocs(s); ri >= relocs.Count() {
2442 panic("invalid relocation ID")
2444 if l.relocVariant == nil {
2445 l.relocVariant = make(map[relocId]sym.RelocVariant)
2448 l.relocVariant[relocId{s, ri}] = v
2450 delete(l.relocVariant, relocId{s, ri})
2454 // RelocVariant returns the 'variant' property of a relocation on
2455 // some specific symbol.
2456 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2457 return l.relocVariant[relocId{s, ri}]
2460 // UndefinedRelocTargets iterates through the global symbol index
2461 // space, looking for symbols with relocations targeting undefined
2462 // references. The linker's loadlib method uses this to determine if
2463 // there are unresolved references to functions in system libraries
2464 // (for example, libgcc.a), presumably due to CGO code. Return
2465 // value is a list of loader.Sym's corresponding to the undefined
2466 // cross-refs. The "limit" param controls the maximum number of
2467 // results returned; if "limit" is -1, then all undefs are returned.
2468 func (l *Loader) UndefinedRelocTargets(limit int) []Sym {
2470 for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2471 relocs := l.Relocs(si)
2472 for ri := 0; ri < relocs.Count(); ri++ {
2475 if rs != 0 && l.SymType(rs) == sym.SXREF && l.RawSymName(rs) != ".got" {
2476 result = append(result, rs)
2477 if limit != -1 && len(result) >= limit {
2486 // AssignTextSymbolOrder populates the Textp slices within each
2487 // library and compilation unit, insuring that packages are laid down
2488 // in dependency order (internal first, then everything else). Return value
2489 // is a slice of all text syms.
2490 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2492 // Library Textp lists should be empty at this point.
2493 for _, lib := range libs {
2494 if len(lib.Textp) != 0 {
2495 panic("expected empty Textp slice for library")
2497 if len(lib.DupTextSyms) != 0 {
2498 panic("expected empty DupTextSyms slice for library")
2502 // Used to record which dupok symbol we've assigned to a unit.
2503 // Can't use the onlist attribute here because it will need to
2504 // clear for the later assignment of the sym.Symbol to a unit.
2505 // NB: we can convert to using onList once we no longer have to
2506 // call the regular addToTextp.
2507 assignedToUnit := MakeBitmap(l.NSym() + 1)
2509 // Start off textp with reachable external syms.
2511 for _, sym := range extsyms {
2512 if !l.attrReachable.Has(sym) {
2515 textp = append(textp, sym)
2518 // Walk through all text symbols from Go object files and append
2519 // them to their corresponding library's textp list.
2520 for _, o := range l.objs[goObjStart:] {
2523 for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
2524 gi := l.toGlobal(r, i)
2525 if !l.attrReachable.Has(gi) {
2529 st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2530 if st != sym.STEXT {
2533 dupok := osym.Dupok()
2534 if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2535 // A dupok text symbol is resolved to another package.
2536 // We still need to record its presence in the current
2537 // package, as the trampoline pass expects packages
2538 // are laid out in dependency order.
2539 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2540 continue // symbol in different object
2543 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2547 lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2551 // Now assemble global textp, and assign text symbols to units.
2552 for _, doInternal := range [2]bool{true, false} {
2553 for idx, lib := range libs {
2554 if intlibs[idx] != doInternal {
2557 lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2558 for i, list := range lists {
2559 for _, s := range list {
2561 if l.attrReachable.Has(sym) && !assignedToUnit.Has(sym) {
2562 textp = append(textp, sym)
2563 unit := l.SymUnit(sym)
2565 unit.Textp = append(unit.Textp, s)
2566 assignedToUnit.Set(sym)
2568 // Dupok symbols may be defined in multiple packages; the
2569 // associated package for a dupok sym is chosen sort of
2570 // arbitrarily (the first containing package that the linker
2571 // loads). Canonicalizes its Pkg to the package with which
2572 // it will be laid down in text.
2573 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2574 l.SetSymPkg(sym, lib.Pkg)
2580 lib.DupTextSyms = nil
2587 // ErrorReporter is a helper class for reporting errors.
2588 type ErrorReporter struct {
2590 AfterErrorAction func()
2593 // Errorf method logs an error message.
2595 // After each error, the error actions function will be invoked; this
2596 // will either terminate the link immediately (if -h option given)
2597 // or it will keep a count and exit if more than 20 errors have been printed.
2599 // Logging an error means that on exit cmd/link will delete any
2600 // output file and return a non-zero error code.
2602 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2603 if s != 0 && reporter.ldr.SymName(s) != "" {
2604 format = reporter.ldr.SymName(s) + ": " + format
2606 format = fmt.Sprintf("sym %d: %s", s, format)
2609 fmt.Fprintf(os.Stderr, format, args...)
2610 reporter.AfterErrorAction()
2613 // GetErrorReporter returns the loader's associated error reporter.
2614 func (l *Loader) GetErrorReporter() *ErrorReporter {
2615 return l.errorReporter
2618 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2619 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2620 l.errorReporter.Errorf(s, format, args...)
2623 // Symbol statistics.
2624 func (l *Loader) Stat() string {
2625 s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
2626 s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
2627 l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
2632 func (l *Loader) Dump() {
2634 for _, obj := range l.objs[goObjStart:] {
2636 fmt.Println(obj.i, obj.r.unit.Lib)
2639 fmt.Println("extStart:", l.extStart)
2640 fmt.Println("Nsyms:", len(l.objSyms))
2642 for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2644 if l.IsExternal(i) {
2645 pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2648 if l.SymSect(i) != nil {
2649 sect = l.SymSect(i).Name
2651 fmt.Printf("%v %v %v %v %x %v\n", i, l.SymName(i), l.SymType(i), pi, l.SymValue(i), sect)
2653 fmt.Println("symsByName")
2654 for name, i := range l.symsByName[0] {
2655 fmt.Println(i, name, 0)
2657 for name, i := range l.symsByName[1] {
2658 fmt.Println(i, name, 1)
2660 fmt.Println("payloads:")
2661 for i := range l.payloads {
2663 fmt.Println(i, pp.name, pp.ver, pp.kind)