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"
27 // Sym encapsulates a global symbol index, used to identify a specific
28 // Go symbol. The 0-valued Sym is corresponds to an invalid symbol.
31 // Relocs encapsulates the set of relocations on a given symbol; an
32 // instance of this type is returned by the Loader Relocs() method.
36 li uint32 // local index of symbol whose relocs we're examining
37 r *oReader // object reader for containing package
41 // ExtReloc contains the payload for an external relocation.
42 type ExtReloc struct {
49 // Reloc holds a "handle" to access a relocation record from an
57 func (rel Reloc) Type() objabi.RelocType { return objabi.RelocType(rel.Reloc.Type()) &^ objabi.R_WEAK }
58 func (rel Reloc) Weak() bool { return objabi.RelocType(rel.Reloc.Type())&objabi.R_WEAK != 0 }
59 func (rel Reloc) SetType(t objabi.RelocType) { rel.Reloc.SetType(uint16(t)) }
60 func (rel Reloc) Sym() Sym { return rel.l.resolve(rel.r, rel.Reloc.Sym()) }
61 func (rel Reloc) SetSym(s Sym) { rel.Reloc.SetSym(goobj.SymRef{PkgIdx: 0, SymIdx: uint32(s)}) }
62 func (rel Reloc) IsMarker() bool { return rel.Siz() == 0 }
64 // Aux holds a "handle" to access an aux symbol record from an
72 func (a Aux) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
74 // oReader is a wrapper type of obj.Reader, along with some
78 unit *sym.CompilationUnit
79 version int // version of static symbol
81 syms []Sym // Sym's global index, indexed by local index
82 pkg []uint32 // indices of referenced package by PkgIdx (index into loader.objs array)
83 ndef int // cache goobj.Reader.NSym()
84 nhashed64def int // cache goobj.Reader.NHashed64Def()
85 nhasheddef int // cache goobj.Reader.NHashedDef()
86 objidx uint32 // index of this reader in the objs slice
89 // Total number of defined symbols (package symbols, hashed symbols, and
90 // non-package symbols).
91 func (r *oReader) NAlldef() int { return r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef() }
98 // objSym represents a symbol in an object file. It is a tuple of
99 // the object and the symbol's local index.
100 // For external symbols, objidx is the index of l.extReader (extObj),
101 // s is its index into the payload array.
102 // {0, 0} represents the nil symbol.
104 objidx uint32 // index of the object (in l.objs array)
105 s uint32 // local index
108 type nameVer struct {
116 func (bm Bitmap) Set(i Sym) {
117 n, r := uint(i)/32, uint(i)%32
121 // unset the i-th bit.
122 func (bm Bitmap) Unset(i Sym) {
123 n, r := uint(i)/32, uint(i)%32
127 // whether the i-th bit is set.
128 func (bm Bitmap) Has(i Sym) bool {
129 n, r := uint(i)/32, uint(i)%32
130 return bm[n]&(1<<r) != 0
133 // return current length of bitmap in bits.
134 func (bm Bitmap) Len() int {
138 // return the number of bits set.
139 func (bm Bitmap) Count() int {
141 for _, x := range bm {
142 s += bits.OnesCount32(x)
147 func MakeBitmap(n int) Bitmap {
148 return make(Bitmap, (n+31)/32)
151 // growBitmap insures that the specified bitmap has enough capacity,
152 // reallocating (doubling the size) if needed.
153 func growBitmap(reqLen int, b Bitmap) Bitmap {
156 b = append(b, MakeBitmap(reqLen+1-curLen)...)
161 type symAndSize struct {
166 // A Loader loads new object files and resolves indexed symbol references.
168 // Notes on the layout of global symbol index space:
170 // - Go object files are read before host object files; each Go object
171 // read adds its defined package symbols to the global index space.
172 // Nonpackage symbols are not yet added.
174 // - In loader.LoadNonpkgSyms, add non-package defined symbols and
175 // references in all object files to the global index space.
177 // - Host object file loading happens; the host object loader does a
178 // name/version lookup for each symbol it finds; this can wind up
179 // extending the external symbol index space range. The host object
180 // loader stores symbol payloads in loader.payloads using SymbolBuilder.
182 // - Each symbol gets a unique global index. For duplicated and
183 // overwriting/overwritten symbols, the second (or later) appearance
184 // of the symbol gets the same global index as the first appearance.
186 start map[*oReader]Sym // map from object file to its start index
187 objs []objIdx // sorted by start index (i.e. objIdx.i)
188 extStart Sym // from this index on, the symbols are externally defined
189 builtinSyms []Sym // global index of builtin symbols
191 objSyms []objSym // global index mapping to local index
193 symsByName [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
194 extStaticSyms map[nameVer]Sym // externally defined static symbols, keyed by name
196 extReader *oReader // a dummy oReader, for external symbols
197 payloadBatch []extSymPayload
198 payloads []*extSymPayload // contents of linker-materialized external syms
199 values []int64 // symbol values, indexed by global sym index
201 sects []*sym.Section // sections
202 symSects []uint16 // symbol's section, index to sects array
204 align []uint8 // symbol 2^N alignment, indexed by global index
206 deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
208 objByPkg map[string]uint32 // map package path to the index of its Go object reader
210 anonVersion int // most recently assigned ext static sym pseudo-version
212 // Bitmaps and other side structures used to store data used to store
213 // symbol flags/attributes; these are to be accessed via the
214 // corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
215 // visit the comments on these methods for more details on the
216 // semantics / interpretation of the specific flags or attribute.
217 attrReachable Bitmap // reachable symbols, indexed by global index
218 attrOnList Bitmap // "on list" symbols, indexed by global index
219 attrLocal Bitmap // "local" symbols, indexed by global index
220 attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by global idx
221 attrUsedInIface Bitmap // "used in interface" symbols, indexed by global idx
222 attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
223 attrDuplicateOK Bitmap // dupOK symbols, indexed by ext sym index
224 attrShared Bitmap // shared symbols, indexed by ext sym index
225 attrExternal Bitmap // external symbols, indexed by ext sym index
227 attrReadOnly map[Sym]bool // readonly data for this sym
228 attrSpecial map[Sym]struct{} // "special" frame symbols
229 attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
230 attrCgoExportStatic map[Sym]struct{} // "cgo_export_static" symbols
231 generatedSyms map[Sym]struct{} // symbols that generate their content
233 // Outer and Sub relations for symbols.
234 // TODO: figure out whether it's more efficient to just have these
235 // as fields on extSymPayload (note that this won't be a viable
236 // strategy if somewhere in the linker we set sub/outer for a
237 // non-external sym).
241 dynimplib map[Sym]string // stores Dynimplib symbol attribute
242 dynimpvers map[Sym]string // stores Dynimpvers symbol attribute
243 localentry map[Sym]uint8 // stores Localentry symbol attribute
244 extname map[Sym]string // stores Extname symbol attribute
245 elfType map[Sym]elf.SymType // stores elf type symbol property
246 elfSym map[Sym]int32 // stores elf sym symbol property
247 localElfSym map[Sym]int32 // stores "local" elf sym symbol property
248 symPkg map[Sym]string // stores package for symbol, or library for shlib-derived syms
249 plt map[Sym]int32 // stores dynimport for pe objects
250 got map[Sym]int32 // stores got for pe objects
251 dynid map[Sym]int32 // stores Dynid for symbol
253 relocVariant map[relocId]sym.RelocVariant // stores variant relocs
255 // Used to implement field tracking; created during deadcode if
256 // field tracking is enabled. Reachparent[K] contains the index of
257 // the symbol that triggered the marking of symbol K as live.
260 // CgoExports records cgo-exported symbols by SymName.
261 CgoExports map[string]Sym
265 strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
267 elfsetstring elfsetstringFunc
269 errorReporter *ErrorReporter
271 npkgsyms int // number of package symbols, for accounting
272 nhashedsyms int // number of hashed symbols, for accounting
290 type elfsetstringFunc func(str string, off int)
292 // extSymPayload holds the payload (data + relocations) for linker-synthesized
293 // external symbols (note that symbol value is stored in a separate slice).
294 type extSymPayload struct {
295 name string // TODO: would this be better as offset into str table?
299 objidx uint32 // index of original object if sym made by cloneToExternal
307 FlagStrictDups = 1 << iota
310 func NewLoader(flags uint32, elfsetstring elfsetstringFunc, reporter *ErrorReporter) *Loader {
311 nbuiltin := goobj.NBuiltin()
312 extReader := &oReader{objidx: extObj}
314 start: make(map[*oReader]Sym),
315 objs: []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
316 objSyms: make([]objSym, 1, 1), // This will get overwritten later.
317 extReader: extReader,
318 symsByName: [2]map[string]Sym{make(map[string]Sym, 80000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
319 objByPkg: make(map[string]uint32),
320 outer: make(map[Sym]Sym),
321 sub: make(map[Sym]Sym),
322 dynimplib: make(map[Sym]string),
323 dynimpvers: make(map[Sym]string),
324 localentry: make(map[Sym]uint8),
325 extname: make(map[Sym]string),
326 attrReadOnly: make(map[Sym]bool),
327 elfType: make(map[Sym]elf.SymType),
328 elfSym: make(map[Sym]int32),
329 localElfSym: make(map[Sym]int32),
330 symPkg: make(map[Sym]string),
331 plt: make(map[Sym]int32),
332 got: make(map[Sym]int32),
333 dynid: make(map[Sym]int32),
334 attrSpecial: make(map[Sym]struct{}),
335 attrCgoExportDynamic: make(map[Sym]struct{}),
336 attrCgoExportStatic: make(map[Sym]struct{}),
337 generatedSyms: make(map[Sym]struct{}),
338 deferReturnTramp: make(map[Sym]bool),
339 extStaticSyms: make(map[nameVer]Sym),
340 builtinSyms: make([]Sym, nbuiltin),
342 elfsetstring: elfsetstring,
343 errorReporter: reporter,
344 sects: []*sym.Section{nil}, // reserve index 0 for nil section
350 // Add object file r, return the start index.
351 func (l *Loader) addObj(pkg string, r *oReader) Sym {
352 if _, ok := l.start[r]; ok {
353 panic("already added")
355 pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
356 if _, ok := l.objByPkg[pkg]; !ok {
357 l.objByPkg[pkg] = r.objidx
359 i := Sym(len(l.objSyms))
361 l.objs = append(l.objs, objIdx{r, i})
365 // Add a symbol from an object file, return the global index.
366 // If the symbol already exist, it returns the index of that symbol.
367 func (st *loadState) addSym(name string, ver int, r *oReader, li uint32, kind int, osym *goobj.Sym) Sym {
370 panic("addSym called after external symbol is created")
372 i := Sym(len(l.objSyms))
373 addToGlobal := func() {
374 l.objSyms = append(l.objSyms, objSym{r.objidx, li})
376 if name == "" && kind != hashed64Def && kind != hashedDef {
378 return i // unnamed aux symbol
380 if ver == r.version {
381 // Static symbol. Add its global index but don't
382 // add to name lookup table, as it cannot be
383 // referenced by name.
389 // Defined package symbols cannot be dup to each other.
390 // We load all the package symbols first, so we don't need
391 // to check dup here.
392 // We still add it to the lookup table, as it may still be
393 // referenced by name (e.g. through linkname).
394 l.symsByName[ver][name] = i
397 case hashed64Def, hashedDef:
398 // Hashed (content-addressable) symbol. Check the hash
399 // but don't add to name lookup table, as they are not
400 // referenced by name. Also no need to do overwriting
401 // check, as same hash indicates same content.
402 var checkHash func() (symAndSize, bool)
403 var addToHashMap func(symAndSize)
404 var h64 uint64 // only used for hashed64Def
405 var h *goobj.HashType // only used for hashedDef
406 if kind == hashed64Def {
407 checkHash = func() (symAndSize, bool) {
408 h64 = r.Hash64(li - uint32(r.ndef))
409 s, existed := st.hashed64Syms[h64]
412 addToHashMap = func(ss symAndSize) { st.hashed64Syms[h64] = ss }
414 checkHash = func() (symAndSize, bool) {
415 h = r.Hash(li - uint32(r.ndef+r.nhashed64def))
416 s, existed := st.hashedSyms[*h]
419 addToHashMap = func(ss symAndSize) { st.hashedSyms[*h] = ss }
422 if s, existed := checkHash(); existed {
423 // The content hash is built from symbol data and relocations. In the
424 // object file, the symbol data may not always contain trailing zeros,
425 // e.g. for [5]int{1,2,3} and [100]int{1,2,3}, the data is same
426 // (although the size is different).
427 // Also, for short symbols, the content hash is the identity function of
428 // the 8 bytes, and trailing zeros doesn't change the hash value, e.g.
429 // hash("A") == hash("A\0\0\0").
430 // So when two symbols have the same hash, we need to use the one with
433 // New symbol has larger size, use the new one. Rewrite the index mapping.
434 l.objSyms[s.sym] = objSym{r.objidx, li}
435 addToHashMap(symAndSize{s.sym, siz})
439 addToHashMap(symAndSize{i, siz})
444 // Non-package (named) symbol. Check if it already exists.
445 oldi, existed := l.symsByName[ver][name]
447 l.symsByName[ver][name] = i
451 // symbol already exists
453 if l.flags&FlagStrictDups != 0 {
454 l.checkdup(name, r, li, oldi)
456 // Fix for issue #47185 -- given two dupok symbols with
457 // different sizes, favor symbol with larger size. See
458 // also issue #46653.
459 szdup := l.SymSize(oldi)
460 sz := int64(r.Sym(li).Siz())
462 // new symbol overwrites old symbol.
463 l.objSyms[oldi] = objSym{r.objidx, li}
467 oldr, oldli := l.toLocal(oldi)
468 oldsym := oldr.Sym(oldli)
472 overwrite := r.DataSize(li) != 0
474 // new symbol overwrites old symbol.
475 oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
476 if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
477 log.Fatalf("duplicated definition of symbol %s, from %s and %s", name, r.unit.Lib.Pkg, oldr.unit.Lib.Pkg)
479 l.objSyms[oldi] = objSym{r.objidx, li}
481 // old symbol overwrites new symbol.
482 typ := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
483 if !typ.IsData() { // only allow overwriting data symbol
484 log.Fatalf("duplicated definition of symbol %s, from %s and %s", name, r.unit.Lib.Pkg, oldr.unit.Lib.Pkg)
490 // newExtSym creates a new external sym with the specified
492 func (l *Loader) newExtSym(name string, ver int) Sym {
493 i := Sym(len(l.objSyms))
497 l.growValues(int(i) + 1)
498 l.growAttrBitmaps(int(i) + 1)
499 pi := l.newPayload(name, ver)
500 l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
501 l.extReader.syms = append(l.extReader.syms, i)
505 // LookupOrCreateSym looks up the symbol with the specified name/version,
506 // returning its Sym index if found. If the lookup fails, a new external
507 // Sym will be created, entered into the lookup tables, and returned.
508 func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
509 i := l.Lookup(name, ver)
513 i = l.newExtSym(name, ver)
514 static := ver >= sym.SymVerStatic || ver < 0
516 l.extStaticSyms[nameVer{name, ver}] = i
518 l.symsByName[ver][name] = i
523 // AddCgoExport records a cgo-exported symbol in l.CgoExports.
524 // This table is used to identify the correct Go symbol ABI to use
525 // to resolve references from host objects (which don't have ABIs).
526 func (l *Loader) AddCgoExport(s Sym) {
527 if l.CgoExports == nil {
528 l.CgoExports = make(map[string]Sym)
530 l.CgoExports[l.SymName(s)] = s
533 // LookupOrCreateCgoExport is like LookupOrCreateSym, but if ver
534 // indicates a global symbol, it uses the CgoExport table to determine
535 // the appropriate symbol version (ABI) to use. ver must be either 0
536 // or a static symbol version.
537 func (l *Loader) LookupOrCreateCgoExport(name string, ver int) Sym {
538 if ver >= sym.SymVerStatic {
539 return l.LookupOrCreateSym(name, ver)
542 panic("ver must be 0 or a static version")
544 // Look for a cgo-exported symbol from Go.
545 if s, ok := l.CgoExports[name]; ok {
548 // Otherwise, this must just be a symbol in the host object.
549 // Create a version 0 symbol for it.
550 return l.LookupOrCreateSym(name, 0)
553 func (l *Loader) IsExternal(i Sym) bool {
555 return l.isExtReader(r)
558 func (l *Loader) isExtReader(r *oReader) bool {
559 return r == l.extReader
562 // For external symbol, return its index in the payloads array.
563 // XXX result is actually not a global index. We (ab)use the Sym type
564 // so we don't need conversion for accessing bitmaps.
565 func (l *Loader) extIndex(i Sym) Sym {
566 _, li := l.toLocal(i)
570 // Get a new payload for external symbol, return its index in
571 // the payloads array.
572 func (l *Loader) newPayload(name string, ver int) int {
573 pi := len(l.payloads)
574 pp := l.allocPayload()
577 l.payloads = append(l.payloads, pp)
578 l.growExtAttrBitmaps()
582 // getPayload returns a pointer to the extSymPayload struct for an
583 // external symbol if the symbol has a payload. Will panic if the
584 // symbol in question is bogus (zero or not an external sym).
585 func (l *Loader) getPayload(i Sym) *extSymPayload {
586 if !l.IsExternal(i) {
587 panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
590 return l.payloads[pi]
593 // allocPayload allocates a new payload.
594 func (l *Loader) allocPayload() *extSymPayload {
595 batch := l.payloadBatch
597 batch = make([]extSymPayload, 1000)
600 l.payloadBatch = batch[1:]
604 func (ms *extSymPayload) Grow(siz int64) {
605 if int64(int(siz)) != siz {
606 log.Fatalf("symgrow size %d too long", siz)
608 if int64(len(ms.data)) >= siz {
611 if cap(ms.data) < int(siz) {
613 ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
614 ms.data = ms.data[0:cl]
616 ms.data = ms.data[:siz]
619 // Convert a local index to a global index.
620 func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
624 // Convert a global index to a local index.
625 func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
626 return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
629 // Resolve a local symbol reference. Return global index.
630 func (l *Loader) resolve(r *oReader, s goobj.SymRef) Sym {
632 switch p := s.PkgIdx; p {
633 case goobj.PkgIdxInvalid:
634 // {0, X} with non-zero X is never a valid sym reference from a Go object.
635 // We steal this space for symbol references from external objects.
636 // In this case, X is just the global index.
637 if l.isExtReader(r) {
644 case goobj.PkgIdxHashed64:
645 i := int(s.SymIdx) + r.ndef
647 case goobj.PkgIdxHashed:
648 i := int(s.SymIdx) + r.ndef + r.nhashed64def
650 case goobj.PkgIdxNone:
651 i := int(s.SymIdx) + r.ndef + r.nhashed64def + r.nhasheddef
653 case goobj.PkgIdxBuiltin:
654 if bi := l.builtinSyms[s.SymIdx]; bi != 0 {
657 l.reportMissingBuiltin(int(s.SymIdx), r.unit.Lib.Pkg)
659 case goobj.PkgIdxSelf:
662 rr = l.objs[r.pkg[p]].r
664 return l.toGlobal(rr, s.SymIdx)
667 // reportMissingBuiltin issues an error in the case where we have a
668 // relocation against a runtime builtin whose definition is not found
669 // when the runtime package is built. The canonical example is
670 // "runtime.racefuncenter" -- currently if you do something like
672 // go build -gcflags=-race myprogram.go
674 // the compiler will insert calls to the builtin runtime.racefuncenter,
675 // but the version of the runtime used for linkage won't actually contain
676 // definitions of that symbol. See issue #42396 for details.
678 // As currently implemented, this is a fatal error. This has drawbacks
679 // in that if there are multiple missing builtins, the error will only
680 // cite the first one. On the plus side, terminating the link here has
681 // advantages in that we won't run the risk of panics or crashes later
682 // on in the linker due to R_CALL relocations with 0-valued target
684 func (l *Loader) reportMissingBuiltin(bsym int, reflib string) {
685 bname, _ := goobj.BuiltinName(bsym)
686 log.Fatalf("reference to undefined builtin %q from package %q",
690 // Look up a symbol by name, return global index, or 0 if not found.
691 // This is more like Syms.ROLookup than Lookup -- it doesn't create
693 func (l *Loader) Lookup(name string, ver int) Sym {
694 if ver >= sym.SymVerStatic || ver < 0 {
695 return l.extStaticSyms[nameVer{name, ver}]
697 return l.symsByName[ver][name]
700 // Check that duplicate symbols have same contents.
701 func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
703 rdup, ldup := l.toLocal(dup)
704 pdup := rdup.Data(ldup)
705 reason := "same length but different contents"
706 if len(p) != len(pdup) {
707 reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
708 } else if bytes.Equal(p, pdup) {
709 // For BSS symbols, we need to check size as well, see issue 46653.
710 szdup := l.SymSize(dup)
711 sz := int64(r.Sym(li).Siz())
715 reason = fmt.Sprintf("different sizes: new size %d != old size %d",
718 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)
720 // For the moment, allow DWARF subprogram DIEs for
721 // auto-generated wrapper functions. What seems to happen
722 // here is that we get different line numbers on formal
723 // params; I am guessing that the pos is being inherited
724 // from the spot where the wrapper is needed.
725 allowed := strings.HasPrefix(name, "go:info.go.interface") ||
726 strings.HasPrefix(name, "go:info.go.builtin") ||
727 strings.HasPrefix(name, "go:debuglines")
733 func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
735 // Number of total symbols.
736 func (l *Loader) NSym() int {
737 return len(l.objSyms)
740 // Number of defined Go symbols.
741 func (l *Loader) NDef() int {
742 return int(l.extStart)
745 // Number of reachable symbols.
746 func (l *Loader) NReachableSym() int {
747 return l.attrReachable.Count()
750 // Returns the name of the i-th symbol.
751 func (l *Loader) SymName(i Sym) string {
753 pp := l.getPayload(i)
756 r, li := l.toLocal(i)
760 return r.Sym(li).Name(r.Reader)
763 // Returns the version of the i-th symbol.
764 func (l *Loader) SymVersion(i Sym) int {
766 pp := l.getPayload(i)
769 r, li := l.toLocal(i)
770 return int(abiToVer(r.Sym(li).ABI(), r.version))
773 func (l *Loader) IsFileLocal(i Sym) bool {
774 return l.SymVersion(i) >= sym.SymVerStatic
777 // IsFromAssembly returns true if this symbol is derived from an
778 // object file generated by the Go assembler.
779 func (l *Loader) IsFromAssembly(i Sym) bool {
784 return r.FromAssembly()
787 // Returns the type of the i-th symbol.
788 func (l *Loader) SymType(i Sym) sym.SymKind {
790 pp := l.getPayload(i)
796 r, li := l.toLocal(i)
797 return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
800 // Returns the attributes of the i-th symbol.
801 func (l *Loader) SymAttr(i Sym) uint8 {
803 // TODO: do something? External symbols have different representation of attributes.
804 // For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
805 // set by external symbol.
808 r, li := l.toLocal(i)
809 return r.Sym(li).Flag()
812 // Returns the size of the i-th symbol.
813 func (l *Loader) SymSize(i Sym) int64 {
815 pp := l.getPayload(i)
818 r, li := l.toLocal(i)
819 return int64(r.Sym(li).Siz())
822 // AttrReachable returns true for symbols that are transitively
823 // referenced from the entry points. Unreachable symbols are not
824 // written to the output.
825 func (l *Loader) AttrReachable(i Sym) bool {
826 return l.attrReachable.Has(i)
829 // SetAttrReachable sets the reachability property for a symbol (see
831 func (l *Loader) SetAttrReachable(i Sym, v bool) {
833 l.attrReachable.Set(i)
835 l.attrReachable.Unset(i)
839 // AttrOnList returns true for symbols that are on some list (such as
840 // the list of all text symbols, or one of the lists of data symbols)
841 // and is consulted to avoid bugs where a symbol is put on a list
843 func (l *Loader) AttrOnList(i Sym) bool {
844 return l.attrOnList.Has(i)
847 // SetAttrOnList sets the "on list" property for a symbol (see
849 func (l *Loader) SetAttrOnList(i Sym, v bool) {
853 l.attrOnList.Unset(i)
857 // AttrLocal returns true for symbols that are only visible within the
858 // module (executable or shared library) being linked. This attribute
859 // is applied to thunks and certain other linker-generated symbols.
860 func (l *Loader) AttrLocal(i Sym) bool {
861 return l.attrLocal.Has(i)
864 // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
865 func (l *Loader) SetAttrLocal(i Sym, v bool) {
873 // AttrUsedInIface returns true for a type symbol that is used in
875 func (l *Loader) AttrUsedInIface(i Sym) bool {
876 return l.attrUsedInIface.Has(i)
879 func (l *Loader) SetAttrUsedInIface(i Sym, v bool) {
881 l.attrUsedInIface.Set(i)
883 l.attrUsedInIface.Unset(i)
887 // SymAddr checks that a symbol is reachable, and returns its value.
888 func (l *Loader) SymAddr(i Sym) int64 {
889 if !l.AttrReachable(i) {
890 panic("unreachable symbol in symaddr")
895 // AttrNotInSymbolTable returns true for symbols that should not be
896 // added to the symbol table of the final generated load module.
897 func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
898 return l.attrNotInSymbolTable.Has(i)
901 // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
902 // (see AttrNotInSymbolTable above).
903 func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
905 l.attrNotInSymbolTable.Set(i)
907 l.attrNotInSymbolTable.Unset(i)
911 // AttrVisibilityHidden symbols returns true for ELF symbols with
912 // visibility set to STV_HIDDEN. They become local symbols in
913 // the final executable. Only relevant when internally linking
914 // on an ELF platform.
915 func (l *Loader) AttrVisibilityHidden(i Sym) bool {
916 if !l.IsExternal(i) {
919 return l.attrVisibilityHidden.Has(l.extIndex(i))
922 // SetAttrVisibilityHidden sets the "hidden visibility" property for a
923 // symbol (see AttrVisibilityHidden).
924 func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
925 if !l.IsExternal(i) {
926 panic("tried to set visibility attr on non-external symbol")
929 l.attrVisibilityHidden.Set(l.extIndex(i))
931 l.attrVisibilityHidden.Unset(l.extIndex(i))
935 // AttrDuplicateOK returns true for a symbol that can be present in
936 // multiple object files.
937 func (l *Loader) AttrDuplicateOK(i Sym) bool {
938 if !l.IsExternal(i) {
939 // TODO: if this path winds up being taken frequently, it
940 // might make more sense to copy the flag value out of the object
941 // into a larger bitmap during preload.
942 r, li := l.toLocal(i)
943 return r.Sym(li).Dupok()
945 return l.attrDuplicateOK.Has(l.extIndex(i))
948 // SetAttrDuplicateOK sets the "duplicate OK" property for an external
949 // symbol (see AttrDuplicateOK).
950 func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
951 if !l.IsExternal(i) {
952 panic("tried to set dupok attr on non-external symbol")
955 l.attrDuplicateOK.Set(l.extIndex(i))
957 l.attrDuplicateOK.Unset(l.extIndex(i))
961 // AttrShared returns true for symbols compiled with the -shared option.
962 func (l *Loader) AttrShared(i Sym) bool {
963 if !l.IsExternal(i) {
964 // TODO: if this path winds up being taken frequently, it
965 // might make more sense to copy the flag value out of the
966 // object into a larger bitmap during preload.
970 return l.attrShared.Has(l.extIndex(i))
973 // SetAttrShared sets the "shared" property for an external
974 // symbol (see AttrShared).
975 func (l *Loader) SetAttrShared(i Sym, v bool) {
976 if !l.IsExternal(i) {
977 panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
980 l.attrShared.Set(l.extIndex(i))
982 l.attrShared.Unset(l.extIndex(i))
986 // AttrExternal returns true for function symbols loaded from host
988 func (l *Loader) AttrExternal(i Sym) bool {
989 if !l.IsExternal(i) {
992 return l.attrExternal.Has(l.extIndex(i))
995 // SetAttrExternal sets the "external" property for an host object
996 // symbol (see AttrExternal).
997 func (l *Loader) SetAttrExternal(i Sym, v bool) {
998 if !l.IsExternal(i) {
999 panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.SymName(i)))
1002 l.attrExternal.Set(l.extIndex(i))
1004 l.attrExternal.Unset(l.extIndex(i))
1008 // AttrSpecial returns true for a symbols that do not have their
1009 // address (i.e. Value) computed by the usual mechanism of
1010 // data.go:dodata() & data.go:address().
1011 func (l *Loader) AttrSpecial(i Sym) bool {
1012 _, ok := l.attrSpecial[i]
1016 // SetAttrSpecial sets the "special" property for a symbol (see
1018 func (l *Loader) SetAttrSpecial(i Sym, v bool) {
1020 l.attrSpecial[i] = struct{}{}
1022 delete(l.attrSpecial, i)
1026 // AttrCgoExportDynamic returns true for a symbol that has been
1027 // specially marked via the "cgo_export_dynamic" compiler directive
1028 // written by cgo (in response to //export directives in the source).
1029 func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
1030 _, ok := l.attrCgoExportDynamic[i]
1034 // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
1035 // (see AttrCgoExportDynamic).
1036 func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
1038 l.attrCgoExportDynamic[i] = struct{}{}
1040 delete(l.attrCgoExportDynamic, i)
1044 // ForAllAttrCgoExportDynamic calls f for every symbol that has been
1045 // marked with the "cgo_export_dynamic" compiler directive.
1046 func (l *Loader) ForAllCgoExportDynamic(f func(Sym)) {
1047 for s := range l.attrCgoExportDynamic {
1052 // AttrCgoExportStatic returns true for a symbol that has been
1053 // specially marked via the "cgo_export_static" directive
1055 func (l *Loader) AttrCgoExportStatic(i Sym) bool {
1056 _, ok := l.attrCgoExportStatic[i]
1060 // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
1061 // (see AttrCgoExportStatic).
1062 func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
1064 l.attrCgoExportStatic[i] = struct{}{}
1066 delete(l.attrCgoExportStatic, i)
1070 // IsGeneratedSym returns true if a symbol's been previously marked as a
1071 // generator symbol through the SetIsGeneratedSym. The functions for generator
1072 // symbols are kept in the Link context.
1073 func (l *Loader) IsGeneratedSym(i Sym) bool {
1074 _, ok := l.generatedSyms[i]
1078 // SetIsGeneratedSym marks symbols as generated symbols. Data shouldn't be
1079 // stored in generated symbols, and a function is registered and called for
1080 // each of these symbols.
1081 func (l *Loader) SetIsGeneratedSym(i Sym, v bool) {
1082 if !l.IsExternal(i) {
1083 panic("only external symbols can be generated")
1086 l.generatedSyms[i] = struct{}{}
1088 delete(l.generatedSyms, i)
1092 func (l *Loader) AttrCgoExport(i Sym) bool {
1093 return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
1096 // AttrReadOnly returns true for a symbol whose underlying data
1097 // is stored via a read-only mmap.
1098 func (l *Loader) AttrReadOnly(i Sym) bool {
1099 if v, ok := l.attrReadOnly[i]; ok {
1102 if l.IsExternal(i) {
1103 pp := l.getPayload(i)
1105 return l.objs[pp.objidx].r.ReadOnly()
1109 r, _ := l.toLocal(i)
1113 // SetAttrReadOnly sets the "data is read only" property for a symbol
1114 // (see AttrReadOnly).
1115 func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
1116 l.attrReadOnly[i] = v
1119 // AttrSubSymbol returns true for symbols that are listed as a
1120 // sub-symbol of some other outer symbol. The sub/outer mechanism is
1121 // used when loading host objects (sections from the host object
1122 // become regular linker symbols and symbols go on the Sub list of
1123 // their section) and for constructing the global offset table when
1124 // internally linking a dynamic executable.
1126 // Note that in later stages of the linker, we set Outer(S) to some
1127 // container symbol C, but don't set Sub(C). Thus we have two
1128 // distinct scenarios:
1130 // - Outer symbol covers the address ranges of its sub-symbols.
1131 // Outer.Sub is set in this case.
1132 // - Outer symbol doesn't conver the address ranges. It is zero-sized
1133 // and doesn't have sub-symbols. In the case, the inner symbol is
1134 // not actually a "SubSymbol". (Tricky!)
1136 // This method returns TRUE only for sub-symbols in the first scenario.
1138 // FIXME: would be better to do away with this and have a better way
1139 // to represent container symbols.
1141 func (l *Loader) AttrSubSymbol(i Sym) bool {
1142 // we don't explicitly store this attribute any more -- return
1143 // a value based on the sub-symbol setting.
1148 return l.SubSym(o) != 0
1151 // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
1152 // clients should instead use the AddInteriorSym method to establish
1153 // containment relationships for host object symbols.
1155 // Returns whether the i-th symbol has ReflectMethod attribute set.
1156 func (l *Loader) IsReflectMethod(i Sym) bool {
1157 return l.SymAttr(i)&goobj.SymFlagReflectMethod != 0
1160 // Returns whether the i-th symbol is nosplit.
1161 func (l *Loader) IsNoSplit(i Sym) bool {
1162 return l.SymAttr(i)&goobj.SymFlagNoSplit != 0
1165 // Returns whether this is a Go type symbol.
1166 func (l *Loader) IsGoType(i Sym) bool {
1167 return l.SymAttr(i)&goobj.SymFlagGoType != 0
1170 // Returns whether this symbol should be included in typelink.
1171 func (l *Loader) IsTypelink(i Sym) bool {
1172 return l.SymAttr(i)&goobj.SymFlagTypelink != 0
1175 // Returns whether this symbol is an itab symbol.
1176 func (l *Loader) IsItab(i Sym) bool {
1177 if l.IsExternal(i) {
1180 r, li := l.toLocal(i)
1181 return r.Sym(li).IsItab()
1184 // Returns whether this symbol is a dictionary symbol.
1185 func (l *Loader) IsDict(i Sym) bool {
1186 if l.IsExternal(i) {
1189 r, li := l.toLocal(i)
1190 return r.Sym(li).IsDict()
1193 // Returns whether this symbol is a compiler-generated package init func.
1194 func (l *Loader) IsPkgInit(i Sym) bool {
1195 if l.IsExternal(i) {
1198 r, li := l.toLocal(i)
1199 return r.Sym(li).IsPkgInit()
1202 // Return whether this is a trampoline of a deferreturn call.
1203 func (l *Loader) IsDeferReturnTramp(i Sym) bool {
1204 return l.deferReturnTramp[i]
1207 // Set that i is a trampoline of a deferreturn call.
1208 func (l *Loader) SetIsDeferReturnTramp(i Sym, v bool) {
1209 l.deferReturnTramp[i] = v
1212 // growValues grows the slice used to store symbol values.
1213 func (l *Loader) growValues(reqLen int) {
1214 curLen := len(l.values)
1215 if reqLen > curLen {
1216 l.values = append(l.values, make([]int64, reqLen+1-curLen)...)
1220 // SymValue returns the value of the i-th symbol. i is global index.
1221 func (l *Loader) SymValue(i Sym) int64 {
1225 // SetSymValue sets the value of the i-th symbol. i is global index.
1226 func (l *Loader) SetSymValue(i Sym, val int64) {
1230 // AddToSymValue adds to the value of the i-th symbol. i is the global index.
1231 func (l *Loader) AddToSymValue(i Sym, val int64) {
1235 // Returns the symbol content of the i-th symbol. i is global index.
1236 func (l *Loader) Data(i Sym) []byte {
1237 if l.IsExternal(i) {
1238 pp := l.getPayload(i)
1244 r, li := l.toLocal(i)
1248 // FreeData clears the symbol data of an external symbol, allowing the memory
1249 // to be freed earlier. No-op for non-external symbols.
1250 // i is global index.
1251 func (l *Loader) FreeData(i Sym) {
1252 if l.IsExternal(i) {
1253 pp := l.getPayload(i)
1260 // SymAlign returns the alignment for a symbol.
1261 func (l *Loader) SymAlign(i Sym) int32 {
1262 if int(i) >= len(l.align) {
1263 // align is extended lazily -- it the sym in question is
1264 // outside the range of the existing slice, then we assume its
1265 // alignment has not yet been set.
1268 // TODO: would it make sense to return an arch-specific
1269 // alignment depending on section type? E.g. STEXT => 32,
1275 return int32(1 << (abits - 1))
1278 // SetSymAlign sets the alignment for a symbol.
1279 func (l *Loader) SetSymAlign(i Sym, align int32) {
1280 // Reject nonsense alignments.
1281 if align < 0 || align&(align-1) != 0 {
1282 panic("bad alignment value")
1284 if int(i) >= len(l.align) {
1285 l.align = append(l.align, make([]uint8, l.NSym()-len(l.align))...)
1290 l.align[i] = uint8(bits.Len32(uint32(align)))
1293 // SymSect returns the section of the i-th symbol. i is global index.
1294 func (l *Loader) SymSect(i Sym) *sym.Section {
1295 if int(i) >= len(l.symSects) {
1296 // symSects is extended lazily -- it the sym in question is
1297 // outside the range of the existing slice, then we assume its
1298 // section has not yet been set.
1301 return l.sects[l.symSects[i]]
1304 // SetSymSect sets the section of the i-th symbol. i is global index.
1305 func (l *Loader) SetSymSect(i Sym, sect *sym.Section) {
1306 if int(i) >= len(l.symSects) {
1307 l.symSects = append(l.symSects, make([]uint16, l.NSym()-len(l.symSects))...)
1309 l.symSects[i] = sect.Index
1312 // growSects grows the slice used to store symbol sections.
1313 func (l *Loader) growSects(reqLen int) {
1314 curLen := len(l.symSects)
1315 if reqLen > curLen {
1316 l.symSects = append(l.symSects, make([]uint16, reqLen+1-curLen)...)
1320 // NewSection creates a new (output) section.
1321 func (l *Loader) NewSection() *sym.Section {
1322 sect := new(sym.Section)
1324 if idx != int(uint16(idx)) {
1325 panic("too many sections created")
1327 sect.Index = uint16(idx)
1328 l.sects = append(l.sects, sect)
1332 // SymDynimplib returns the "dynimplib" attribute for the specified
1333 // symbol, making up a portion of the info for a symbol specified
1334 // on a "cgo_import_dynamic" compiler directive.
1335 func (l *Loader) SymDynimplib(i Sym) string {
1336 return l.dynimplib[i]
1339 // SetSymDynimplib sets the "dynimplib" attribute for a symbol.
1340 func (l *Loader) SetSymDynimplib(i Sym, value string) {
1341 // reject bad symbols
1342 if i >= Sym(len(l.objSyms)) || i == 0 {
1343 panic("bad symbol index in SetDynimplib")
1346 delete(l.dynimplib, i)
1348 l.dynimplib[i] = value
1352 // SymDynimpvers returns the "dynimpvers" attribute for the specified
1353 // symbol, making up a portion of the info for a symbol specified
1354 // on a "cgo_import_dynamic" compiler directive.
1355 func (l *Loader) SymDynimpvers(i Sym) string {
1356 return l.dynimpvers[i]
1359 // SetSymDynimpvers sets the "dynimpvers" attribute for a symbol.
1360 func (l *Loader) SetSymDynimpvers(i Sym, value string) {
1361 // reject bad symbols
1362 if i >= Sym(len(l.objSyms)) || i == 0 {
1363 panic("bad symbol index in SetDynimpvers")
1366 delete(l.dynimpvers, i)
1368 l.dynimpvers[i] = value
1372 // SymExtname returns the "extname" value for the specified
1374 func (l *Loader) SymExtname(i Sym) string {
1375 if s, ok := l.extname[i]; ok {
1381 // SetSymExtname sets the "extname" attribute for a symbol.
1382 func (l *Loader) SetSymExtname(i Sym, value string) {
1383 // reject bad symbols
1384 if i >= Sym(len(l.objSyms)) || i == 0 {
1385 panic("bad symbol index in SetExtname")
1388 delete(l.extname, i)
1390 l.extname[i] = value
1394 // SymElfType returns the previously recorded ELF type for a symbol
1395 // (used only for symbols read from shared libraries by ldshlibsyms).
1396 // It is not set for symbols defined by the packages being linked or
1397 // by symbols read by ldelf (and so is left as elf.STT_NOTYPE).
1398 func (l *Loader) SymElfType(i Sym) elf.SymType {
1399 if et, ok := l.elfType[i]; ok {
1402 return elf.STT_NOTYPE
1405 // SetSymElfType sets the elf type attribute for a symbol.
1406 func (l *Loader) SetSymElfType(i Sym, et elf.SymType) {
1407 // reject bad symbols
1408 if i >= Sym(len(l.objSyms)) || i == 0 {
1409 panic("bad symbol index in SetSymElfType")
1411 if et == elf.STT_NOTYPE {
1412 delete(l.elfType, i)
1418 // SymElfSym returns the ELF symbol index for a given loader
1419 // symbol, assigned during ELF symtab generation.
1420 func (l *Loader) SymElfSym(i Sym) int32 {
1424 // SetSymElfSym sets the elf symbol index for a symbol.
1425 func (l *Loader) SetSymElfSym(i Sym, es int32) {
1427 panic("bad sym index")
1436 // SymLocalElfSym returns the "local" ELF symbol index for a given loader
1437 // symbol, assigned during ELF symtab generation.
1438 func (l *Loader) SymLocalElfSym(i Sym) int32 {
1439 return l.localElfSym[i]
1442 // SetSymLocalElfSym sets the "local" elf symbol index for a symbol.
1443 func (l *Loader) SetSymLocalElfSym(i Sym, es int32) {
1445 panic("bad sym index")
1448 delete(l.localElfSym, i)
1450 l.localElfSym[i] = es
1454 // SymPlt returns the PLT offset of symbol s.
1455 func (l *Loader) SymPlt(s Sym) int32 {
1456 if v, ok := l.plt[s]; ok {
1462 // SetPlt sets the PLT offset of symbol i.
1463 func (l *Loader) SetPlt(i Sym, v int32) {
1464 if i >= Sym(len(l.objSyms)) || i == 0 {
1465 panic("bad symbol for SetPlt")
1474 // SymGot returns the GOT offset of symbol s.
1475 func (l *Loader) SymGot(s Sym) int32 {
1476 if v, ok := l.got[s]; ok {
1482 // SetGot sets the GOT offset of symbol i.
1483 func (l *Loader) SetGot(i Sym, v int32) {
1484 if i >= Sym(len(l.objSyms)) || i == 0 {
1485 panic("bad symbol for SetGot")
1494 // SymDynid returns the "dynid" property for the specified symbol.
1495 func (l *Loader) SymDynid(i Sym) int32 {
1496 if s, ok := l.dynid[i]; ok {
1502 // SetSymDynid sets the "dynid" property for a symbol.
1503 func (l *Loader) SetSymDynid(i Sym, val int32) {
1504 // reject bad symbols
1505 if i >= Sym(len(l.objSyms)) || i == 0 {
1506 panic("bad symbol index in SetSymDynid")
1515 // DynidSyms returns the set of symbols for which dynID is set to an
1516 // interesting (non-default) value. This is expected to be a fairly
1518 func (l *Loader) DynidSyms() []Sym {
1519 sl := make([]Sym, 0, len(l.dynid))
1520 for s := range l.dynid {
1523 sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
1527 // SymGoType returns the 'Gotype' property for a given symbol (set by
1528 // the Go compiler for variable symbols). This version relies on
1529 // reading aux symbols for the target sym -- it could be that a faster
1530 // approach would be to check for gotype during preload and copy the
1531 // results in to a map (might want to try this at some point and see
1532 // if it helps speed things up).
1533 func (l *Loader) SymGoType(i Sym) Sym { return l.aux1(i, goobj.AuxGotype) }
1535 // SymUnit returns the compilation unit for a given symbol (which will
1536 // typically be nil for external or linker-manufactured symbols).
1537 func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
1538 if l.IsExternal(i) {
1539 pp := l.getPayload(i)
1541 r := l.objs[pp.objidx].r
1546 r, _ := l.toLocal(i)
1550 // SymPkg returns the package where the symbol came from (for
1551 // regular compiler-generated Go symbols), but in the case of
1552 // building with "-linkshared" (when a symbol is read from a
1553 // shared library), will hold the library name.
1554 // NOTE: this corresponds to sym.Symbol.File field.
1555 func (l *Loader) SymPkg(i Sym) string {
1556 if f, ok := l.symPkg[i]; ok {
1559 if l.IsExternal(i) {
1560 pp := l.getPayload(i)
1562 r := l.objs[pp.objidx].r
1563 return r.unit.Lib.Pkg
1567 r, _ := l.toLocal(i)
1568 return r.unit.Lib.Pkg
1571 // SetSymPkg sets the package/library for a symbol. This is
1572 // needed mainly for external symbols, specifically those imported
1573 // from shared libraries.
1574 func (l *Loader) SetSymPkg(i Sym, pkg string) {
1575 // reject bad symbols
1576 if i >= Sym(len(l.objSyms)) || i == 0 {
1577 panic("bad symbol index in SetSymPkg")
1582 // SymLocalentry returns an offset in bytes of the "local entry" of a symbol.
1583 func (l *Loader) SymLocalentry(i Sym) uint8 {
1584 return l.localentry[i]
1587 // SetSymLocalentry sets the "local entry" offset attribute for a symbol.
1588 func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
1589 // reject bad symbols
1590 if i >= Sym(len(l.objSyms)) || i == 0 {
1591 panic("bad symbol index in SetSymLocalentry")
1594 delete(l.localentry, i)
1596 l.localentry[i] = value
1600 // Returns the number of aux symbols given a global index.
1601 func (l *Loader) NAux(i Sym) int {
1602 if l.IsExternal(i) {
1605 r, li := l.toLocal(i)
1609 // Returns the "handle" to the j-th aux symbol of the i-th symbol.
1610 func (l *Loader) Aux(i Sym, j int) Aux {
1611 if l.IsExternal(i) {
1614 r, li := l.toLocal(i)
1615 if j >= r.NAux(li) {
1618 return Aux{r.Aux(li, j), r, l}
1621 // WasmImportSym returns the auxiliary WebAssembly import symbol associated with
1622 // a given function symbol. The aux sym only exists for Go function stubs that
1623 // have been annotated with the //go:wasmimport directive. The aux sym
1624 // contains the information necessary for the linker to add a WebAssembly
1625 // import statement.
1626 // (https://webassembly.github.io/spec/core/syntax/modules.html#imports)
1627 func (l *Loader) WasmImportSym(fnSymIdx Sym) (Sym, bool) {
1628 if l.SymType(fnSymIdx) != sym.STEXT {
1629 log.Fatalf("error: non-function sym %d/%s t=%s passed to WasmImportSym", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1631 r, li := l.toLocal(fnSymIdx)
1633 for i := range auxs {
1636 case goobj.AuxWasmImport:
1637 return l.resolve(r, a.Sym()), true
1644 // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
1645 // symbols associated with a given function symbol. Prior to the
1646 // introduction of the loader, this was done purely using name
1647 // lookups, e.f. for function with name XYZ we would then look up
1648 // go.info.XYZ, etc.
1649 func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
1650 if l.SymType(fnSymIdx) != sym.STEXT {
1651 log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1653 r, auxs := l.auxs(fnSymIdx)
1655 for i := range auxs {
1658 case goobj.AuxDwarfInfo:
1659 auxDwarfInfo = l.resolve(r, a.Sym())
1660 if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
1661 panic("aux dwarf info sym with wrong type")
1663 case goobj.AuxDwarfLoc:
1664 auxDwarfLoc = l.resolve(r, a.Sym())
1665 if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
1666 panic("aux dwarf loc sym with wrong type")
1668 case goobj.AuxDwarfRanges:
1669 auxDwarfRanges = l.resolve(r, a.Sym())
1670 if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
1671 panic("aux dwarf ranges sym with wrong type")
1673 case goobj.AuxDwarfLines:
1674 auxDwarfLines = l.resolve(r, a.Sym())
1675 if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
1676 panic("aux dwarf lines sym with wrong type")
1683 // AddInteriorSym sets up 'interior' as an interior symbol of
1684 // container/payload symbol 'container'. An interior symbol does not
1685 // itself have data, but gives a name to a subrange of the data in its
1686 // container symbol. The container itself may or may not have a name.
1687 // This method is intended primarily for use in the host object
1688 // loaders, to capture the semantics of symbols and sections in an
1689 // object file. When reading a host object file, we'll typically
1690 // encounter a static section symbol (ex: ".text") containing content
1691 // for a collection of functions, then a series of ELF (or macho, etc)
1692 // symbol table entries each of which points into a sub-section
1693 // (offset and length) of its corresponding container symbol. Within
1694 // the go linker we create a loader.Sym for the container (which is
1695 // expected to have the actual content/payload) and then a set of
1696 // interior loader.Sym's that point into a portion of the container.
1697 func (l *Loader) AddInteriorSym(container Sym, interior Sym) {
1698 // Container symbols are expected to have content/data.
1699 // NB: this restriction may turn out to be too strict (it's possible
1700 // to imagine a zero-sized container with an interior symbol pointing
1701 // into it); it's ok to relax or remove it if we counter an
1702 // oddball host object that triggers this.
1703 if l.SymSize(container) == 0 && len(l.Data(container)) == 0 {
1704 panic("unexpected empty container symbol")
1706 // The interior symbols for a container are not expected to have
1707 // content/data or relocations.
1708 if len(l.Data(interior)) != 0 {
1709 panic("unexpected non-empty interior symbol")
1711 // Interior symbol is expected to be in the symbol table.
1712 if l.AttrNotInSymbolTable(interior) {
1713 panic("interior symbol must be in symtab")
1715 // Only a single level of containment is allowed.
1716 if l.OuterSym(container) != 0 {
1717 panic("outer has outer itself")
1719 // Interior sym should not already have a sibling.
1720 if l.SubSym(interior) != 0 {
1721 panic("sub set for subsym")
1723 // Interior sym should not already point at a container.
1724 if l.OuterSym(interior) != 0 {
1725 panic("outer already set for subsym")
1727 l.sub[interior] = l.sub[container]
1728 l.sub[container] = interior
1729 l.outer[interior] = container
1732 // OuterSym gets the outer symbol for host object loaded symbols.
1733 func (l *Loader) OuterSym(i Sym) Sym {
1734 // FIXME: add check for isExternal?
1738 // SubSym gets the subsymbol for host object loaded symbols.
1739 func (l *Loader) SubSym(i Sym) Sym {
1740 // NB: note -- no check for l.isExternal(), since I am pretty sure
1741 // that later phases in the linker set subsym for "type:" syms
1745 // SetCarrierSym declares that 'c' is the carrier or container symbol
1746 // for 's'. Carrier symbols are used in the linker to as a container
1747 // for a collection of sub-symbols where the content of the
1748 // sub-symbols is effectively concatenated to form the content of the
1749 // carrier. The carrier is given a name in the output symbol table
1750 // while the sub-symbol names are not. For example, the Go compiler
1751 // emits named string symbols (type SGOSTRING) when compiling a
1752 // package; after being deduplicated, these symbols are collected into
1753 // a single unit by assigning them a new carrier symbol named
1754 // "go:string.*" (which appears in the final symbol table for the
1755 // output load module).
1756 func (l *Loader) SetCarrierSym(s Sym, c Sym) {
1758 panic("invalid carrier in SetCarrierSym")
1761 panic("invalid sub-symbol in SetCarrierSym")
1763 // Carrier symbols are not expected to have content/data. It is
1764 // ok for them to have non-zero size (to allow for use of generator
1766 if len(l.Data(c)) != 0 {
1767 panic("unexpected non-empty carrier symbol")
1770 // relocsym's foldSubSymbolOffset requires that we only
1771 // have a single level of containment-- enforce here.
1772 if l.outer[c] != 0 {
1773 panic("invalid nested carrier sym")
1777 // Initialize Reachable bitmap and its siblings for running deadcode pass.
1778 func (l *Loader) InitReachable() {
1779 l.growAttrBitmaps(l.NSym() + 1)
1782 type symWithVal struct {
1786 type bySymValue []symWithVal
1788 func (s bySymValue) Len() int { return len(s) }
1789 func (s bySymValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1790 func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
1792 // SortSub walks through the sub-symbols for 's' and sorts them
1793 // in place by increasing value. Return value is the new
1794 // sub symbol for the specified outer symbol.
1795 func (l *Loader) SortSub(s Sym) Sym {
1797 if s == 0 || l.sub[s] == 0 {
1801 // Sort symbols using a slice first. Use a stable sort on the off
1802 // chance that there's more than once symbol with the same value,
1803 // so as to preserve reproducible builds.
1804 sl := []symWithVal{}
1805 for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
1806 sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
1808 sort.Stable(bySymValue(sl))
1810 // Then apply any changes needed to the sub map.
1812 for i := len(sl) - 1; i >= 0; i-- {
1818 // Update sub for outer symbol, then return
1823 // SortSyms sorts a list of symbols by their value.
1824 func (l *Loader) SortSyms(ss []Sym) {
1825 sort.SliceStable(ss, func(i, j int) bool { return l.SymValue(ss[i]) < l.SymValue(ss[j]) })
1828 // Insure that reachable bitmap and its siblings have enough size.
1829 func (l *Loader) growAttrBitmaps(reqLen int) {
1830 if reqLen > l.attrReachable.Len() {
1831 // These are indexed by global symbol
1832 l.attrReachable = growBitmap(reqLen, l.attrReachable)
1833 l.attrOnList = growBitmap(reqLen, l.attrOnList)
1834 l.attrLocal = growBitmap(reqLen, l.attrLocal)
1835 l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
1836 l.attrUsedInIface = growBitmap(reqLen, l.attrUsedInIface)
1838 l.growExtAttrBitmaps()
1841 func (l *Loader) growExtAttrBitmaps() {
1842 // These are indexed by external symbol index (e.g. l.extIndex(i))
1843 extReqLen := len(l.payloads)
1844 if extReqLen > l.attrVisibilityHidden.Len() {
1845 l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
1846 l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
1847 l.attrShared = growBitmap(extReqLen, l.attrShared)
1848 l.attrExternal = growBitmap(extReqLen, l.attrExternal)
1852 func (relocs *Relocs) Count() int { return len(relocs.rs) }
1854 // At returns the j-th reloc for a global symbol.
1855 func (relocs *Relocs) At(j int) Reloc {
1856 if relocs.l.isExtReader(relocs.r) {
1857 return Reloc{&relocs.rs[j], relocs.r, relocs.l}
1859 return Reloc{&relocs.rs[j], relocs.r, relocs.l}
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 func (l *Loader) auxs(i Sym) (*oReader, []goobj.Aux) {
1889 if l.IsExternal(i) {
1890 pp := l.getPayload(i)
1891 return l.objs[pp.objidx].r, pp.auxs
1893 r, li := l.toLocal(i)
1894 return r, r.Auxs(li)
1898 // Returns a specific aux symbol of type t for symbol i.
1899 func (l *Loader) aux1(i Sym, t uint8) Sym {
1900 r, auxs := l.auxs(i)
1901 for j := range auxs {
1904 return l.resolve(r, a.Sym())
1910 func (l *Loader) Pcsp(i Sym) Sym { return l.aux1(i, goobj.AuxPcsp) }
1912 // Returns all aux symbols of per-PC data for symbol i.
1913 // tmp is a scratch space for the pcdata slice.
1914 func (l *Loader) PcdataAuxs(i Sym, tmp []Sym) (pcsp, pcfile, pcline, pcinline Sym, pcdata []Sym) {
1916 r, auxs := l.auxs(i)
1917 for j := range auxs {
1921 pcsp = l.resolve(r, a.Sym())
1922 case goobj.AuxPcline:
1923 pcline = l.resolve(r, a.Sym())
1924 case goobj.AuxPcfile:
1925 pcfile = l.resolve(r, a.Sym())
1926 case goobj.AuxPcinline:
1927 pcinline = l.resolve(r, a.Sym())
1928 case goobj.AuxPcdata:
1929 pcdata = append(pcdata, l.resolve(r, a.Sym()))
1935 // Returns the number of pcdata for symbol i.
1936 func (l *Loader) NumPcdata(i Sym) int {
1938 _, auxs := l.auxs(i)
1939 for j := range auxs {
1941 if a.Type() == goobj.AuxPcdata {
1948 // Returns all funcdata symbols of symbol i.
1949 // tmp is a scratch space.
1950 func (l *Loader) Funcdata(i Sym, tmp []Sym) []Sym {
1952 r, auxs := l.auxs(i)
1953 for j := range auxs {
1955 if a.Type() == goobj.AuxFuncdata {
1956 fd = append(fd, l.resolve(r, a.Sym()))
1962 // Returns the number of funcdata for symbol i.
1963 func (l *Loader) NumFuncdata(i Sym) int {
1965 _, auxs := l.auxs(i)
1966 for j := range auxs {
1968 if a.Type() == goobj.AuxFuncdata {
1975 // FuncInfo provides hooks to access goobj.FuncInfo in the objects.
1976 type FuncInfo struct {
1980 lengths goobj.FuncInfoLengths
1983 func (fi *FuncInfo) Valid() bool { return fi.r != nil }
1985 func (fi *FuncInfo) Args() int {
1986 return int((*goobj.FuncInfo)(nil).ReadArgs(fi.data))
1989 func (fi *FuncInfo) Locals() int {
1990 return int((*goobj.FuncInfo)(nil).ReadLocals(fi.data))
1993 func (fi *FuncInfo) FuncID() objabi.FuncID {
1994 return (*goobj.FuncInfo)(nil).ReadFuncID(fi.data)
1997 func (fi *FuncInfo) FuncFlag() objabi.FuncFlag {
1998 return (*goobj.FuncInfo)(nil).ReadFuncFlag(fi.data)
2001 func (fi *FuncInfo) StartLine() int32 {
2002 return (*goobj.FuncInfo)(nil).ReadStartLine(fi.data)
2005 // Preload has to be called prior to invoking the various methods
2006 // below related to pcdata, funcdataoff, files, and inltree nodes.
2007 func (fi *FuncInfo) Preload() {
2008 fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
2011 func (fi *FuncInfo) NumFile() uint32 {
2012 if !fi.lengths.Initialized {
2013 panic("need to call Preload first")
2015 return fi.lengths.NumFile
2018 func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
2019 if !fi.lengths.Initialized {
2020 panic("need to call Preload first")
2022 return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
2025 // TopFrame returns true if the function associated with this FuncInfo
2026 // is an entry point, meaning that unwinders should stop when they hit
2028 func (fi *FuncInfo) TopFrame() bool {
2029 return (fi.FuncFlag() & objabi.FuncFlag_TOPFRAME) != 0
2032 type InlTreeNode struct {
2034 File goobj.CUFileIndex
2040 func (fi *FuncInfo) NumInlTree() uint32 {
2041 if !fi.lengths.Initialized {
2042 panic("need to call Preload first")
2044 return fi.lengths.NumInlTree
2047 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
2048 if !fi.lengths.Initialized {
2049 panic("need to call Preload first")
2051 node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
2053 Parent: node.Parent,
2056 Func: fi.l.resolve(fi.r, node.Func),
2057 ParentPC: node.ParentPC,
2061 func (l *Loader) FuncInfo(i Sym) FuncInfo {
2062 r, auxs := l.auxs(i)
2063 for j := range auxs {
2065 if a.Type() == goobj.AuxFuncInfo {
2066 b := r.Data(a.Sym().SymIdx)
2067 return FuncInfo{l, r, b, goobj.FuncInfoLengths{}}
2073 // Preload a package: adds autolib.
2074 // Does not add defined package or non-packaged symbols to the symbol table.
2075 // These are done in LoadSyms.
2076 // Does not read symbol data.
2077 // Returns the fingerprint of the object.
2078 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
2079 roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
2081 log.Fatal("cannot read object file:", err)
2083 r := goobj.NewReaderFromBytes(roObject, readonly)
2085 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
2086 log.Fatalf("found object file %s in old format", f.File().Name())
2088 panic("cannot read object file")
2090 pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
2092 nhashed64def := r.NHashed64def()
2093 nhasheddef := r.NHasheddef()
2097 version: localSymVersion,
2098 pkgprefix: pkgprefix,
2099 syms: make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
2101 nhasheddef: nhasheddef,
2102 nhashed64def: nhashed64def,
2103 objidx: uint32(len(l.objs)),
2107 log.Fatalf("link: unlinkable object (from package %s) - compiler requires -p flag", lib.Pkg)
2111 lib.Autolib = append(lib.Autolib, r.Autolib()...)
2115 unit.FileTable = make([]string, nfile)
2116 for i := range unit.FileTable {
2117 unit.FileTable[i] = r.File(i)
2120 l.addObj(lib.Pkg, or)
2122 // The caller expects us consuming all the data
2123 f.MustSeek(length, io.SeekCurrent)
2125 return r.Fingerprint()
2128 // Holds the loader along with temporary states for loading symbols.
2129 type loadState struct {
2131 hashed64Syms map[uint64]symAndSize // short hashed (content-addressable) symbols, keyed by content hash
2132 hashedSyms map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
2135 // Preload symbols of given kind from an object.
2136 func (st *loadState) preloadSyms(r *oReader, kind int) {
2138 var start, end uint32
2142 end = uint32(r.ndef)
2144 start = uint32(r.ndef)
2145 end = uint32(r.ndef + r.nhashed64def)
2147 start = uint32(r.ndef + r.nhashed64def)
2148 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2150 start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2151 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
2153 panic("preloadSyms: bad kind")
2155 l.growAttrBitmaps(len(l.objSyms) + int(end-start))
2156 loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
2157 for i := start; i < end; i++ {
2161 if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
2162 name = osym.Name(r.Reader)
2163 v = abiToVer(osym.ABI(), r.version)
2165 gi := st.addSym(name, v, r, i, kind, osym)
2168 l.SetAttrLocal(gi, true)
2170 if osym.UsedInIface() {
2171 l.SetAttrUsedInIface(gi, true)
2173 if strings.HasPrefix(name, "runtime.") ||
2174 (loadingRuntimePkg && strings.HasPrefix(name, "type:")) {
2175 if bi := goobj.BuiltinIdx(name, int(osym.ABI())); bi != -1 {
2176 // This is a definition of a builtin symbol. Record where it is.
2177 l.builtinSyms[bi] = gi
2180 if a := int32(osym.Align()); a != 0 && a > l.SymAlign(gi) {
2181 l.SetSymAlign(gi, a)
2186 // Add syms, hashed (content-addressable) symbols, non-package symbols, and
2187 // references to external symbols (which are always named).
2188 func (l *Loader) LoadSyms(arch *sys.Arch) {
2189 // Allocate space for symbols, making a guess as to how much space we need.
2190 // This function was determined empirically by looking at the cmd/compile on
2191 // Darwin, and picking factors for hashed and hashed64 syms.
2192 var symSize, hashedSize, hashed64Size int
2193 for _, o := range l.objs[goObjStart:] {
2194 symSize += o.r.ndef + o.r.nhasheddef/2 + o.r.nhashed64def/2 + o.r.NNonpkgdef()
2195 hashedSize += o.r.nhasheddef / 2
2196 hashed64Size += o.r.nhashed64def / 2
2198 // Index 0 is invalid for symbols.
2199 l.objSyms = make([]objSym, 1, symSize)
2203 hashed64Syms: make(map[uint64]symAndSize, hashed64Size),
2204 hashedSyms: make(map[goobj.HashType]symAndSize, hashedSize),
2207 for _, o := range l.objs[goObjStart:] {
2208 st.preloadSyms(o.r, pkgDef)
2210 l.npkgsyms = l.NSym()
2211 for _, o := range l.objs[goObjStart:] {
2212 st.preloadSyms(o.r, hashed64Def)
2213 st.preloadSyms(o.r, hashedDef)
2214 st.preloadSyms(o.r, nonPkgDef)
2216 l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
2217 for _, o := range l.objs[goObjStart:] {
2218 loadObjRefs(l, o.r, arch)
2220 l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2223 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2224 // load non-package refs
2225 ndef := uint32(r.NAlldef())
2226 for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2227 osym := r.Sym(ndef + i)
2228 name := osym.Name(r.Reader)
2229 v := abiToVer(osym.ABI(), r.version)
2230 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2231 gi := r.syms[ndef+i]
2233 l.SetAttrLocal(gi, true)
2235 if osym.UsedInIface() {
2236 l.SetAttrUsedInIface(gi, true)
2240 // referenced packages
2242 r.pkg = make([]uint32, npkg)
2243 for i := 1; i < npkg; i++ { // PkgIdx 0 is a dummy invalid package
2245 objidx, ok := l.objByPkg[pkg]
2247 log.Fatalf("%v: reference to nonexistent package %s", r.unit.Lib, pkg)
2252 // load flags of package refs
2253 for i, n := 0, r.NRefFlags(); i < n; i++ {
2255 gi := l.resolve(r, rf.Sym())
2256 if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
2257 l.SetAttrUsedInIface(gi, true)
2262 func abiToVer(abi uint16, localSymVersion int) int {
2264 if abi == goobj.SymABIstatic {
2267 } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2268 // Note that data symbols are "ABI0", which maps to version 0.
2271 log.Fatalf("invalid symbol ABI: %d", abi)
2276 // TopLevelSym tests a symbol (by name and kind) to determine whether
2277 // the symbol first class sym (participating in the link) or is an
2278 // anonymous aux or sub-symbol containing some sub-part or payload of
2280 func (l *Loader) TopLevelSym(s Sym) bool {
2281 return topLevelSym(l.SymName(s), l.SymType(s))
2284 // topLevelSym tests a symbol name and kind to determine whether
2285 // the symbol first class sym (participating in the link) or is an
2286 // anonymous aux or sub-symbol containing some sub-part or payload of
2288 func topLevelSym(sname string, skind sym.SymKind) bool {
2293 case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2300 // cloneToExternal takes the existing object file symbol (symIdx)
2301 // and creates a new external symbol payload that is a clone with
2302 // respect to name, version, type, relocations, etc. The idea here
2303 // is that if the linker decides it wants to update the contents of
2304 // a symbol originally discovered as part of an object file, it's
2305 // easier to do this if we make the updates to an external symbol
2307 func (l *Loader) cloneToExternal(symIdx Sym) {
2308 if l.IsExternal(symIdx) {
2309 panic("sym is already external, no need for clone")
2312 // Read the particulars from object.
2313 r, li := l.toLocal(symIdx)
2315 sname := osym.Name(r.Reader)
2316 sver := abiToVer(osym.ABI(), r.version)
2317 skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2319 // Create new symbol, update version and kind.
2320 pi := l.newPayload(sname, sver)
2321 pp := l.payloads[pi]
2324 pp.size = int64(osym.Siz())
2325 pp.objidx = r.objidx
2327 // If this is a def, then copy the guts. We expect this case
2328 // to be very rare (one case it may come up is with -X).
2329 if li < uint32(r.NAlldef()) {
2332 relocs := l.Relocs(symIdx)
2333 pp.relocs = make([]goobj.Reloc, relocs.Count())
2334 for i := range pp.relocs {
2335 // Copy the relocs slice.
2336 // Convert local reference to global reference.
2338 pp.relocs[i].Set(rel.Off(), rel.Siz(), uint16(rel.Type()), rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2342 pp.data = r.Data(li)
2345 // If we're overriding a data symbol, collect the associated
2346 // Gotype, so as to propagate it to the new symbol.
2350 // Install new payload to global index space.
2351 // (This needs to happen at the end, as the accessors above
2352 // need to access the old symbol content.)
2353 l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2354 l.extReader.syms = append(l.extReader.syms, symIdx)
2356 // Some attributes were encoded in the object file. Copy them over.
2357 l.SetAttrDuplicateOK(symIdx, r.Sym(li).Dupok())
2358 l.SetAttrShared(symIdx, r.Shared())
2361 // Copy the payload of symbol src to dst. Both src and dst must be external
2363 // The intended use case is that when building/linking against a shared library,
2364 // where we do symbol name mangling, the Go object file may have reference to
2365 // the original symbol name whereas the shared library provides a symbol with
2366 // the mangled name. When we do mangling, we copy payload of mangled to original.
2367 func (l *Loader) CopySym(src, dst Sym) {
2368 if !l.IsExternal(dst) {
2369 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2371 if !l.IsExternal(src) {
2372 panic("src is not external") //l.cloneToExternal(src)
2374 l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2375 l.SetSymPkg(dst, l.SymPkg(src))
2376 // TODO: other attributes?
2379 // CreateExtSym creates a new external symbol with the specified name
2380 // without adding it to any lookup tables, returning a Sym index for it.
2381 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2382 return l.newExtSym(name, ver)
2385 // CreateStaticSym creates a new static symbol with the specified name
2386 // without adding it to any lookup tables, returning a Sym index for it.
2387 func (l *Loader) CreateStaticSym(name string) Sym {
2388 // Assign a new unique negative version -- this is to mark the
2389 // symbol so that it is not included in the name lookup table.
2391 return l.newExtSym(name, l.anonVersion)
2394 func (l *Loader) FreeSym(i Sym) {
2395 if l.IsExternal(i) {
2396 pp := l.getPayload(i)
2397 *pp = extSymPayload{}
2401 // relocId is essentially a <S,R> tuple identifying the Rth
2402 // relocation of symbol S.
2403 type relocId struct {
2408 // SetRelocVariant sets the 'variant' property of a relocation on
2409 // some specific symbol.
2410 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2412 if relocs := l.Relocs(s); ri >= relocs.Count() {
2413 panic("invalid relocation ID")
2415 if l.relocVariant == nil {
2416 l.relocVariant = make(map[relocId]sym.RelocVariant)
2419 l.relocVariant[relocId{s, ri}] = v
2421 delete(l.relocVariant, relocId{s, ri})
2425 // RelocVariant returns the 'variant' property of a relocation on
2426 // some specific symbol.
2427 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2428 return l.relocVariant[relocId{s, ri}]
2431 // UndefinedRelocTargets iterates through the global symbol index
2432 // space, looking for symbols with relocations targeting undefined
2433 // references. The linker's loadlib method uses this to determine if
2434 // there are unresolved references to functions in system libraries
2435 // (for example, libgcc.a), presumably due to CGO code. Return value
2436 // is a pair of lists of loader.Sym's. First list corresponds to the
2437 // corresponding to the undefined symbols themselves, the second list
2438 // is the symbol that is making a reference to the undef. The "limit"
2439 // param controls the maximum number of results returned; if "limit"
2440 // is -1, then all undefs are returned.
2441 func (l *Loader) UndefinedRelocTargets(limit int) ([]Sym, []Sym) {
2442 result, fromr := []Sym{}, []Sym{}
2444 for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2445 relocs := l.Relocs(si)
2446 for ri := 0; ri < relocs.Count(); ri++ {
2449 if rs != 0 && l.SymType(rs) == sym.SXREF && l.SymName(rs) != ".got" {
2450 result = append(result, rs)
2451 fromr = append(fromr, si)
2452 if limit != -1 && len(result) >= limit {
2458 return result, fromr
2461 // AssignTextSymbolOrder populates the Textp slices within each
2462 // library and compilation unit, insuring that packages are laid down
2463 // in dependency order (internal first, then everything else). Return value
2464 // is a slice of all text syms.
2465 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2467 // Library Textp lists should be empty at this point.
2468 for _, lib := range libs {
2469 if len(lib.Textp) != 0 {
2470 panic("expected empty Textp slice for library")
2472 if len(lib.DupTextSyms) != 0 {
2473 panic("expected empty DupTextSyms slice for library")
2477 // Used to record which dupok symbol we've assigned to a unit.
2478 // Can't use the onlist attribute here because it will need to
2479 // clear for the later assignment of the sym.Symbol to a unit.
2480 // NB: we can convert to using onList once we no longer have to
2481 // call the regular addToTextp.
2482 assignedToUnit := MakeBitmap(l.NSym() + 1)
2484 // Start off textp with reachable external syms.
2486 for _, sym := range extsyms {
2487 if !l.attrReachable.Has(sym) {
2490 textp = append(textp, sym)
2493 // Walk through all text symbols from Go object files and append
2494 // them to their corresponding library's textp list.
2495 for _, o := range l.objs[goObjStart:] {
2498 for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
2499 gi := l.toGlobal(r, i)
2500 if !l.attrReachable.Has(gi) {
2504 st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2505 if st != sym.STEXT {
2508 dupok := osym.Dupok()
2509 if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2510 // A dupok text symbol is resolved to another package.
2511 // We still need to record its presence in the current
2512 // package, as the trampoline pass expects packages
2513 // are laid out in dependency order.
2514 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2515 continue // symbol in different object
2518 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2522 lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2526 // Now assemble global textp, and assign text symbols to units.
2527 for _, doInternal := range [2]bool{true, false} {
2528 for idx, lib := range libs {
2529 if intlibs[idx] != doInternal {
2532 lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2533 for i, list := range lists {
2534 for _, s := range list {
2536 if !assignedToUnit.Has(sym) {
2537 textp = append(textp, sym)
2538 unit := l.SymUnit(sym)
2540 unit.Textp = append(unit.Textp, s)
2541 assignedToUnit.Set(sym)
2543 // Dupok symbols may be defined in multiple packages; the
2544 // associated package for a dupok sym is chosen sort of
2545 // arbitrarily (the first containing package that the linker
2546 // loads). Canonicalizes its Pkg to the package with which
2547 // it will be laid down in text.
2548 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2549 l.SetSymPkg(sym, lib.Pkg)
2555 lib.DupTextSyms = nil
2562 // ErrorReporter is a helper class for reporting errors.
2563 type ErrorReporter struct {
2565 AfterErrorAction func()
2568 // Errorf method logs an error message.
2570 // After each error, the error actions function will be invoked; this
2571 // will either terminate the link immediately (if -h option given)
2572 // or it will keep a count and exit if more than 20 errors have been printed.
2574 // Logging an error means that on exit cmd/link will delete any
2575 // output file and return a non-zero error code.
2576 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2577 if s != 0 && reporter.ldr.SymName(s) != "" {
2578 // Note: Replace is needed here because symbol names might have % in them,
2579 // due to the use of LinkString for names of instantiating types.
2580 format = strings.Replace(reporter.ldr.SymName(s), "%", "%%", -1) + ": " + format
2582 format = fmt.Sprintf("sym %d: %s", s, format)
2585 fmt.Fprintf(os.Stderr, format, args...)
2586 reporter.AfterErrorAction()
2589 // GetErrorReporter returns the loader's associated error reporter.
2590 func (l *Loader) GetErrorReporter() *ErrorReporter {
2591 return l.errorReporter
2594 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2595 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2596 l.errorReporter.Errorf(s, format, args...)
2599 // Symbol statistics.
2600 func (l *Loader) Stat() string {
2601 s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
2602 s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
2603 l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
2608 func (l *Loader) Dump() {
2610 for _, obj := range l.objs[goObjStart:] {
2612 fmt.Println(obj.i, obj.r.unit.Lib)
2615 fmt.Println("extStart:", l.extStart)
2616 fmt.Println("Nsyms:", len(l.objSyms))
2618 for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2620 if l.IsExternal(i) {
2621 pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2624 if l.SymSect(i) != nil {
2625 sect = l.SymSect(i).Name
2627 fmt.Printf("%v %v %v %v %x %v\n", i, l.SymName(i), l.SymType(i), pi, l.SymValue(i), sect)
2629 fmt.Println("symsByName")
2630 for name, i := range l.symsByName[0] {
2631 fmt.Println(i, name, 0)
2633 for name, i := range l.symsByName[1] {
2634 fmt.Println(i, name, 1)
2636 fmt.Println("payloads:")
2637 for i := range l.payloads {
2639 fmt.Println(i, pp.name, pp.ver, pp.kind)