1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 "cmd/link/internal/sym"
26 // Sym encapsulates a global symbol index, used to identify a specific
27 // Go symbol. The 0-valued Sym is corresponds to an invalid symbol.
30 // Relocs encapsulates the set of relocations on a given symbol; an
31 // instance of this type is returned by the Loader Relocs() method.
35 li uint32 // local index of symbol whose relocs we're examining
36 r *oReader // object reader for containing package
40 // ExtReloc contains the payload for an external relocation.
41 type ExtReloc struct {
48 // Reloc holds a "handle" to access a relocation record from an
55 // External reloc types may not fit into a uint8 which the Go object file uses.
56 // Store it here, instead of in the byte of goobj.Reloc.
57 // For Go symbols this will always be zero.
58 // goobj.Reloc.Type() + typ is always the right type, for both Go and external
63 func (rel Reloc) Type() objabi.RelocType { return objabi.RelocType(rel.Reloc.Type()) + rel.typ }
64 func (rel Reloc) Sym() Sym { return rel.l.resolve(rel.r, rel.Reloc.Sym()) }
65 func (rel Reloc) SetSym(s Sym) { rel.Reloc.SetSym(goobj.SymRef{PkgIdx: 0, SymIdx: uint32(s)}) }
66 func (rel Reloc) IsMarker() bool { return rel.Siz() == 0 }
68 func (rel Reloc) SetType(t objabi.RelocType) {
69 if t != objabi.RelocType(uint8(t)) {
70 panic("SetType: type doesn't fit into Reloc")
72 rel.Reloc.SetType(uint8(t))
74 // should use SymbolBuilder.SetRelocType
75 panic("wrong method to set reloc type")
79 // Aux holds a "handle" to access an aux symbol record from an
87 func (a Aux) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
89 // oReader is a wrapper type of obj.Reader, along with some
93 unit *sym.CompilationUnit
94 version int // version of static symbol
95 flags uint32 // read from object file
97 syms []Sym // Sym's global index, indexed by local index
98 pkg []uint32 // indices of referenced package by PkgIdx (index into loader.objs array)
99 ndef int // cache goobj.Reader.NSym()
100 nhashed64def int // cache goobj.Reader.NHashed64Def()
101 nhasheddef int // cache goobj.Reader.NHashedDef()
102 objidx uint32 // index of this reader in the objs slice
105 // Total number of defined symbols (package symbols, hashed symbols, and
106 // non-package symbols).
107 func (r *oReader) NAlldef() int { return r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef() }
114 // objSym represents a symbol in an object file. It is a tuple of
115 // the object and the symbol's local index.
116 // For external symbols, objidx is the index of l.extReader (extObj),
117 // s is its index into the payload array.
118 // {0, 0} represents the nil symbol.
120 objidx uint32 // index of the object (in l.objs array)
121 s uint32 // local index
124 type nameVer struct {
132 func (bm Bitmap) Set(i Sym) {
133 n, r := uint(i)/32, uint(i)%32
137 // unset the i-th bit.
138 func (bm Bitmap) Unset(i Sym) {
139 n, r := uint(i)/32, uint(i)%32
143 // whether the i-th bit is set.
144 func (bm Bitmap) Has(i Sym) bool {
145 n, r := uint(i)/32, uint(i)%32
146 return bm[n]&(1<<r) != 0
149 // return current length of bitmap in bits.
150 func (bm Bitmap) Len() int {
154 // return the number of bits set.
155 func (bm Bitmap) Count() int {
157 for _, x := range bm {
158 s += bits.OnesCount32(x)
163 func MakeBitmap(n int) Bitmap {
164 return make(Bitmap, (n+31)/32)
167 // growBitmap insures that the specified bitmap has enough capacity,
168 // reallocating (doubling the size) if needed.
169 func growBitmap(reqLen int, b Bitmap) Bitmap {
172 b = append(b, MakeBitmap(reqLen+1-curLen)...)
177 type symAndSize struct {
182 // A Loader loads new object files and resolves indexed symbol references.
184 // Notes on the layout of global symbol index space:
186 // - Go object files are read before host object files; each Go object
187 // read adds its defined package symbols to the global index space.
188 // Nonpackage symbols are not yet added.
190 // - In loader.LoadNonpkgSyms, add non-package defined symbols and
191 // references in all object files to the global index space.
193 // - Host object file loading happens; the host object loader does a
194 // name/version lookup for each symbol it finds; this can wind up
195 // extending the external symbol index space range. The host object
196 // loader stores symbol payloads in loader.payloads using SymbolBuilder.
198 // - Each symbol gets a unique global index. For duplicated and
199 // overwriting/overwritten symbols, the second (or later) appearance
200 // of the symbol gets the same global index as the first appearance.
202 start map[*oReader]Sym // map from object file to its start index
203 objs []objIdx // sorted by start index (i.e. objIdx.i)
204 extStart Sym // from this index on, the symbols are externally defined
205 builtinSyms []Sym // global index of builtin symbols
207 objSyms []objSym // global index mapping to local index
209 symsByName [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
210 extStaticSyms map[nameVer]Sym // externally defined static symbols, keyed by name
212 extReader *oReader // a dummy oReader, for external symbols
213 payloadBatch []extSymPayload
214 payloads []*extSymPayload // contents of linker-materialized external syms
215 values []int64 // symbol values, indexed by global sym index
217 sects []*sym.Section // sections
218 symSects []uint16 // symbol's section, index to sects array
220 align []uint8 // symbol 2^N alignment, indexed by global index
222 deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
224 objByPkg map[string]uint32 // map package path to the index of its Go object reader
226 anonVersion int // most recently assigned ext static sym pseudo-version
228 // Bitmaps and other side structures used to store data used to store
229 // symbol flags/attributes; these are to be accessed via the
230 // corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
231 // visit the comments on these methods for more details on the
232 // semantics / interpretation of the specific flags or attribute.
233 attrReachable Bitmap // reachable symbols, indexed by global index
234 attrOnList Bitmap // "on list" symbols, indexed by global index
235 attrLocal Bitmap // "local" symbols, indexed by global index
236 attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by global idx
237 attrUsedInIface Bitmap // "used in interface" symbols, indexed by global idx
238 attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
239 attrDuplicateOK Bitmap // dupOK symbols, indexed by ext sym index
240 attrShared Bitmap // shared symbols, indexed by ext sym index
241 attrExternal Bitmap // external symbols, indexed by ext sym index
243 attrReadOnly map[Sym]bool // readonly data for this sym
244 attrTopFrame map[Sym]struct{} // top frame symbols
245 attrSpecial map[Sym]struct{} // "special" frame symbols
246 attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
247 attrCgoExportStatic map[Sym]struct{} // "cgo_export_static" symbols
248 generatedSyms map[Sym]struct{} // symbols that generate their content
250 // Outer and Sub relations for symbols.
251 // TODO: figure out whether it's more efficient to just have these
252 // as fields on extSymPayload (note that this won't be a viable
253 // strategy if somewhere in the linker we set sub/outer for a
254 // non-external sym).
258 dynimplib map[Sym]string // stores Dynimplib symbol attribute
259 dynimpvers map[Sym]string // stores Dynimpvers symbol attribute
260 localentry map[Sym]uint8 // stores Localentry symbol attribute
261 extname map[Sym]string // stores Extname symbol attribute
262 elfType map[Sym]elf.SymType // stores elf type symbol property
263 elfSym map[Sym]int32 // stores elf sym symbol property
264 localElfSym map[Sym]int32 // stores "local" elf sym symbol property
265 symPkg map[Sym]string // stores package for symbol, or library for shlib-derived syms
266 plt map[Sym]int32 // stores dynimport for pe objects
267 got map[Sym]int32 // stores got for pe objects
268 dynid map[Sym]int32 // stores Dynid for symbol
270 relocVariant map[relocId]sym.RelocVariant // stores variant relocs
272 // Used to implement field tracking; created during deadcode if
273 // field tracking is enabled. Reachparent[K] contains the index of
274 // the symbol that triggered the marking of symbol K as live.
279 hasUnknownPkgPath bool // if any Go object has unknown package path
281 strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
283 elfsetstring elfsetstringFunc
285 errorReporter *ErrorReporter
287 npkgsyms int // number of package symbols, for accounting
288 nhashedsyms int // number of hashed symbols, for accounting
306 type elfsetstringFunc func(str string, off int)
308 // extSymPayload holds the payload (data + relocations) for linker-synthesized
309 // external symbols (note that symbol value is stored in a separate slice).
310 type extSymPayload struct {
311 name string // TODO: would this be better as offset into str table?
315 objidx uint32 // index of original object if sym made by cloneToExternal
317 reltypes []objabi.RelocType // relocation types
324 FlagStrictDups = 1 << iota
328 func NewLoader(flags uint32, elfsetstring elfsetstringFunc, reporter *ErrorReporter) *Loader {
329 nbuiltin := goobj.NBuiltin()
330 extReader := &oReader{objidx: extObj}
332 start: make(map[*oReader]Sym),
333 objs: []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
334 objSyms: make([]objSym, 1, 1), // This will get overwritten later.
335 extReader: extReader,
336 symsByName: [2]map[string]Sym{make(map[string]Sym, 80000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
337 objByPkg: make(map[string]uint32),
338 outer: make(map[Sym]Sym),
339 sub: make(map[Sym]Sym),
340 dynimplib: make(map[Sym]string),
341 dynimpvers: make(map[Sym]string),
342 localentry: make(map[Sym]uint8),
343 extname: make(map[Sym]string),
344 attrReadOnly: make(map[Sym]bool),
345 elfType: make(map[Sym]elf.SymType),
346 elfSym: make(map[Sym]int32),
347 localElfSym: make(map[Sym]int32),
348 symPkg: make(map[Sym]string),
349 plt: make(map[Sym]int32),
350 got: make(map[Sym]int32),
351 dynid: make(map[Sym]int32),
352 attrTopFrame: make(map[Sym]struct{}),
353 attrSpecial: make(map[Sym]struct{}),
354 attrCgoExportDynamic: make(map[Sym]struct{}),
355 attrCgoExportStatic: make(map[Sym]struct{}),
356 generatedSyms: make(map[Sym]struct{}),
357 deferReturnTramp: make(map[Sym]bool),
358 extStaticSyms: make(map[nameVer]Sym),
359 builtinSyms: make([]Sym, nbuiltin),
361 elfsetstring: elfsetstring,
362 errorReporter: reporter,
363 sects: []*sym.Section{nil}, // reserve index 0 for nil section
369 // Add object file r, return the start index.
370 func (l *Loader) addObj(pkg string, r *oReader) Sym {
371 if _, ok := l.start[r]; ok {
372 panic("already added")
374 pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
375 if _, ok := l.objByPkg[pkg]; !ok {
376 l.objByPkg[pkg] = r.objidx
378 i := Sym(len(l.objSyms))
380 l.objs = append(l.objs, objIdx{r, i})
381 if r.NeedNameExpansion() && !r.FromAssembly() {
382 l.hasUnknownPkgPath = true
387 // Add a symbol from an object file, return the global index.
388 // If the symbol already exist, it returns the index of that symbol.
389 func (st *loadState) addSym(name string, ver int, r *oReader, li uint32, kind int, osym *goobj.Sym) Sym {
392 panic("addSym called after external symbol is created")
394 i := Sym(len(l.objSyms))
395 addToGlobal := func() {
396 l.objSyms = append(l.objSyms, objSym{r.objidx, li})
398 if name == "" && kind != hashed64Def && kind != hashedDef {
400 return i // unnamed aux symbol
402 if ver == r.version {
403 // Static symbol. Add its global index but don't
404 // add to name lookup table, as it cannot be
405 // referenced by name.
411 // Defined package symbols cannot be dup to each other.
412 // We load all the package symbols first, so we don't need
413 // to check dup here.
414 // We still add it to the lookup table, as it may still be
415 // referenced by name (e.g. through linkname).
416 l.symsByName[ver][name] = i
419 case hashed64Def, hashedDef:
420 // Hashed (content-addressable) symbol. Check the hash
421 // but don't add to name lookup table, as they are not
422 // referenced by name. Also no need to do overwriting
423 // check, as same hash indicates same content.
424 var checkHash func() (symAndSize, bool)
425 var addToHashMap func(symAndSize)
426 var h64 uint64 // only used for hashed64Def
427 var h *goobj.HashType // only used for hashedDef
428 if kind == hashed64Def {
429 checkHash = func() (symAndSize, bool) {
430 h64 = r.Hash64(li - uint32(r.ndef))
431 s, existed := st.hashed64Syms[h64]
434 addToHashMap = func(ss symAndSize) { st.hashed64Syms[h64] = ss }
436 checkHash = func() (symAndSize, bool) {
437 h = r.Hash(li - uint32(r.ndef+r.nhashed64def))
438 s, existed := st.hashedSyms[*h]
441 addToHashMap = func(ss symAndSize) { st.hashedSyms[*h] = ss }
444 if s, existed := checkHash(); existed {
445 // The content hash is built from symbol data and relocations. In the
446 // object file, the symbol data may not always contain trailing zeros,
447 // e.g. for [5]int{1,2,3} and [100]int{1,2,3}, the data is same
448 // (although the size is different).
449 // Also, for short symbols, the content hash is the identity function of
450 // the 8 bytes, and trailing zeros doesn't change the hash value, e.g.
451 // hash("A") == hash("A\0\0\0").
452 // So when two symbols have the same hash, we need to use the one with
455 // New symbol has larger size, use the new one. Rewrite the index mapping.
456 l.objSyms[s.sym] = objSym{r.objidx, li}
457 addToHashMap(symAndSize{s.sym, siz})
461 addToHashMap(symAndSize{i, siz})
466 // Non-package (named) symbol. Check if it already exists.
467 oldi, existed := l.symsByName[ver][name]
469 l.symsByName[ver][name] = i
473 // symbol already exists
475 if l.flags&FlagStrictDups != 0 {
476 l.checkdup(name, r, li, oldi)
480 oldr, oldli := l.toLocal(oldi)
481 oldsym := oldr.Sym(oldli)
485 overwrite := r.DataSize(li) != 0
487 // new symbol overwrites old symbol.
488 oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
489 if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
490 log.Fatalf("duplicated definition of symbol " + name)
492 l.objSyms[oldi] = objSym{r.objidx, li}
494 // old symbol overwrites new symbol.
495 typ := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
496 if !typ.IsData() { // only allow overwriting data symbol
497 log.Fatalf("duplicated definition of symbol " + name)
503 // newExtSym creates a new external sym with the specified
505 func (l *Loader) newExtSym(name string, ver int) Sym {
506 i := Sym(len(l.objSyms))
510 l.growValues(int(i) + 1)
511 l.growAttrBitmaps(int(i) + 1)
512 pi := l.newPayload(name, ver)
513 l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
514 l.extReader.syms = append(l.extReader.syms, i)
518 // LookupOrCreateSym looks up the symbol with the specified name/version,
519 // returning its Sym index if found. If the lookup fails, a new external
520 // Sym will be created, entered into the lookup tables, and returned.
521 func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
522 i := l.Lookup(name, ver)
526 i = l.newExtSym(name, ver)
527 static := ver >= sym.SymVerStatic || ver < 0
529 l.extStaticSyms[nameVer{name, ver}] = i
531 l.symsByName[ver][name] = i
536 func (l *Loader) IsExternal(i Sym) bool {
538 return l.isExtReader(r)
541 func (l *Loader) isExtReader(r *oReader) bool {
542 return r == l.extReader
545 // For external symbol, return its index in the payloads array.
546 // XXX result is actually not a global index. We (ab)use the Sym type
547 // so we don't need conversion for accessing bitmaps.
548 func (l *Loader) extIndex(i Sym) Sym {
549 _, li := l.toLocal(i)
553 // Get a new payload for external symbol, return its index in
554 // the payloads array.
555 func (l *Loader) newPayload(name string, ver int) int {
556 pi := len(l.payloads)
557 pp := l.allocPayload()
560 l.payloads = append(l.payloads, pp)
561 l.growExtAttrBitmaps()
565 // getPayload returns a pointer to the extSymPayload struct for an
566 // external symbol if the symbol has a payload. Will panic if the
567 // symbol in question is bogus (zero or not an external sym).
568 func (l *Loader) getPayload(i Sym) *extSymPayload {
569 if !l.IsExternal(i) {
570 panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
573 return l.payloads[pi]
576 // allocPayload allocates a new payload.
577 func (l *Loader) allocPayload() *extSymPayload {
578 batch := l.payloadBatch
580 batch = make([]extSymPayload, 1000)
583 l.payloadBatch = batch[1:]
587 func (ms *extSymPayload) Grow(siz int64) {
588 if int64(int(siz)) != siz {
589 log.Fatalf("symgrow size %d too long", siz)
591 if int64(len(ms.data)) >= siz {
594 if cap(ms.data) < int(siz) {
596 ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
597 ms.data = ms.data[0:cl]
599 ms.data = ms.data[:siz]
602 // Convert a local index to a global index.
603 func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
607 // Convert a global index to a local index.
608 func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
609 return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
612 // Resolve a local symbol reference. Return global index.
613 func (l *Loader) resolve(r *oReader, s goobj.SymRef) Sym {
615 switch p := s.PkgIdx; p {
616 case goobj.PkgIdxInvalid:
617 // {0, X} with non-zero X is never a valid sym reference from a Go object.
618 // We steal this space for symbol references from external objects.
619 // In this case, X is just the global index.
620 if l.isExtReader(r) {
627 case goobj.PkgIdxHashed64:
628 i := int(s.SymIdx) + r.ndef
630 case goobj.PkgIdxHashed:
631 i := int(s.SymIdx) + r.ndef + r.nhashed64def
633 case goobj.PkgIdxNone:
634 i := int(s.SymIdx) + r.ndef + r.nhashed64def + r.nhasheddef
636 case goobj.PkgIdxBuiltin:
637 if bi := l.builtinSyms[s.SymIdx]; bi != 0 {
640 l.reportMissingBuiltin(int(s.SymIdx), r.unit.Lib.Pkg)
642 case goobj.PkgIdxSelf:
645 rr = l.objs[r.pkg[p]].r
647 return l.toGlobal(rr, s.SymIdx)
650 // reportMissingBuiltin issues an error in the case where we have a
651 // relocation against a runtime builtin whose definition is not found
652 // when the runtime package is built. The canonical example is
653 // "runtime.racefuncenter" -- currently if you do something like
655 // go build -gcflags=-race myprogram.go
657 // the compiler will insert calls to the builtin runtime.racefuncenter,
658 // but the version of the runtime used for linkage won't actually contain
659 // definitions of that symbol. See issue #42396 for details.
661 // As currently implemented, this is a fatal error. This has drawbacks
662 // in that if there are multiple missing builtins, the error will only
663 // cite the first one. On the plus side, terminating the link here has
664 // advantages in that we won't run the risk of panics or crashes later
665 // on in the linker due to R_CALL relocations with 0-valued target
667 func (l *Loader) reportMissingBuiltin(bsym int, reflib string) {
668 bname, _ := goobj.BuiltinName(bsym)
669 log.Fatalf("reference to undefined builtin %q from package %q",
673 // Look up a symbol by name, return global index, or 0 if not found.
674 // This is more like Syms.ROLookup than Lookup -- it doesn't create
676 func (l *Loader) Lookup(name string, ver int) Sym {
677 if ver >= sym.SymVerStatic || ver < 0 {
678 return l.extStaticSyms[nameVer{name, ver}]
680 return l.symsByName[ver][name]
683 // Check that duplicate symbols have same contents.
684 func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
686 rdup, ldup := l.toLocal(dup)
687 pdup := rdup.Data(ldup)
688 if bytes.Equal(p, pdup) {
691 reason := "same length but different contents"
692 if len(p) != len(pdup) {
693 reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
695 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)
697 // For the moment, allow DWARF subprogram DIEs for
698 // auto-generated wrapper functions. What seems to happen
699 // here is that we get different line numbers on formal
700 // params; I am guessing that the pos is being inherited
701 // from the spot where the wrapper is needed.
702 allowed := strings.HasPrefix(name, "go.info.go.interface") ||
703 strings.HasPrefix(name, "go.info.go.builtin") ||
704 strings.HasPrefix(name, "go.debuglines")
710 func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
712 // Number of total symbols.
713 func (l *Loader) NSym() int {
714 return len(l.objSyms)
717 // Number of defined Go symbols.
718 func (l *Loader) NDef() int {
719 return int(l.extStart)
722 // Number of reachable symbols.
723 func (l *Loader) NReachableSym() int {
724 return l.attrReachable.Count()
727 // SymNameLen returns the length of the symbol name, trying hard not to load
729 func (l *Loader) SymNameLen(i Sym) int {
730 // Not much we can do about external symbols.
732 return len(l.SymName(i))
734 r, li := l.toLocal(i)
735 le := r.Sym(li).NameLen(r.Reader)
736 if !r.NeedNameExpansion() {
739 // Just load the symbol name. We don't know how expanded it'll be.
740 return len(l.SymName(i))
743 // Returns the raw (unpatched) name of the i-th symbol.
744 func (l *Loader) RawSymName(i Sym) string {
746 pp := l.getPayload(i)
749 r, li := l.toLocal(i)
750 return r.Sym(li).Name(r.Reader)
753 // Returns the (patched) name of the i-th symbol.
754 func (l *Loader) SymName(i Sym) string {
756 pp := l.getPayload(i)
759 r, li := l.toLocal(i)
760 name := r.Sym(li).Name(r.Reader)
761 if !r.NeedNameExpansion() {
764 return strings.Replace(name, "\"\".", r.pkgprefix, -1)
767 // Returns the version of the i-th symbol.
768 func (l *Loader) SymVersion(i Sym) int {
770 pp := l.getPayload(i)
773 r, li := l.toLocal(i)
774 return int(abiToVer(r.Sym(li).ABI(), r.version))
777 func (l *Loader) IsFileLocal(i Sym) bool {
778 return l.SymVersion(i) >= sym.SymVerStatic
781 // IsFromAssembly returns true if this symbol is derived from an
782 // object file generated by the Go assembler.
783 func (l *Loader) IsFromAssembly(i Sym) bool {
788 return r.FromAssembly()
791 // Returns the type of the i-th symbol.
792 func (l *Loader) SymType(i Sym) sym.SymKind {
794 pp := l.getPayload(i)
800 r, li := l.toLocal(i)
801 return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
804 // Returns the attributes of the i-th symbol.
805 func (l *Loader) SymAttr(i Sym) uint8 {
807 // TODO: do something? External symbols have different representation of attributes.
808 // For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
809 // set by external symbol.
812 r, li := l.toLocal(i)
813 return r.Sym(li).Flag()
816 // Returns the size of the i-th symbol.
817 func (l *Loader) SymSize(i Sym) int64 {
819 pp := l.getPayload(i)
822 r, li := l.toLocal(i)
823 return int64(r.Sym(li).Siz())
826 // AttrReachable returns true for symbols that are transitively
827 // referenced from the entry points. Unreachable symbols are not
828 // written to the output.
829 func (l *Loader) AttrReachable(i Sym) bool {
830 return l.attrReachable.Has(i)
833 // SetAttrReachable sets the reachability property for a symbol (see
835 func (l *Loader) SetAttrReachable(i Sym, v bool) {
837 l.attrReachable.Set(i)
839 l.attrReachable.Unset(i)
843 // AttrOnList returns true for symbols that are on some list (such as
844 // the list of all text symbols, or one of the lists of data symbols)
845 // and is consulted to avoid bugs where a symbol is put on a list
847 func (l *Loader) AttrOnList(i Sym) bool {
848 return l.attrOnList.Has(i)
851 // SetAttrOnList sets the "on list" property for a symbol (see
853 func (l *Loader) SetAttrOnList(i Sym, v bool) {
857 l.attrOnList.Unset(i)
861 // AttrLocal returns true for symbols that are only visible within the
862 // module (executable or shared library) being linked. This attribute
863 // is applied to thunks and certain other linker-generated symbols.
864 func (l *Loader) AttrLocal(i Sym) bool {
865 return l.attrLocal.Has(i)
868 // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
869 func (l *Loader) SetAttrLocal(i Sym, v bool) {
877 // AttrUsedInIface returns true for a type symbol that is used in
879 func (l *Loader) AttrUsedInIface(i Sym) bool {
880 return l.attrUsedInIface.Has(i)
883 func (l *Loader) SetAttrUsedInIface(i Sym, v bool) {
885 l.attrUsedInIface.Set(i)
887 l.attrUsedInIface.Unset(i)
891 // SymAddr checks that a symbol is reachable, and returns its value.
892 func (l *Loader) SymAddr(i Sym) int64 {
893 if !l.AttrReachable(i) {
894 panic("unreachable symbol in symaddr")
899 // AttrNotInSymbolTable returns true for symbols that should not be
900 // added to the symbol table of the final generated load module.
901 func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
902 return l.attrNotInSymbolTable.Has(i)
905 // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
906 // (see AttrNotInSymbolTable above).
907 func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
909 l.attrNotInSymbolTable.Set(i)
911 l.attrNotInSymbolTable.Unset(i)
915 // AttrVisibilityHidden symbols returns true for ELF symbols with
916 // visibility set to STV_HIDDEN. They become local symbols in
917 // the final executable. Only relevant when internally linking
918 // on an ELF platform.
919 func (l *Loader) AttrVisibilityHidden(i Sym) bool {
920 if !l.IsExternal(i) {
923 return l.attrVisibilityHidden.Has(l.extIndex(i))
926 // SetAttrVisibilityHidden sets the "hidden visibility" property for a
927 // symbol (see AttrVisibilityHidden).
928 func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
929 if !l.IsExternal(i) {
930 panic("tried to set visibility attr on non-external symbol")
933 l.attrVisibilityHidden.Set(l.extIndex(i))
935 l.attrVisibilityHidden.Unset(l.extIndex(i))
939 // AttrDuplicateOK returns true for a symbol that can be present in
940 // multiple object files.
941 func (l *Loader) AttrDuplicateOK(i Sym) bool {
942 if !l.IsExternal(i) {
943 // TODO: if this path winds up being taken frequently, it
944 // might make more sense to copy the flag value out of the object
945 // into a larger bitmap during preload.
946 r, li := l.toLocal(i)
947 return r.Sym(li).Dupok()
949 return l.attrDuplicateOK.Has(l.extIndex(i))
952 // SetAttrDuplicateOK sets the "duplicate OK" property for an external
953 // symbol (see AttrDuplicateOK).
954 func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
955 if !l.IsExternal(i) {
956 panic("tried to set dupok attr on non-external symbol")
959 l.attrDuplicateOK.Set(l.extIndex(i))
961 l.attrDuplicateOK.Unset(l.extIndex(i))
965 // AttrShared returns true for symbols compiled with the -shared option.
966 func (l *Loader) AttrShared(i Sym) bool {
967 if !l.IsExternal(i) {
968 // TODO: if this path winds up being taken frequently, it
969 // might make more sense to copy the flag value out of the
970 // object into a larger bitmap during preload.
974 return l.attrShared.Has(l.extIndex(i))
977 // SetAttrShared sets the "shared" property for an external
978 // symbol (see AttrShared).
979 func (l *Loader) SetAttrShared(i Sym, v bool) {
980 if !l.IsExternal(i) {
981 panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
984 l.attrShared.Set(l.extIndex(i))
986 l.attrShared.Unset(l.extIndex(i))
990 // AttrExternal returns true for function symbols loaded from host
992 func (l *Loader) AttrExternal(i Sym) bool {
993 if !l.IsExternal(i) {
996 return l.attrExternal.Has(l.extIndex(i))
999 // SetAttrExternal sets the "external" property for an host object
1000 // symbol (see AttrExternal).
1001 func (l *Loader) SetAttrExternal(i Sym, v bool) {
1002 if !l.IsExternal(i) {
1003 panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.RawSymName(i)))
1006 l.attrExternal.Set(l.extIndex(i))
1008 l.attrExternal.Unset(l.extIndex(i))
1012 // AttrTopFrame returns true for a function symbol that is an entry
1013 // point, meaning that unwinders should stop when they hit this
1015 func (l *Loader) AttrTopFrame(i Sym) bool {
1016 _, ok := l.attrTopFrame[i]
1020 // SetAttrTopFrame sets the "top frame" property for a symbol (see
1022 func (l *Loader) SetAttrTopFrame(i Sym, v bool) {
1024 l.attrTopFrame[i] = struct{}{}
1026 delete(l.attrTopFrame, i)
1030 // AttrSpecial returns true for a symbols that do not have their
1031 // address (i.e. Value) computed by the usual mechanism of
1032 // data.go:dodata() & data.go:address().
1033 func (l *Loader) AttrSpecial(i Sym) bool {
1034 _, ok := l.attrSpecial[i]
1038 // SetAttrSpecial sets the "special" property for a symbol (see
1040 func (l *Loader) SetAttrSpecial(i Sym, v bool) {
1042 l.attrSpecial[i] = struct{}{}
1044 delete(l.attrSpecial, i)
1048 // AttrCgoExportDynamic returns true for a symbol that has been
1049 // specially marked via the "cgo_export_dynamic" compiler directive
1050 // written by cgo (in response to //export directives in the source).
1051 func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
1052 _, ok := l.attrCgoExportDynamic[i]
1056 // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
1057 // (see AttrCgoExportDynamic).
1058 func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
1060 l.attrCgoExportDynamic[i] = struct{}{}
1062 delete(l.attrCgoExportDynamic, i)
1066 // AttrCgoExportStatic returns true for a symbol that has been
1067 // specially marked via the "cgo_export_static" directive
1069 func (l *Loader) AttrCgoExportStatic(i Sym) bool {
1070 _, ok := l.attrCgoExportStatic[i]
1074 // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
1075 // (see AttrCgoExportStatic).
1076 func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
1078 l.attrCgoExportStatic[i] = struct{}{}
1080 delete(l.attrCgoExportStatic, i)
1084 // IsGeneratedSym returns true if a symbol's been previously marked as a
1085 // generator symbol through the SetIsGeneratedSym. The functions for generator
1086 // symbols are kept in the Link context.
1087 func (l *Loader) IsGeneratedSym(i Sym) bool {
1088 _, ok := l.generatedSyms[i]
1092 // SetIsGeneratedSym marks symbols as generated symbols. Data shouldn't be
1093 // stored in generated symbols, and a function is registered and called for
1094 // each of these symbols.
1095 func (l *Loader) SetIsGeneratedSym(i Sym, v bool) {
1096 if !l.IsExternal(i) {
1097 panic("only external symbols can be generated")
1100 l.generatedSyms[i] = struct{}{}
1102 delete(l.generatedSyms, i)
1106 func (l *Loader) AttrCgoExport(i Sym) bool {
1107 return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
1110 // AttrReadOnly returns true for a symbol whose underlying data
1111 // is stored via a read-only mmap.
1112 func (l *Loader) AttrReadOnly(i Sym) bool {
1113 if v, ok := l.attrReadOnly[i]; ok {
1116 if l.IsExternal(i) {
1117 pp := l.getPayload(i)
1119 return l.objs[pp.objidx].r.ReadOnly()
1123 r, _ := l.toLocal(i)
1127 // SetAttrReadOnly sets the "data is read only" property for a symbol
1128 // (see AttrReadOnly).
1129 func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
1130 l.attrReadOnly[i] = v
1133 // AttrSubSymbol returns true for symbols that are listed as a
1134 // sub-symbol of some other outer symbol. The sub/outer mechanism is
1135 // used when loading host objects (sections from the host object
1136 // become regular linker symbols and symbols go on the Sub list of
1137 // their section) and for constructing the global offset table when
1138 // internally linking a dynamic executable.
1140 // Note that in later stages of the linker, we set Outer(S) to some
1141 // container symbol C, but don't set Sub(C). Thus we have two
1142 // distinct scenarios:
1144 // - Outer symbol covers the address ranges of its sub-symbols.
1145 // Outer.Sub is set in this case.
1146 // - Outer symbol doesn't conver the address ranges. It is zero-sized
1147 // and doesn't have sub-symbols. In the case, the inner symbol is
1148 // not actually a "SubSymbol". (Tricky!)
1150 // This method returns TRUE only for sub-symbols in the first scenario.
1152 // FIXME: would be better to do away with this and have a better way
1153 // to represent container symbols.
1155 func (l *Loader) AttrSubSymbol(i Sym) bool {
1156 // we don't explicitly store this attribute any more -- return
1157 // a value based on the sub-symbol setting.
1162 return l.SubSym(o) != 0
1165 // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
1166 // clients should instead use the AddInteriorSym method to establish
1167 // containment relationships for host object symbols.
1169 // Returns whether the i-th symbol has ReflectMethod attribute set.
1170 func (l *Loader) IsReflectMethod(i Sym) bool {
1171 return l.SymAttr(i)&goobj.SymFlagReflectMethod != 0
1174 // Returns whether the i-th symbol is nosplit.
1175 func (l *Loader) IsNoSplit(i Sym) bool {
1176 return l.SymAttr(i)&goobj.SymFlagNoSplit != 0
1179 // Returns whether this is a Go type symbol.
1180 func (l *Loader) IsGoType(i Sym) bool {
1181 return l.SymAttr(i)&goobj.SymFlagGoType != 0
1184 // Returns whether this symbol should be included in typelink.
1185 func (l *Loader) IsTypelink(i Sym) bool {
1186 return l.SymAttr(i)&goobj.SymFlagTypelink != 0
1189 // Returns whether this symbol is an itab symbol.
1190 func (l *Loader) IsItab(i Sym) bool {
1191 if l.IsExternal(i) {
1194 r, li := l.toLocal(i)
1195 return r.Sym(li).IsItab()
1198 // Return whether this is a trampoline of a deferreturn call.
1199 func (l *Loader) IsDeferReturnTramp(i Sym) bool {
1200 return l.deferReturnTramp[i]
1203 // Set that i is a trampoline of a deferreturn call.
1204 func (l *Loader) SetIsDeferReturnTramp(i Sym, v bool) {
1205 l.deferReturnTramp[i] = v
1208 // growValues grows the slice used to store symbol values.
1209 func (l *Loader) growValues(reqLen int) {
1210 curLen := len(l.values)
1211 if reqLen > curLen {
1212 l.values = append(l.values, make([]int64, reqLen+1-curLen)...)
1216 // SymValue returns the value of the i-th symbol. i is global index.
1217 func (l *Loader) SymValue(i Sym) int64 {
1221 // SetSymValue sets the value of the i-th symbol. i is global index.
1222 func (l *Loader) SetSymValue(i Sym, val int64) {
1226 // AddToSymValue adds to the value of the i-th symbol. i is the global index.
1227 func (l *Loader) AddToSymValue(i Sym, val int64) {
1231 // Returns the symbol content of the i-th symbol. i is global index.
1232 func (l *Loader) Data(i Sym) []byte {
1233 if l.IsExternal(i) {
1234 pp := l.getPayload(i)
1240 r, li := l.toLocal(i)
1244 // FreeData clears the symbol data of an external symbol, allowing the memory
1245 // to be freed earlier. No-op for non-external symbols.
1246 // i is global index.
1247 func (l *Loader) FreeData(i Sym) {
1248 if l.IsExternal(i) {
1249 pp := l.getPayload(i)
1256 // SymAlign returns the alignment for a symbol.
1257 func (l *Loader) SymAlign(i Sym) int32 {
1258 if int(i) >= len(l.align) {
1259 // align is extended lazily -- it the sym in question is
1260 // outside the range of the existing slice, then we assume its
1261 // alignment has not yet been set.
1264 // TODO: would it make sense to return an arch-specific
1265 // alignment depending on section type? E.g. STEXT => 32,
1271 return int32(1 << (abits - 1))
1274 // SetSymAlign sets the alignment for a symbol.
1275 func (l *Loader) SetSymAlign(i Sym, align int32) {
1276 // Reject nonsense alignments.
1277 if align < 0 || align&(align-1) != 0 {
1278 panic("bad alignment value")
1280 if int(i) >= len(l.align) {
1281 l.align = append(l.align, make([]uint8, l.NSym()-len(l.align))...)
1286 l.align[i] = uint8(bits.Len32(uint32(align)))
1289 // SymValue returns the section of the i-th symbol. i is global index.
1290 func (l *Loader) SymSect(i Sym) *sym.Section {
1291 if int(i) >= len(l.symSects) {
1292 // symSects is extended lazily -- it the sym in question is
1293 // outside the range of the existing slice, then we assume its
1294 // section has not yet been set.
1297 return l.sects[l.symSects[i]]
1300 // SetSymSect sets the section of the i-th symbol. i is global index.
1301 func (l *Loader) SetSymSect(i Sym, sect *sym.Section) {
1302 if int(i) >= len(l.symSects) {
1303 l.symSects = append(l.symSects, make([]uint16, l.NSym()-len(l.symSects))...)
1305 l.symSects[i] = sect.Index
1308 // growSects grows the slice used to store symbol sections.
1309 func (l *Loader) growSects(reqLen int) {
1310 curLen := len(l.symSects)
1311 if reqLen > curLen {
1312 l.symSects = append(l.symSects, make([]uint16, reqLen+1-curLen)...)
1316 // NewSection creates a new (output) section.
1317 func (l *Loader) NewSection() *sym.Section {
1318 sect := new(sym.Section)
1320 if idx != int(uint16(idx)) {
1321 panic("too many sections created")
1323 sect.Index = uint16(idx)
1324 l.sects = append(l.sects, sect)
1328 // SymDynImplib returns the "dynimplib" 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) SymDynimplib(i Sym) string {
1332 return l.dynimplib[i]
1335 // SetSymDynimplib sets the "dynimplib" attribute for a symbol.
1336 func (l *Loader) SetSymDynimplib(i Sym, value string) {
1337 // reject bad symbols
1338 if i >= Sym(len(l.objSyms)) || i == 0 {
1339 panic("bad symbol index in SetDynimplib")
1342 delete(l.dynimplib, i)
1344 l.dynimplib[i] = value
1348 // SymDynimpvers returns the "dynimpvers" attribute for the specified
1349 // symbol, making up a portion of the info for a symbol specified
1350 // on a "cgo_import_dynamic" compiler directive.
1351 func (l *Loader) SymDynimpvers(i Sym) string {
1352 return l.dynimpvers[i]
1355 // SetSymDynimpvers sets the "dynimpvers" attribute for a symbol.
1356 func (l *Loader) SetSymDynimpvers(i Sym, value string) {
1357 // reject bad symbols
1358 if i >= Sym(len(l.objSyms)) || i == 0 {
1359 panic("bad symbol index in SetDynimpvers")
1362 delete(l.dynimpvers, i)
1364 l.dynimpvers[i] = value
1368 // SymExtname returns the "extname" value for the specified
1370 func (l *Loader) SymExtname(i Sym) string {
1371 if s, ok := l.extname[i]; ok {
1377 // SetSymExtname sets the "extname" attribute for a symbol.
1378 func (l *Loader) SetSymExtname(i Sym, value string) {
1379 // reject bad symbols
1380 if i >= Sym(len(l.objSyms)) || i == 0 {
1381 panic("bad symbol index in SetExtname")
1384 delete(l.extname, i)
1386 l.extname[i] = value
1390 // SymElfType returns the previously recorded ELF type for a symbol
1391 // (used only for symbols read from shared libraries by ldshlibsyms).
1392 // It is not set for symbols defined by the packages being linked or
1393 // by symbols read by ldelf (and so is left as elf.STT_NOTYPE).
1394 func (l *Loader) SymElfType(i Sym) elf.SymType {
1395 if et, ok := l.elfType[i]; ok {
1398 return elf.STT_NOTYPE
1401 // SetSymElfType sets the elf type attribute for a symbol.
1402 func (l *Loader) SetSymElfType(i Sym, et elf.SymType) {
1403 // reject bad symbols
1404 if i >= Sym(len(l.objSyms)) || i == 0 {
1405 panic("bad symbol index in SetSymElfType")
1407 if et == elf.STT_NOTYPE {
1408 delete(l.elfType, i)
1414 // SymElfSym returns the ELF symbol index for a given loader
1415 // symbol, assigned during ELF symtab generation.
1416 func (l *Loader) SymElfSym(i Sym) int32 {
1420 // SetSymElfSym sets the elf symbol index for a symbol.
1421 func (l *Loader) SetSymElfSym(i Sym, es int32) {
1423 panic("bad sym index")
1432 // SymLocalElfSym returns the "local" ELF symbol index for a given loader
1433 // symbol, assigned during ELF symtab generation.
1434 func (l *Loader) SymLocalElfSym(i Sym) int32 {
1435 return l.localElfSym[i]
1438 // SetSymLocalElfSym sets the "local" elf symbol index for a symbol.
1439 func (l *Loader) SetSymLocalElfSym(i Sym, es int32) {
1441 panic("bad sym index")
1444 delete(l.localElfSym, i)
1446 l.localElfSym[i] = es
1450 // SymPlt returns the plt value for pe symbols.
1451 func (l *Loader) SymPlt(s Sym) int32 {
1452 if v, ok := l.plt[s]; ok {
1458 // SetPlt sets the plt value for pe symbols.
1459 func (l *Loader) SetPlt(i Sym, v int32) {
1460 if i >= Sym(len(l.objSyms)) || i == 0 {
1461 panic("bad symbol for SetPlt")
1470 // SymGot returns the got value for pe symbols.
1471 func (l *Loader) SymGot(s Sym) int32 {
1472 if v, ok := l.got[s]; ok {
1478 // SetGot sets the got value for pe symbols.
1479 func (l *Loader) SetGot(i Sym, v int32) {
1480 if i >= Sym(len(l.objSyms)) || i == 0 {
1481 panic("bad symbol for SetGot")
1490 // SymDynid returns the "dynid" property for the specified symbol.
1491 func (l *Loader) SymDynid(i Sym) int32 {
1492 if s, ok := l.dynid[i]; ok {
1498 // SetSymDynid sets the "dynid" property for a symbol.
1499 func (l *Loader) SetSymDynid(i Sym, val int32) {
1500 // reject bad symbols
1501 if i >= Sym(len(l.objSyms)) || i == 0 {
1502 panic("bad symbol index in SetSymDynid")
1511 // DynIdSyms returns the set of symbols for which dynID is set to an
1512 // interesting (non-default) value. This is expected to be a fairly
1514 func (l *Loader) DynidSyms() []Sym {
1515 sl := make([]Sym, 0, len(l.dynid))
1516 for s := range l.dynid {
1519 sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
1523 // SymGoType returns the 'Gotype' property for a given symbol (set by
1524 // the Go compiler for variable symbols). This version relies on
1525 // reading aux symbols for the target sym -- it could be that a faster
1526 // approach would be to check for gotype during preload and copy the
1527 // results in to a map (might want to try this at some point and see
1528 // if it helps speed things up).
1529 func (l *Loader) SymGoType(i Sym) Sym {
1531 var auxs []goobj.Aux
1532 if l.IsExternal(i) {
1533 pp := l.getPayload(i)
1534 r = l.objs[pp.objidx].r
1538 r, li = l.toLocal(i)
1541 for j := range auxs {
1544 case goobj.AuxGotype:
1545 return l.resolve(r, a.Sym())
1551 // SymUnit returns the compilation unit for a given symbol (which will
1552 // typically be nil for external or linker-manufactured symbols).
1553 func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
1554 if l.IsExternal(i) {
1555 pp := l.getPayload(i)
1557 r := l.objs[pp.objidx].r
1562 r, _ := l.toLocal(i)
1566 // SymPkg returns the package where the symbol came from (for
1567 // regular compiler-generated Go symbols), but in the case of
1568 // building with "-linkshared" (when a symbol is read from a
1569 // shared library), will hold the library name.
1570 // NOTE: this correspondes to sym.Symbol.File field.
1571 func (l *Loader) SymPkg(i Sym) string {
1572 if f, ok := l.symPkg[i]; ok {
1575 if l.IsExternal(i) {
1576 pp := l.getPayload(i)
1578 r := l.objs[pp.objidx].r
1579 return r.unit.Lib.Pkg
1583 r, _ := l.toLocal(i)
1584 return r.unit.Lib.Pkg
1587 // SetSymPkg sets the package/library for a symbol. This is
1588 // needed mainly for external symbols, specifically those imported
1589 // from shared libraries.
1590 func (l *Loader) SetSymPkg(i Sym, pkg string) {
1591 // reject bad symbols
1592 if i >= Sym(len(l.objSyms)) || i == 0 {
1593 panic("bad symbol index in SetSymPkg")
1598 // SymLocalentry returns the "local entry" value for the specified
1600 func (l *Loader) SymLocalentry(i Sym) uint8 {
1601 return l.localentry[i]
1604 // SetSymLocalentry sets the "local entry" attribute for a symbol.
1605 func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
1606 // reject bad symbols
1607 if i >= Sym(len(l.objSyms)) || i == 0 {
1608 panic("bad symbol index in SetSymLocalentry")
1611 delete(l.localentry, i)
1613 l.localentry[i] = value
1617 // Returns the number of aux symbols given a global index.
1618 func (l *Loader) NAux(i Sym) int {
1619 if l.IsExternal(i) {
1622 r, li := l.toLocal(i)
1626 // Returns the "handle" to the j-th aux symbol of the i-th symbol.
1627 func (l *Loader) Aux(i Sym, j int) Aux {
1628 if l.IsExternal(i) {
1631 r, li := l.toLocal(i)
1632 if j >= r.NAux(li) {
1635 return Aux{r.Aux(li, j), r, l}
1638 // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
1639 // symbols associated with a given function symbol. Prior to the
1640 // introduction of the loader, this was done purely using name
1641 // lookups, e.f. for function with name XYZ we would then look up
1642 // go.info.XYZ, etc.
1643 func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
1644 if l.SymType(fnSymIdx) != sym.STEXT {
1645 log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1647 if l.IsExternal(fnSymIdx) {
1648 // Current expectation is that any external function will
1649 // not have auxsyms.
1652 r, li := l.toLocal(fnSymIdx)
1654 for i := range auxs {
1657 case goobj.AuxDwarfInfo:
1658 auxDwarfInfo = l.resolve(r, a.Sym())
1659 if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
1660 panic("aux dwarf info sym with wrong type")
1662 case goobj.AuxDwarfLoc:
1663 auxDwarfLoc = l.resolve(r, a.Sym())
1664 if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
1665 panic("aux dwarf loc sym with wrong type")
1667 case goobj.AuxDwarfRanges:
1668 auxDwarfRanges = l.resolve(r, a.Sym())
1669 if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
1670 panic("aux dwarf ranges sym with wrong type")
1672 case goobj.AuxDwarfLines:
1673 auxDwarfLines = l.resolve(r, a.Sym())
1674 if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
1675 panic("aux dwarf lines sym with wrong type")
1682 // AddInteriorSym sets up 'interior' as an interior symbol of
1683 // container/payload symbol 'container'. An interior symbol does not
1684 // itself have data, but gives a name to a subrange of the data in its
1685 // container symbol. The container itself may or may not have a name.
1686 // This method is intended primarily for use in the host object
1687 // loaders, to capture the semantics of symbols and sections in an
1688 // object file. When reading a host object file, we'll typically
1689 // encounter a static section symbol (ex: ".text") containing content
1690 // for a collection of functions, then a series of ELF (or macho, etc)
1691 // symbol table entries each of which points into a sub-section
1692 // (offset and length) of its corresponding container symbol. Within
1693 // the go linker we create a loader.Sym for the container (which is
1694 // expected to have the actual content/payload) and then a set of
1695 // interior loader.Sym's that point into a portion of the container.
1696 func (l *Loader) AddInteriorSym(container Sym, interior Sym) {
1697 // Container symbols are expected to have content/data.
1698 // NB: this restriction may turn out to be too strict (it's possible
1699 // to imagine a zero-sized container with an interior symbol pointing
1700 // into it); it's ok to relax or remove it if we counter an
1701 // oddball host object that triggers this.
1702 if l.SymSize(container) == 0 && len(l.Data(container)) == 0 {
1703 panic("unexpected empty container symbol")
1705 // The interior symbols for a container are not expected to have
1706 // content/data or relocations.
1707 if len(l.Data(interior)) != 0 {
1708 panic("unexpected non-empty interior symbol")
1710 // Interior symbol is expected to be in the symbol table.
1711 if l.AttrNotInSymbolTable(interior) {
1712 panic("interior symbol must be in symtab")
1714 // Only a single level of containment is allowed.
1715 if l.OuterSym(container) != 0 {
1716 panic("outer has outer itself")
1718 // Interior sym should not already have a sibling.
1719 if l.SubSym(interior) != 0 {
1720 panic("sub set for subsym")
1722 // Interior sym should not already point at a container.
1723 if l.OuterSym(interior) != 0 {
1724 panic("outer already set for subsym")
1726 l.sub[interior] = l.sub[container]
1727 l.sub[container] = interior
1728 l.outer[interior] = container
1731 // OuterSym gets the outer symbol for host object loaded symbols.
1732 func (l *Loader) OuterSym(i Sym) Sym {
1733 // FIXME: add check for isExternal?
1737 // SubSym gets the subsymbol for host object loaded symbols.
1738 func (l *Loader) SubSym(i Sym) Sym {
1739 // NB: note -- no check for l.isExternal(), since I am pretty sure
1740 // that later phases in the linker set subsym for "type." syms
1744 // SetCarrierSym declares that 'c' is the carrier or container symbol
1745 // for 's'. Carrier symbols are used in the linker to as a container
1746 // for a collection of sub-symbols where the content of the
1747 // sub-symbols is effectively concatenated to form the content of the
1748 // carrier. The carrier is given a name in the output symbol table
1749 // while the sub-symbol names are not. For example, the Go compiler
1750 // emits named string symbols (type SGOSTRING) when compiling a
1751 // package; after being deduplicated, these symbols are collected into
1752 // a single unit by assigning them a new carrier symbol named
1753 // "go.string.*" (which appears in the final symbol table for the
1754 // output load module).
1755 func (l *Loader) SetCarrierSym(s Sym, c Sym) {
1757 panic("invalid carrier in SetCarrierSym")
1760 panic("invalid sub-symbol in SetCarrierSym")
1762 // Carrier symbols are not expected to have content/data. It is
1763 // ok for them to have non-zero size (to allow for use of generator
1765 if len(l.Data(c)) != 0 {
1766 panic("unexpected non-empty carrier symbol")
1769 // relocsym's foldSubSymbolOffset requires that we only
1770 // have a single level of containment-- enforce here.
1771 if l.outer[c] != 0 {
1772 panic("invalid nested carrier sym")
1776 // Initialize Reachable bitmap and its siblings for running deadcode pass.
1777 func (l *Loader) InitReachable() {
1778 l.growAttrBitmaps(l.NSym() + 1)
1781 type symWithVal struct {
1785 type bySymValue []symWithVal
1787 func (s bySymValue) Len() int { return len(s) }
1788 func (s bySymValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1789 func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
1791 // SortSub walks through the sub-symbols for 's' and sorts them
1792 // in place by increasing value. Return value is the new
1793 // sub symbol for the specified outer symbol.
1794 func (l *Loader) SortSub(s Sym) Sym {
1796 if s == 0 || l.sub[s] == 0 {
1800 // Sort symbols using a slice first. Use a stable sort on the off
1801 // chance that there's more than once symbol with the same value,
1802 // so as to preserve reproducible builds.
1803 sl := []symWithVal{}
1804 for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
1805 sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
1807 sort.Stable(bySymValue(sl))
1809 // Then apply any changes needed to the sub map.
1811 for i := len(sl) - 1; i >= 0; i-- {
1817 // Update sub for outer symbol, then return
1822 // SortSyms sorts a list of symbols by their value.
1823 func (l *Loader) SortSyms(ss []Sym) {
1824 sort.SliceStable(ss, func(i, j int) bool { return l.SymValue(ss[i]) < l.SymValue(ss[j]) })
1827 // Insure that reachable bitmap and its siblings have enough size.
1828 func (l *Loader) growAttrBitmaps(reqLen int) {
1829 if reqLen > l.attrReachable.Len() {
1830 // These are indexed by global symbol
1831 l.attrReachable = growBitmap(reqLen, l.attrReachable)
1832 l.attrOnList = growBitmap(reqLen, l.attrOnList)
1833 l.attrLocal = growBitmap(reqLen, l.attrLocal)
1834 l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
1835 l.attrUsedInIface = growBitmap(reqLen, l.attrUsedInIface)
1837 l.growExtAttrBitmaps()
1840 func (l *Loader) growExtAttrBitmaps() {
1841 // These are indexed by external symbol index (e.g. l.extIndex(i))
1842 extReqLen := len(l.payloads)
1843 if extReqLen > l.attrVisibilityHidden.Len() {
1844 l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
1845 l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
1846 l.attrShared = growBitmap(extReqLen, l.attrShared)
1847 l.attrExternal = growBitmap(extReqLen, l.attrExternal)
1851 func (relocs *Relocs) Count() int { return len(relocs.rs) }
1853 // At returns the j-th reloc for a global symbol.
1854 func (relocs *Relocs) At(j int) Reloc {
1855 if relocs.l.isExtReader(relocs.r) {
1856 pp := relocs.l.payloads[relocs.li]
1857 return Reloc{&relocs.rs[j], relocs.r, relocs.l, pp.reltypes[j]}
1859 return Reloc{&relocs.rs[j], relocs.r, relocs.l, 0}
1862 // Relocs returns a Relocs object for the given global sym.
1863 func (l *Loader) Relocs(i Sym) Relocs {
1864 r, li := l.toLocal(i)
1866 panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
1868 return l.relocs(r, li)
1871 // Relocs returns a Relocs object given a local sym index and reader.
1872 func (l *Loader) relocs(r *oReader, li uint32) Relocs {
1873 var rs []goobj.Reloc
1874 if l.isExtReader(r) {
1875 pp := l.payloads[li]
1888 // FuncInfo provides hooks to access goobj.FuncInfo in the objects.
1889 type FuncInfo struct {
1894 lengths goobj.FuncInfoLengths
1897 func (fi *FuncInfo) Valid() bool { return fi.r != nil }
1899 func (fi *FuncInfo) Args() int {
1900 return int((*goobj.FuncInfo)(nil).ReadArgs(fi.data))
1903 func (fi *FuncInfo) Locals() int {
1904 return int((*goobj.FuncInfo)(nil).ReadLocals(fi.data))
1907 func (fi *FuncInfo) FuncID() objabi.FuncID {
1908 return objabi.FuncID((*goobj.FuncInfo)(nil).ReadFuncID(fi.data))
1911 func (fi *FuncInfo) Pcsp() Sym {
1912 sym := (*goobj.FuncInfo)(nil).ReadPcsp(fi.data)
1913 return fi.l.resolve(fi.r, sym)
1916 func (fi *FuncInfo) Pcfile() Sym {
1917 sym := (*goobj.FuncInfo)(nil).ReadPcfile(fi.data)
1918 return fi.l.resolve(fi.r, sym)
1921 func (fi *FuncInfo) Pcline() Sym {
1922 sym := (*goobj.FuncInfo)(nil).ReadPcline(fi.data)
1923 return fi.l.resolve(fi.r, sym)
1926 func (fi *FuncInfo) Pcinline() Sym {
1927 sym := (*goobj.FuncInfo)(nil).ReadPcinline(fi.data)
1928 return fi.l.resolve(fi.r, sym)
1931 // Preload has to be called prior to invoking the various methods
1932 // below related to pcdata, funcdataoff, files, and inltree nodes.
1933 func (fi *FuncInfo) Preload() {
1934 fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
1937 func (fi *FuncInfo) Pcdata() []Sym {
1938 if !fi.lengths.Initialized {
1939 panic("need to call Preload first")
1941 syms := (*goobj.FuncInfo)(nil).ReadPcdata(fi.data)
1942 ret := make([]Sym, len(syms))
1943 for i := range ret {
1944 ret[i] = fi.l.resolve(fi.r, syms[i])
1949 func (fi *FuncInfo) NumFuncdataoff() uint32 {
1950 if !fi.lengths.Initialized {
1951 panic("need to call Preload first")
1953 return fi.lengths.NumFuncdataoff
1956 func (fi *FuncInfo) Funcdataoff(k int) int64 {
1957 if !fi.lengths.Initialized {
1958 panic("need to call Preload first")
1960 return (*goobj.FuncInfo)(nil).ReadFuncdataoff(fi.data, fi.lengths.FuncdataoffOff, uint32(k))
1963 func (fi *FuncInfo) Funcdata(syms []Sym) []Sym {
1964 if !fi.lengths.Initialized {
1965 panic("need to call Preload first")
1967 if int(fi.lengths.NumFuncdataoff) > cap(syms) {
1968 syms = make([]Sym, 0, fi.lengths.NumFuncdataoff)
1972 for j := range fi.auxs {
1974 if a.Type() == goobj.AuxFuncdata {
1975 syms = append(syms, fi.l.resolve(fi.r, a.Sym()))
1981 func (fi *FuncInfo) NumFile() uint32 {
1982 if !fi.lengths.Initialized {
1983 panic("need to call Preload first")
1985 return fi.lengths.NumFile
1988 func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
1989 if !fi.lengths.Initialized {
1990 panic("need to call Preload first")
1992 return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
1995 type InlTreeNode struct {
1997 File goobj.CUFileIndex
2003 func (fi *FuncInfo) NumInlTree() uint32 {
2004 if !fi.lengths.Initialized {
2005 panic("need to call Preload first")
2007 return fi.lengths.NumInlTree
2010 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
2011 if !fi.lengths.Initialized {
2012 panic("need to call Preload first")
2014 node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
2016 Parent: node.Parent,
2019 Func: fi.l.resolve(fi.r, node.Func),
2020 ParentPC: node.ParentPC,
2024 func (l *Loader) FuncInfo(i Sym) FuncInfo {
2026 var auxs []goobj.Aux
2027 if l.IsExternal(i) {
2028 pp := l.getPayload(i)
2032 r = l.objs[pp.objidx].r
2036 r, li = l.toLocal(i)
2039 for j := range auxs {
2041 if a.Type() == goobj.AuxFuncInfo {
2042 b := r.Data(a.Sym().SymIdx)
2043 return FuncInfo{l, r, b, auxs, goobj.FuncInfoLengths{}}
2049 // Preload a package: adds autolib.
2050 // Does not add defined package or non-packaged symbols to the symbol table.
2051 // These are done in LoadSyms.
2052 // Does not read symbol data.
2053 // Returns the fingerprint of the object.
2054 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
2055 roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
2057 log.Fatal("cannot read object file:", err)
2059 r := goobj.NewReaderFromBytes(roObject, readonly)
2061 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
2062 log.Fatalf("found object file %s in old format", f.File().Name())
2064 panic("cannot read object file")
2066 pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
2068 nhashed64def := r.NHashed64def()
2069 nhasheddef := r.NHasheddef()
2073 version: localSymVersion,
2075 pkgprefix: pkgprefix,
2076 syms: make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
2078 nhasheddef: nhasheddef,
2079 nhashed64def: nhashed64def,
2080 objidx: uint32(len(l.objs)),
2084 lib.Autolib = append(lib.Autolib, r.Autolib()...)
2088 unit.FileTable = make([]string, nfile)
2089 for i := range unit.FileTable {
2090 unit.FileTable[i] = r.File(i)
2093 l.addObj(lib.Pkg, or)
2095 // The caller expects us consuming all the data
2096 f.MustSeek(length, os.SEEK_CUR)
2098 return r.Fingerprint()
2101 // Holds the loader along with temporary states for loading symbols.
2102 type loadState struct {
2104 hashed64Syms map[uint64]symAndSize // short hashed (content-addressable) symbols, keyed by content hash
2105 hashedSyms map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
2108 // Preload symbols of given kind from an object.
2109 func (st *loadState) preloadSyms(r *oReader, kind int) {
2111 var start, end uint32
2115 end = uint32(r.ndef)
2117 start = uint32(r.ndef)
2118 end = uint32(r.ndef + r.nhashed64def)
2120 start = uint32(r.ndef + r.nhashed64def)
2121 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2122 if l.hasUnknownPkgPath {
2123 // The content hash depends on symbol name expansion. If any package is
2124 // built without fully expanded names, the content hash is unreliable.
2125 // Treat them as named symbols.
2127 // (We don't need to do this for hashed64Def case, as there the hash
2128 // function is simply the identity function, which doesn't depend on
2133 start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2134 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
2136 panic("preloadSyms: bad kind")
2138 l.growAttrBitmaps(len(l.objSyms) + int(end-start))
2139 needNameExpansion := r.NeedNameExpansion()
2140 loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
2141 for i := start; i < end; i++ {
2145 if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
2146 name = osym.Name(r.Reader)
2147 if needNameExpansion {
2148 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2150 v = abiToVer(osym.ABI(), r.version)
2152 gi := st.addSym(name, v, r, i, kind, osym)
2154 if osym.TopFrame() {
2155 l.SetAttrTopFrame(gi, true)
2158 l.SetAttrLocal(gi, true)
2160 if osym.UsedInIface() {
2161 l.SetAttrUsedInIface(gi, true)
2163 if strings.HasPrefix(name, "runtime.") ||
2164 (loadingRuntimePkg && strings.HasPrefix(name, "type.")) {
2165 if bi := goobj.BuiltinIdx(name, v); bi != -1 {
2166 // This is a definition of a builtin symbol. Record where it is.
2167 l.builtinSyms[bi] = gi
2170 if a := int32(osym.Align()); a != 0 && a > l.SymAlign(gi) {
2171 l.SetSymAlign(gi, a)
2176 // Add syms, hashed (content-addressable) symbols, non-package symbols, and
2177 // references to external symbols (which are always named).
2178 func (l *Loader) LoadSyms(arch *sys.Arch) {
2179 // Allocate space for symbols, making a guess as to how much space we need.
2180 // This function was determined empirically by looking at the cmd/compile on
2181 // Darwin, and picking factors for hashed and hashed64 syms.
2182 var symSize, hashedSize, hashed64Size int
2183 for _, o := range l.objs[goObjStart:] {
2184 symSize += o.r.ndef + o.r.nhasheddef/2 + o.r.nhashed64def/2 + o.r.NNonpkgdef()
2185 hashedSize += o.r.nhasheddef / 2
2186 hashed64Size += o.r.nhashed64def / 2
2188 // Index 0 is invalid for symbols.
2189 l.objSyms = make([]objSym, 1, symSize)
2191 l.npkgsyms = l.NSym()
2194 hashed64Syms: make(map[uint64]symAndSize, hashed64Size),
2195 hashedSyms: make(map[goobj.HashType]symAndSize, hashedSize),
2198 for _, o := range l.objs[goObjStart:] {
2199 st.preloadSyms(o.r, pkgDef)
2201 for _, o := range l.objs[goObjStart:] {
2202 st.preloadSyms(o.r, hashed64Def)
2203 st.preloadSyms(o.r, hashedDef)
2204 st.preloadSyms(o.r, nonPkgDef)
2206 l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
2207 for _, o := range l.objs[goObjStart:] {
2208 loadObjRefs(l, o.r, arch)
2210 l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2213 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2214 // load non-package refs
2215 ndef := uint32(r.NAlldef())
2216 needNameExpansion := r.NeedNameExpansion()
2217 for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2218 osym := r.Sym(ndef + i)
2219 name := osym.Name(r.Reader)
2220 if needNameExpansion {
2221 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2223 v := abiToVer(osym.ABI(), r.version)
2224 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2225 gi := r.syms[ndef+i]
2227 l.SetAttrLocal(gi, true)
2229 if osym.UsedInIface() {
2230 l.SetAttrUsedInIface(gi, true)
2234 // referenced packages
2236 r.pkg = make([]uint32, npkg)
2237 for i := 1; i < npkg; i++ { // PkgIdx 0 is a dummy invalid package
2239 objidx, ok := l.objByPkg[pkg]
2241 log.Fatalf("reference of nonexisted package %s, from %v", pkg, r.unit.Lib)
2246 // load flags of package refs
2247 for i, n := 0, r.NRefFlags(); i < n; i++ {
2249 gi := l.resolve(r, rf.Sym())
2250 if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
2251 l.SetAttrUsedInIface(gi, true)
2256 func abiToVer(abi uint16, localSymVersion int) int {
2258 if abi == goobj.SymABIstatic {
2261 } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2262 // Note that data symbols are "ABI0", which maps to version 0.
2265 log.Fatalf("invalid symbol ABI: %d", abi)
2270 // ResolveABIAlias given a symbol returns the ABI alias target of that
2271 // symbol. If the sym in question is not an alias, the sym itself is
2273 func (l *Loader) ResolveABIAlias(s Sym) Sym {
2274 if l.flags&FlagUseABIAlias == 0 {
2280 if l.SymType(s) != sym.SABIALIAS {
2283 relocs := l.Relocs(s)
2284 target := relocs.At(0).Sym()
2285 if l.SymType(target) == sym.SABIALIAS {
2286 panic(fmt.Sprintf("ABI alias %s references another ABI alias %s", l.SymName(s), l.SymName(target)))
2291 // TopLevelSym tests a symbol (by name and kind) to determine whether
2292 // the symbol first class sym (participating in the link) or is an
2293 // anonymous aux or sub-symbol containing some sub-part or payload of
2295 func (l *Loader) TopLevelSym(s Sym) bool {
2296 return topLevelSym(l.RawSymName(s), l.SymType(s))
2299 // topLevelSym tests a symbol name and kind to determine whether
2300 // the symbol first class sym (participating in the link) or is an
2301 // anonymous aux or sub-symbol containing some sub-part or payload of
2303 func topLevelSym(sname string, skind sym.SymKind) bool {
2308 case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2315 // cloneToExternal takes the existing object file symbol (symIdx)
2316 // and creates a new external symbol payload that is a clone with
2317 // respect to name, version, type, relocations, etc. The idea here
2318 // is that if the linker decides it wants to update the contents of
2319 // a symbol originally discovered as part of an object file, it's
2320 // easier to do this if we make the updates to an external symbol
2322 func (l *Loader) cloneToExternal(symIdx Sym) {
2323 if l.IsExternal(symIdx) {
2324 panic("sym is already external, no need for clone")
2327 // Read the particulars from object.
2328 r, li := l.toLocal(symIdx)
2330 sname := osym.Name(r.Reader)
2331 if r.NeedNameExpansion() {
2332 sname = strings.Replace(sname, "\"\".", r.pkgprefix, -1)
2334 sver := abiToVer(osym.ABI(), r.version)
2335 skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2337 // Create new symbol, update version and kind.
2338 pi := l.newPayload(sname, sver)
2339 pp := l.payloads[pi]
2342 pp.size = int64(osym.Siz())
2343 pp.objidx = r.objidx
2345 // If this is a def, then copy the guts. We expect this case
2346 // to be very rare (one case it may come up is with -X).
2347 if li < uint32(r.NAlldef()) {
2350 relocs := l.Relocs(symIdx)
2351 pp.relocs = make([]goobj.Reloc, relocs.Count())
2352 pp.reltypes = make([]objabi.RelocType, relocs.Count())
2353 for i := range pp.relocs {
2354 // Copy the relocs slice.
2355 // Convert local reference to global reference.
2357 pp.relocs[i].Set(rel.Off(), rel.Siz(), 0, rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2358 pp.reltypes[i] = rel.Type()
2362 pp.data = r.Data(li)
2365 // If we're overriding a data symbol, collect the associated
2366 // Gotype, so as to propagate it to the new symbol.
2370 // Install new payload to global index space.
2371 // (This needs to happen at the end, as the accessors above
2372 // need to access the old symbol content.)
2373 l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2374 l.extReader.syms = append(l.extReader.syms, symIdx)
2377 // Copy the payload of symbol src to dst. Both src and dst must be external
2379 // The intended use case is that when building/linking against a shared library,
2380 // where we do symbol name mangling, the Go object file may have reference to
2381 // the original symbol name whereas the shared library provides a symbol with
2382 // the mangled name. When we do mangling, we copy payload of mangled to original.
2383 func (l *Loader) CopySym(src, dst Sym) {
2384 if !l.IsExternal(dst) {
2385 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2387 if !l.IsExternal(src) {
2388 panic("src is not external") //l.cloneToExternal(src)
2390 l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2391 l.SetSymPkg(dst, l.SymPkg(src))
2392 // TODO: other attributes?
2395 // CopyAttributes copies over all of the attributes of symbol 'src' to
2397 func (l *Loader) CopyAttributes(src Sym, dst Sym) {
2398 l.SetAttrReachable(dst, l.AttrReachable(src))
2399 l.SetAttrOnList(dst, l.AttrOnList(src))
2400 l.SetAttrLocal(dst, l.AttrLocal(src))
2401 l.SetAttrNotInSymbolTable(dst, l.AttrNotInSymbolTable(src))
2402 if l.IsExternal(dst) {
2403 l.SetAttrVisibilityHidden(dst, l.AttrVisibilityHidden(src))
2404 l.SetAttrDuplicateOK(dst, l.AttrDuplicateOK(src))
2405 l.SetAttrShared(dst, l.AttrShared(src))
2406 l.SetAttrExternal(dst, l.AttrExternal(src))
2408 // Some attributes are modifiable only for external symbols.
2409 // In such cases, don't try to transfer over the attribute
2410 // from the source even if there is a clash. This comes up
2411 // when copying attributes from a dupOK ABI wrapper symbol to
2412 // the real target symbol (which may not be marked dupOK).
2414 l.SetAttrTopFrame(dst, l.AttrTopFrame(src))
2415 l.SetAttrSpecial(dst, l.AttrSpecial(src))
2416 l.SetAttrCgoExportDynamic(dst, l.AttrCgoExportDynamic(src))
2417 l.SetAttrCgoExportStatic(dst, l.AttrCgoExportStatic(src))
2418 l.SetAttrReadOnly(dst, l.AttrReadOnly(src))
2421 // CreateExtSym creates a new external symbol with the specified name
2422 // without adding it to any lookup tables, returning a Sym index for it.
2423 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2424 return l.newExtSym(name, ver)
2427 // CreateStaticSym creates a new static symbol with the specified name
2428 // without adding it to any lookup tables, returning a Sym index for it.
2429 func (l *Loader) CreateStaticSym(name string) Sym {
2430 // Assign a new unique negative version -- this is to mark the
2431 // symbol so that it is not included in the name lookup table.
2433 return l.newExtSym(name, l.anonVersion)
2436 func (l *Loader) FreeSym(i Sym) {
2437 if l.IsExternal(i) {
2438 pp := l.getPayload(i)
2439 *pp = extSymPayload{}
2443 // relocId is essentially a <S,R> tuple identifying the Rth
2444 // relocation of symbol S.
2445 type relocId struct {
2450 // SetRelocVariant sets the 'variant' property of a relocation on
2451 // some specific symbol.
2452 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2454 if relocs := l.Relocs(s); ri >= relocs.Count() {
2455 panic("invalid relocation ID")
2457 if l.relocVariant == nil {
2458 l.relocVariant = make(map[relocId]sym.RelocVariant)
2461 l.relocVariant[relocId{s, ri}] = v
2463 delete(l.relocVariant, relocId{s, ri})
2467 // RelocVariant returns the 'variant' property of a relocation on
2468 // some specific symbol.
2469 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2470 return l.relocVariant[relocId{s, ri}]
2473 // UndefinedRelocTargets iterates through the global symbol index
2474 // space, looking for symbols with relocations targeting undefined
2475 // references. The linker's loadlib method uses this to determine if
2476 // there are unresolved references to functions in system libraries
2477 // (for example, libgcc.a), presumably due to CGO code. Return
2478 // value is a list of loader.Sym's corresponding to the undefined
2479 // cross-refs. The "limit" param controls the maximum number of
2480 // results returned; if "limit" is -1, then all undefs are returned.
2481 func (l *Loader) UndefinedRelocTargets(limit int) []Sym {
2483 for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2484 relocs := l.Relocs(si)
2485 for ri := 0; ri < relocs.Count(); ri++ {
2488 if rs != 0 && l.SymType(rs) == sym.SXREF && l.RawSymName(rs) != ".got" {
2489 result = append(result, rs)
2490 if limit != -1 && len(result) >= limit {
2499 // AssignTextSymbolOrder populates the Textp slices within each
2500 // library and compilation unit, insuring that packages are laid down
2501 // in dependency order (internal first, then everything else). Return value
2502 // is a slice of all text syms.
2503 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2505 // Library Textp lists should be empty at this point.
2506 for _, lib := range libs {
2507 if len(lib.Textp) != 0 {
2508 panic("expected empty Textp slice for library")
2510 if len(lib.DupTextSyms) != 0 {
2511 panic("expected empty DupTextSyms slice for library")
2515 // Used to record which dupok symbol we've assigned to a unit.
2516 // Can't use the onlist attribute here because it will need to
2517 // clear for the later assignment of the sym.Symbol to a unit.
2518 // NB: we can convert to using onList once we no longer have to
2519 // call the regular addToTextp.
2520 assignedToUnit := MakeBitmap(l.NSym() + 1)
2522 // Start off textp with reachable external syms.
2524 for _, sym := range extsyms {
2525 if !l.attrReachable.Has(sym) {
2528 textp = append(textp, sym)
2531 // Walk through all text symbols from Go object files and append
2532 // them to their corresponding library's textp list.
2533 for _, o := range l.objs[goObjStart:] {
2536 for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
2537 gi := l.toGlobal(r, i)
2538 if !l.attrReachable.Has(gi) {
2542 st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2543 if st != sym.STEXT {
2546 dupok := osym.Dupok()
2547 if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2548 // A dupok text symbol is resolved to another package.
2549 // We still need to record its presence in the current
2550 // package, as the trampoline pass expects packages
2551 // are laid out in dependency order.
2552 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2553 continue // symbol in different object
2556 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2560 lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2564 // Now assemble global textp, and assign text symbols to units.
2565 for _, doInternal := range [2]bool{true, false} {
2566 for idx, lib := range libs {
2567 if intlibs[idx] != doInternal {
2570 lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2571 for i, list := range lists {
2572 for _, s := range list {
2574 if l.attrReachable.Has(sym) && !assignedToUnit.Has(sym) {
2575 textp = append(textp, sym)
2576 unit := l.SymUnit(sym)
2578 unit.Textp = append(unit.Textp, s)
2579 assignedToUnit.Set(sym)
2581 // Dupok symbols may be defined in multiple packages; the
2582 // associated package for a dupok sym is chosen sort of
2583 // arbitrarily (the first containing package that the linker
2584 // loads). Canonicalizes its Pkg to the package with which
2585 // it will be laid down in text.
2586 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2587 l.SetSymPkg(sym, lib.Pkg)
2593 lib.DupTextSyms = nil
2600 // ErrorReporter is a helper class for reporting errors.
2601 type ErrorReporter struct {
2603 AfterErrorAction func()
2606 // Errorf method logs an error message.
2608 // After each error, the error actions function will be invoked; this
2609 // will either terminate the link immediately (if -h option given)
2610 // or it will keep a count and exit if more than 20 errors have been printed.
2612 // Logging an error means that on exit cmd/link will delete any
2613 // output file and return a non-zero error code.
2615 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2616 if s != 0 && reporter.ldr.SymName(s) != "" {
2617 format = reporter.ldr.SymName(s) + ": " + format
2619 format = fmt.Sprintf("sym %d: %s", s, format)
2622 fmt.Fprintf(os.Stderr, format, args...)
2623 reporter.AfterErrorAction()
2626 // GetErrorReporter returns the loader's associated error reporter.
2627 func (l *Loader) GetErrorReporter() *ErrorReporter {
2628 return l.errorReporter
2631 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2632 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2633 l.errorReporter.Errorf(s, format, args...)
2636 // Symbol statistics.
2637 func (l *Loader) Stat() string {
2638 s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
2639 s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
2640 l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
2645 func (l *Loader) Dump() {
2647 for _, obj := range l.objs[goObjStart:] {
2649 fmt.Println(obj.i, obj.r.unit.Lib)
2652 fmt.Println("extStart:", l.extStart)
2653 fmt.Println("Nsyms:", len(l.objSyms))
2655 for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2657 if l.IsExternal(i) {
2658 pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2661 if l.SymSect(i) != nil {
2662 sect = l.SymSect(i).Name
2664 fmt.Printf("%v %v %v %v %x %v\n", i, l.SymName(i), l.SymType(i), pi, l.SymValue(i), sect)
2666 fmt.Println("symsByName")
2667 for name, i := range l.symsByName[0] {
2668 fmt.Println(i, name, 0)
2670 for name, i := range l.symsByName[1] {
2671 fmt.Println(i, name, 1)
2673 fmt.Println("payloads:")
2674 for i := range l.payloads {
2676 fmt.Println(i, pp.name, pp.ver, pp.kind)