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"
28 // Sym encapsulates a global symbol index, used to identify a specific
29 // Go symbol. The 0-valued Sym is corresponds to an invalid symbol.
32 // Relocs encapsulates the set of relocations on a given symbol; an
33 // instance of this type is returned by the Loader Relocs() method.
37 li uint32 // local index of symbol whose relocs we're examining
38 r *oReader // object reader for containing package
42 // ExtReloc contains the payload for an external relocation.
43 type ExtReloc struct {
50 // Reloc holds a "handle" to access a relocation record from an
58 func (rel Reloc) Type() objabi.RelocType { return objabi.RelocType(rel.Reloc.Type()) &^ objabi.R_WEAK }
59 func (rel Reloc) Weak() bool { return objabi.RelocType(rel.Reloc.Type())&objabi.R_WEAK != 0 }
60 func (rel Reloc) SetType(t objabi.RelocType) { rel.Reloc.SetType(uint16(t)) }
61 func (rel Reloc) Sym() Sym { return rel.l.resolve(rel.r, rel.Reloc.Sym()) }
62 func (rel Reloc) SetSym(s Sym) { rel.Reloc.SetSym(goobj.SymRef{PkgIdx: 0, SymIdx: uint32(s)}) }
63 func (rel Reloc) IsMarker() bool { return rel.Siz() == 0 }
65 // Aux holds a "handle" to access an aux symbol record from an
73 func (a Aux) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
75 // oReader is a wrapper type of obj.Reader, along with some
79 unit *sym.CompilationUnit
80 version int // version of static symbol
82 syms []Sym // Sym's global index, indexed by local index
83 pkg []uint32 // indices of referenced package by PkgIdx (index into loader.objs array)
84 ndef int // cache goobj.Reader.NSym()
85 nhashed64def int // cache goobj.Reader.NHashed64Def()
86 nhasheddef int // cache goobj.Reader.NHashedDef()
87 objidx uint32 // index of this reader in the objs slice
90 // Total number of defined symbols (package symbols, hashed symbols, and
91 // non-package symbols).
92 func (r *oReader) NAlldef() int { return r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef() }
99 // objSym represents a symbol in an object file. It is a tuple of
100 // the object and the symbol's local index.
101 // For external symbols, objidx is the index of l.extReader (extObj),
102 // s is its index into the payload array.
103 // {0, 0} represents the nil symbol.
105 objidx uint32 // index of the object (in l.objs array)
106 s uint32 // local index
109 type nameVer struct {
117 func (bm Bitmap) Set(i Sym) {
118 n, r := uint(i)/32, uint(i)%32
122 // unset the i-th bit.
123 func (bm Bitmap) Unset(i Sym) {
124 n, r := uint(i)/32, uint(i)%32
128 // whether the i-th bit is set.
129 func (bm Bitmap) Has(i Sym) bool {
130 n, r := uint(i)/32, uint(i)%32
131 return bm[n]&(1<<r) != 0
134 // return current length of bitmap in bits.
135 func (bm Bitmap) Len() int {
139 // return the number of bits set.
140 func (bm Bitmap) Count() int {
142 for _, x := range bm {
143 s += bits.OnesCount32(x)
148 func MakeBitmap(n int) Bitmap {
149 return make(Bitmap, (n+31)/32)
152 // growBitmap insures that the specified bitmap has enough capacity,
153 // reallocating (doubling the size) if needed.
154 func growBitmap(reqLen int, b Bitmap) Bitmap {
157 b = append(b, MakeBitmap(reqLen+1-curLen)...)
162 type symAndSize struct {
167 // A Loader loads new object files and resolves indexed symbol references.
169 // Notes on the layout of global symbol index space:
171 // - Go object files are read before host object files; each Go object
172 // read adds its defined package symbols to the global index space.
173 // Nonpackage symbols are not yet added.
175 // - In loader.LoadNonpkgSyms, add non-package defined symbols and
176 // references in all object files to the global index space.
178 // - Host object file loading happens; the host object loader does a
179 // name/version lookup for each symbol it finds; this can wind up
180 // extending the external symbol index space range. The host object
181 // loader stores symbol payloads in loader.payloads using SymbolBuilder.
183 // - Each symbol gets a unique global index. For duplicated and
184 // overwriting/overwritten symbols, the second (or later) appearance
185 // of the symbol gets the same global index as the first appearance.
187 start map[*oReader]Sym // map from object file to its start index
188 objs []objIdx // sorted by start index (i.e. objIdx.i)
189 extStart Sym // from this index on, the symbols are externally defined
190 builtinSyms []Sym // global index of builtin symbols
192 objSyms []objSym // global index mapping to local index
194 symsByName [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
195 extStaticSyms map[nameVer]Sym // externally defined static symbols, keyed by name
197 extReader *oReader // a dummy oReader, for external symbols
198 payloadBatch []extSymPayload
199 payloads []*extSymPayload // contents of linker-materialized external syms
200 values []int64 // symbol values, indexed by global sym index
202 sects []*sym.Section // sections
203 symSects []uint16 // symbol's section, index to sects array
205 align []uint8 // symbol 2^N alignment, indexed by global index
207 deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
209 objByPkg map[string]uint32 // map package path to the index of its Go object reader
211 anonVersion int // most recently assigned ext static sym pseudo-version
213 // Bitmaps and other side structures used to store data used to store
214 // symbol flags/attributes; these are to be accessed via the
215 // corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
216 // visit the comments on these methods for more details on the
217 // semantics / interpretation of the specific flags or attribute.
218 attrReachable Bitmap // reachable symbols, indexed by global index
219 attrOnList Bitmap // "on list" symbols, indexed by global index
220 attrLocal Bitmap // "local" symbols, indexed by global index
221 attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by global idx
222 attrUsedInIface Bitmap // "used in interface" symbols, indexed by global idx
223 attrSpecial Bitmap // "special" frame symbols, indexed by global idx
224 attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
225 attrDuplicateOK Bitmap // dupOK symbols, indexed by ext sym index
226 attrShared Bitmap // shared symbols, indexed by ext sym index
227 attrExternal Bitmap // external symbols, indexed by ext sym index
228 generatedSyms Bitmap // symbols that generate their content, indexed by ext sym idx
230 attrReadOnly map[Sym]bool // readonly data for this sym
231 attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
232 attrCgoExportStatic map[Sym]struct{} // "cgo_export_static" symbols
234 // Outer and Sub relations for symbols.
235 outer []Sym // indexed by global index
238 dynimplib map[Sym]string // stores Dynimplib symbol attribute
239 dynimpvers map[Sym]string // stores Dynimpvers symbol attribute
240 localentry map[Sym]uint8 // stores Localentry symbol attribute
241 extname map[Sym]string // stores Extname symbol attribute
242 elfType map[Sym]elf.SymType // stores elf type symbol property
243 elfSym map[Sym]int32 // stores elf sym symbol property
244 localElfSym map[Sym]int32 // stores "local" elf sym symbol property
245 symPkg map[Sym]string // stores package for symbol, or library for shlib-derived syms
246 plt map[Sym]int32 // stores dynimport for pe objects
247 got map[Sym]int32 // stores got for pe objects
248 dynid map[Sym]int32 // stores Dynid for symbol
250 relocVariant map[relocId]sym.RelocVariant // stores variant relocs
252 // Used to implement field tracking; created during deadcode if
253 // field tracking is enabled. Reachparent[K] contains the index of
254 // the symbol that triggered the marking of symbol K as live.
257 // CgoExports records cgo-exported symbols by SymName.
258 CgoExports map[string]Sym
262 strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
264 elfsetstring elfsetstringFunc
266 errorReporter *ErrorReporter
268 npkgsyms int // number of package symbols, for accounting
269 nhashedsyms int // number of hashed symbols, for accounting
287 type elfsetstringFunc func(str string, off int)
289 // extSymPayload holds the payload (data + relocations) for linker-synthesized
290 // external symbols (note that symbol value is stored in a separate slice).
291 type extSymPayload struct {
292 name string // TODO: would this be better as offset into str table?
296 objidx uint32 // index of original object if sym made by cloneToExternal
304 FlagStrictDups = 1 << iota
307 func NewLoader(flags uint32, elfsetstring elfsetstringFunc, reporter *ErrorReporter) *Loader {
308 nbuiltin := goobj.NBuiltin()
309 extReader := &oReader{objidx: extObj}
311 start: make(map[*oReader]Sym),
312 objs: []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
313 objSyms: make([]objSym, 1, 1), // This will get overwritten later.
314 extReader: extReader,
315 symsByName: [2]map[string]Sym{make(map[string]Sym, 80000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
316 objByPkg: make(map[string]uint32),
317 sub: make(map[Sym]Sym),
318 dynimplib: make(map[Sym]string),
319 dynimpvers: make(map[Sym]string),
320 localentry: make(map[Sym]uint8),
321 extname: make(map[Sym]string),
322 attrReadOnly: make(map[Sym]bool),
323 elfType: make(map[Sym]elf.SymType),
324 elfSym: make(map[Sym]int32),
325 localElfSym: make(map[Sym]int32),
326 symPkg: make(map[Sym]string),
327 plt: make(map[Sym]int32),
328 got: make(map[Sym]int32),
329 dynid: make(map[Sym]int32),
330 attrCgoExportDynamic: make(map[Sym]struct{}),
331 attrCgoExportStatic: make(map[Sym]struct{}),
332 deferReturnTramp: make(map[Sym]bool),
333 extStaticSyms: make(map[nameVer]Sym),
334 builtinSyms: make([]Sym, nbuiltin),
336 elfsetstring: elfsetstring,
337 errorReporter: reporter,
338 sects: []*sym.Section{nil}, // reserve index 0 for nil section
344 // Add object file r, return the start index.
345 func (l *Loader) addObj(pkg string, r *oReader) Sym {
346 if _, ok := l.start[r]; ok {
347 panic("already added")
349 pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
350 if _, ok := l.objByPkg[pkg]; !ok {
351 l.objByPkg[pkg] = r.objidx
353 i := Sym(len(l.objSyms))
355 l.objs = append(l.objs, objIdx{r, i})
359 // Add a symbol from an object file, return the global index.
360 // If the symbol already exist, it returns the index of that symbol.
361 func (st *loadState) addSym(name string, ver int, r *oReader, li uint32, kind int, osym *goobj.Sym) Sym {
364 panic("addSym called after external symbol is created")
366 i := Sym(len(l.objSyms))
367 addToGlobal := func() {
368 l.objSyms = append(l.objSyms, objSym{r.objidx, li})
370 if name == "" && kind != hashed64Def && kind != hashedDef {
372 return i // unnamed aux symbol
374 if ver == r.version {
375 // Static symbol. Add its global index but don't
376 // add to name lookup table, as it cannot be
377 // referenced by name.
383 // Defined package symbols cannot be dup to each other.
384 // We load all the package symbols first, so we don't need
385 // to check dup here.
386 // We still add it to the lookup table, as it may still be
387 // referenced by name (e.g. through linkname).
388 l.symsByName[ver][name] = i
391 case hashed64Def, hashedDef:
392 // Hashed (content-addressable) symbol. Check the hash
393 // but don't add to name lookup table, as they are not
394 // referenced by name. Also no need to do overwriting
395 // check, as same hash indicates same content.
396 var checkHash func() (symAndSize, bool)
397 var addToHashMap func(symAndSize)
398 var h64 uint64 // only used for hashed64Def
399 var h *goobj.HashType // only used for hashedDef
400 if kind == hashed64Def {
401 checkHash = func() (symAndSize, bool) {
402 h64 = r.Hash64(li - uint32(r.ndef))
403 s, existed := st.hashed64Syms[h64]
406 addToHashMap = func(ss symAndSize) { st.hashed64Syms[h64] = ss }
408 checkHash = func() (symAndSize, bool) {
409 h = r.Hash(li - uint32(r.ndef+r.nhashed64def))
410 s, existed := st.hashedSyms[*h]
413 addToHashMap = func(ss symAndSize) { st.hashedSyms[*h] = ss }
416 if s, existed := checkHash(); existed {
417 // The content hash is built from symbol data and relocations. In the
418 // object file, the symbol data may not always contain trailing zeros,
419 // e.g. for [5]int{1,2,3} and [100]int{1,2,3}, the data is same
420 // (although the size is different).
421 // Also, for short symbols, the content hash is the identity function of
422 // the 8 bytes, and trailing zeros doesn't change the hash value, e.g.
423 // hash("A") == hash("A\0\0\0").
424 // So when two symbols have the same hash, we need to use the one with
427 // New symbol has larger size, use the new one. Rewrite the index mapping.
428 l.objSyms[s.sym] = objSym{r.objidx, li}
429 addToHashMap(symAndSize{s.sym, siz})
433 addToHashMap(symAndSize{i, siz})
438 // Non-package (named) symbol. Check if it already exists.
439 oldi, existed := l.symsByName[ver][name]
441 l.symsByName[ver][name] = i
445 // symbol already exists
447 if l.flags&FlagStrictDups != 0 {
448 l.checkdup(name, r, li, oldi)
450 // Fix for issue #47185 -- given two dupok symbols with
451 // different sizes, favor symbol with larger size. See
452 // also issue #46653.
453 szdup := l.SymSize(oldi)
454 sz := int64(r.Sym(li).Siz())
456 // new symbol overwrites old symbol.
457 l.objSyms[oldi] = objSym{r.objidx, li}
461 oldr, oldli := l.toLocal(oldi)
462 oldsym := oldr.Sym(oldli)
466 overwrite := r.DataSize(li) != 0
468 // new symbol overwrites old symbol.
469 oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
470 if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
471 log.Fatalf("duplicated definition of symbol %s, from %s and %s", name, r.unit.Lib.Pkg, oldr.unit.Lib.Pkg)
473 l.objSyms[oldi] = objSym{r.objidx, li}
475 // old symbol overwrites new symbol.
476 typ := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
477 if !typ.IsData() { // only allow overwriting data symbol
478 log.Fatalf("duplicated definition of symbol %s, from %s and %s", name, r.unit.Lib.Pkg, oldr.unit.Lib.Pkg)
484 // newExtSym creates a new external sym with the specified
486 func (l *Loader) newExtSym(name string, ver int) Sym {
487 i := Sym(len(l.objSyms))
491 l.growValues(int(i) + 1)
492 l.growOuter(int(i) + 1)
493 l.growAttrBitmaps(int(i) + 1)
494 pi := l.newPayload(name, ver)
495 l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
496 l.extReader.syms = append(l.extReader.syms, i)
500 // LookupOrCreateSym looks up the symbol with the specified name/version,
501 // returning its Sym index if found. If the lookup fails, a new external
502 // Sym will be created, entered into the lookup tables, and returned.
503 func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
504 i := l.Lookup(name, ver)
508 i = l.newExtSym(name, ver)
509 static := ver >= sym.SymVerStatic || ver < 0
511 l.extStaticSyms[nameVer{name, ver}] = i
513 l.symsByName[ver][name] = i
518 // AddCgoExport records a cgo-exported symbol in l.CgoExports.
519 // This table is used to identify the correct Go symbol ABI to use
520 // to resolve references from host objects (which don't have ABIs).
521 func (l *Loader) AddCgoExport(s Sym) {
522 if l.CgoExports == nil {
523 l.CgoExports = make(map[string]Sym)
525 l.CgoExports[l.SymName(s)] = s
528 // LookupOrCreateCgoExport is like LookupOrCreateSym, but if ver
529 // indicates a global symbol, it uses the CgoExport table to determine
530 // the appropriate symbol version (ABI) to use. ver must be either 0
531 // or a static symbol version.
532 func (l *Loader) LookupOrCreateCgoExport(name string, ver int) Sym {
533 if ver >= sym.SymVerStatic {
534 return l.LookupOrCreateSym(name, ver)
537 panic("ver must be 0 or a static version")
539 // Look for a cgo-exported symbol from Go.
540 if s, ok := l.CgoExports[name]; ok {
543 // Otherwise, this must just be a symbol in the host object.
544 // Create a version 0 symbol for it.
545 return l.LookupOrCreateSym(name, 0)
548 func (l *Loader) IsExternal(i Sym) bool {
550 return l.isExtReader(r)
553 func (l *Loader) isExtReader(r *oReader) bool {
554 return r == l.extReader
557 // For external symbol, return its index in the payloads array.
558 // XXX result is actually not a global index. We (ab)use the Sym type
559 // so we don't need conversion for accessing bitmaps.
560 func (l *Loader) extIndex(i Sym) Sym {
561 _, li := l.toLocal(i)
565 // Get a new payload for external symbol, return its index in
566 // the payloads array.
567 func (l *Loader) newPayload(name string, ver int) int {
568 pi := len(l.payloads)
569 pp := l.allocPayload()
572 l.payloads = append(l.payloads, pp)
573 l.growExtAttrBitmaps()
577 // getPayload returns a pointer to the extSymPayload struct for an
578 // external symbol if the symbol has a payload. Will panic if the
579 // symbol in question is bogus (zero or not an external sym).
580 func (l *Loader) getPayload(i Sym) *extSymPayload {
581 if !l.IsExternal(i) {
582 panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
585 return l.payloads[pi]
588 // allocPayload allocates a new payload.
589 func (l *Loader) allocPayload() *extSymPayload {
590 batch := l.payloadBatch
592 batch = make([]extSymPayload, 1000)
595 l.payloadBatch = batch[1:]
599 func (ms *extSymPayload) Grow(siz int64) {
600 if int64(int(siz)) != siz {
601 log.Fatalf("symgrow size %d too long", siz)
603 if int64(len(ms.data)) >= siz {
606 if cap(ms.data) < int(siz) {
608 ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
609 ms.data = ms.data[0:cl]
611 ms.data = ms.data[:siz]
614 // Convert a local index to a global index.
615 func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
619 // Convert a global index to a local index.
620 func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
621 return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
624 // Resolve a local symbol reference. Return global index.
625 func (l *Loader) resolve(r *oReader, s goobj.SymRef) Sym {
627 switch p := s.PkgIdx; p {
628 case goobj.PkgIdxInvalid:
629 // {0, X} with non-zero X is never a valid sym reference from a Go object.
630 // We steal this space for symbol references from external objects.
631 // In this case, X is just the global index.
632 if l.isExtReader(r) {
639 case goobj.PkgIdxHashed64:
640 i := int(s.SymIdx) + r.ndef
642 case goobj.PkgIdxHashed:
643 i := int(s.SymIdx) + r.ndef + r.nhashed64def
645 case goobj.PkgIdxNone:
646 i := int(s.SymIdx) + r.ndef + r.nhashed64def + r.nhasheddef
648 case goobj.PkgIdxBuiltin:
649 if bi := l.builtinSyms[s.SymIdx]; bi != 0 {
652 l.reportMissingBuiltin(int(s.SymIdx), r.unit.Lib.Pkg)
654 case goobj.PkgIdxSelf:
657 rr = l.objs[r.pkg[p]].r
659 return l.toGlobal(rr, s.SymIdx)
662 // reportMissingBuiltin issues an error in the case where we have a
663 // relocation against a runtime builtin whose definition is not found
664 // when the runtime package is built. The canonical example is
665 // "runtime.racefuncenter" -- currently if you do something like
667 // go build -gcflags=-race myprogram.go
669 // the compiler will insert calls to the builtin runtime.racefuncenter,
670 // but the version of the runtime used for linkage won't actually contain
671 // definitions of that symbol. See issue #42396 for details.
673 // As currently implemented, this is a fatal error. This has drawbacks
674 // in that if there are multiple missing builtins, the error will only
675 // cite the first one. On the plus side, terminating the link here has
676 // advantages in that we won't run the risk of panics or crashes later
677 // on in the linker due to R_CALL relocations with 0-valued target
679 func (l *Loader) reportMissingBuiltin(bsym int, reflib string) {
680 bname, _ := goobj.BuiltinName(bsym)
681 log.Fatalf("reference to undefined builtin %q from package %q",
685 // Look up a symbol by name, return global index, or 0 if not found.
686 // This is more like Syms.ROLookup than Lookup -- it doesn't create
688 func (l *Loader) Lookup(name string, ver int) Sym {
689 if ver >= sym.SymVerStatic || ver < 0 {
690 return l.extStaticSyms[nameVer{name, ver}]
692 return l.symsByName[ver][name]
695 // Check that duplicate symbols have same contents.
696 func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
698 rdup, ldup := l.toLocal(dup)
699 pdup := rdup.Data(ldup)
700 reason := "same length but different contents"
701 if len(p) != len(pdup) {
702 reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
703 } else if bytes.Equal(p, pdup) {
704 // For BSS symbols, we need to check size as well, see issue 46653.
705 szdup := l.SymSize(dup)
706 sz := int64(r.Sym(li).Siz())
710 reason = fmt.Sprintf("different sizes: new size %d != old size %d",
713 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)
715 // For the moment, allow DWARF subprogram DIEs for
716 // auto-generated wrapper functions. What seems to happen
717 // here is that we get different line numbers on formal
718 // params; I am guessing that the pos is being inherited
719 // from the spot where the wrapper is needed.
720 allowed := strings.HasPrefix(name, "go:info.go.interface") ||
721 strings.HasPrefix(name, "go:info.go.builtin") ||
722 strings.HasPrefix(name, "go:debuglines")
728 func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
730 // Number of total symbols.
731 func (l *Loader) NSym() int {
732 return len(l.objSyms)
735 // Number of defined Go symbols.
736 func (l *Loader) NDef() int {
737 return int(l.extStart)
740 // Number of reachable symbols.
741 func (l *Loader) NReachableSym() int {
742 return l.attrReachable.Count()
745 // Returns the name of the i-th symbol.
746 func (l *Loader) SymName(i Sym) string {
748 pp := l.getPayload(i)
751 r, li := l.toLocal(i)
755 return r.Sym(li).Name(r.Reader)
758 // Returns the version of the i-th symbol.
759 func (l *Loader) SymVersion(i Sym) int {
761 pp := l.getPayload(i)
764 r, li := l.toLocal(i)
765 return int(abiToVer(r.Sym(li).ABI(), r.version))
768 func (l *Loader) IsFileLocal(i Sym) bool {
769 return l.SymVersion(i) >= sym.SymVerStatic
772 // IsFromAssembly returns true if this symbol is derived from an
773 // object file generated by the Go assembler.
774 func (l *Loader) IsFromAssembly(i Sym) bool {
779 return r.FromAssembly()
782 // Returns the type of the i-th symbol.
783 func (l *Loader) SymType(i Sym) sym.SymKind {
785 pp := l.getPayload(i)
791 r, li := l.toLocal(i)
792 return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
795 // Returns the attributes of the i-th symbol.
796 func (l *Loader) SymAttr(i Sym) uint8 {
798 // TODO: do something? External symbols have different representation of attributes.
799 // For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
800 // set by external symbol.
803 r, li := l.toLocal(i)
804 return r.Sym(li).Flag()
807 // Returns the size of the i-th symbol.
808 func (l *Loader) SymSize(i Sym) int64 {
810 pp := l.getPayload(i)
813 r, li := l.toLocal(i)
814 return int64(r.Sym(li).Siz())
817 // AttrReachable returns true for symbols that are transitively
818 // referenced from the entry points. Unreachable symbols are not
819 // written to the output.
820 func (l *Loader) AttrReachable(i Sym) bool {
821 return l.attrReachable.Has(i)
824 // SetAttrReachable sets the reachability property for a symbol (see
826 func (l *Loader) SetAttrReachable(i Sym, v bool) {
828 l.attrReachable.Set(i)
830 l.attrReachable.Unset(i)
834 // AttrOnList returns true for symbols that are on some list (such as
835 // the list of all text symbols, or one of the lists of data symbols)
836 // and is consulted to avoid bugs where a symbol is put on a list
838 func (l *Loader) AttrOnList(i Sym) bool {
839 return l.attrOnList.Has(i)
842 // SetAttrOnList sets the "on list" property for a symbol (see
844 func (l *Loader) SetAttrOnList(i Sym, v bool) {
848 l.attrOnList.Unset(i)
852 // AttrLocal returns true for symbols that are only visible within the
853 // module (executable or shared library) being linked. This attribute
854 // is applied to thunks and certain other linker-generated symbols.
855 func (l *Loader) AttrLocal(i Sym) bool {
856 return l.attrLocal.Has(i)
859 // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
860 func (l *Loader) SetAttrLocal(i Sym, v bool) {
868 // AttrUsedInIface returns true for a type symbol that is used in
870 func (l *Loader) AttrUsedInIface(i Sym) bool {
871 return l.attrUsedInIface.Has(i)
874 func (l *Loader) SetAttrUsedInIface(i Sym, v bool) {
876 l.attrUsedInIface.Set(i)
878 l.attrUsedInIface.Unset(i)
882 // SymAddr checks that a symbol is reachable, and returns its value.
883 func (l *Loader) SymAddr(i Sym) int64 {
884 if !l.AttrReachable(i) {
885 panic("unreachable symbol in symaddr")
890 // AttrNotInSymbolTable returns true for symbols that should not be
891 // added to the symbol table of the final generated load module.
892 func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
893 return l.attrNotInSymbolTable.Has(i)
896 // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
897 // (see AttrNotInSymbolTable above).
898 func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
900 l.attrNotInSymbolTable.Set(i)
902 l.attrNotInSymbolTable.Unset(i)
906 // AttrVisibilityHidden symbols returns true for ELF symbols with
907 // visibility set to STV_HIDDEN. They become local symbols in
908 // the final executable. Only relevant when internally linking
909 // on an ELF platform.
910 func (l *Loader) AttrVisibilityHidden(i Sym) bool {
911 if !l.IsExternal(i) {
914 return l.attrVisibilityHidden.Has(l.extIndex(i))
917 // SetAttrVisibilityHidden sets the "hidden visibility" property for a
918 // symbol (see AttrVisibilityHidden).
919 func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
920 if !l.IsExternal(i) {
921 panic("tried to set visibility attr on non-external symbol")
924 l.attrVisibilityHidden.Set(l.extIndex(i))
926 l.attrVisibilityHidden.Unset(l.extIndex(i))
930 // AttrDuplicateOK returns true for a symbol that can be present in
931 // multiple object files.
932 func (l *Loader) AttrDuplicateOK(i Sym) bool {
933 if !l.IsExternal(i) {
934 // TODO: if this path winds up being taken frequently, it
935 // might make more sense to copy the flag value out of the object
936 // into a larger bitmap during preload.
937 r, li := l.toLocal(i)
938 return r.Sym(li).Dupok()
940 return l.attrDuplicateOK.Has(l.extIndex(i))
943 // SetAttrDuplicateOK sets the "duplicate OK" property for an external
944 // symbol (see AttrDuplicateOK).
945 func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
946 if !l.IsExternal(i) {
947 panic("tried to set dupok attr on non-external symbol")
950 l.attrDuplicateOK.Set(l.extIndex(i))
952 l.attrDuplicateOK.Unset(l.extIndex(i))
956 // AttrShared returns true for symbols compiled with the -shared option.
957 func (l *Loader) AttrShared(i Sym) bool {
958 if !l.IsExternal(i) {
959 // TODO: if this path winds up being taken frequently, it
960 // might make more sense to copy the flag value out of the
961 // object into a larger bitmap during preload.
965 return l.attrShared.Has(l.extIndex(i))
968 // SetAttrShared sets the "shared" property for an external
969 // symbol (see AttrShared).
970 func (l *Loader) SetAttrShared(i Sym, v bool) {
971 if !l.IsExternal(i) {
972 panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
975 l.attrShared.Set(l.extIndex(i))
977 l.attrShared.Unset(l.extIndex(i))
981 // AttrExternal returns true for function symbols loaded from host
983 func (l *Loader) AttrExternal(i Sym) bool {
984 if !l.IsExternal(i) {
987 return l.attrExternal.Has(l.extIndex(i))
990 // SetAttrExternal sets the "external" property for an host object
991 // symbol (see AttrExternal).
992 func (l *Loader) SetAttrExternal(i Sym, v bool) {
993 if !l.IsExternal(i) {
994 panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.SymName(i)))
997 l.attrExternal.Set(l.extIndex(i))
999 l.attrExternal.Unset(l.extIndex(i))
1003 // AttrSpecial returns true for a symbols that do not have their
1004 // address (i.e. Value) computed by the usual mechanism of
1005 // data.go:dodata() & data.go:address().
1006 func (l *Loader) AttrSpecial(i Sym) bool {
1007 return l.attrSpecial.Has(i)
1010 // SetAttrSpecial sets the "special" property for a symbol (see
1012 func (l *Loader) SetAttrSpecial(i Sym, v bool) {
1014 l.attrSpecial.Set(i)
1016 l.attrSpecial.Unset(i)
1020 // AttrCgoExportDynamic returns true for a symbol that has been
1021 // specially marked via the "cgo_export_dynamic" compiler directive
1022 // written by cgo (in response to //export directives in the source).
1023 func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
1024 _, ok := l.attrCgoExportDynamic[i]
1028 // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
1029 // (see AttrCgoExportDynamic).
1030 func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
1032 l.attrCgoExportDynamic[i] = struct{}{}
1034 delete(l.attrCgoExportDynamic, i)
1038 // ForAllAttrCgoExportDynamic calls f for every symbol that has been
1039 // marked with the "cgo_export_dynamic" compiler directive.
1040 func (l *Loader) ForAllCgoExportDynamic(f func(Sym)) {
1041 for s := range l.attrCgoExportDynamic {
1046 // AttrCgoExportStatic returns true for a symbol that has been
1047 // specially marked via the "cgo_export_static" directive
1049 func (l *Loader) AttrCgoExportStatic(i Sym) bool {
1050 _, ok := l.attrCgoExportStatic[i]
1054 // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
1055 // (see AttrCgoExportStatic).
1056 func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
1058 l.attrCgoExportStatic[i] = struct{}{}
1060 delete(l.attrCgoExportStatic, i)
1064 // IsGeneratedSym returns true if a symbol's been previously marked as a
1065 // generator symbol through the SetIsGeneratedSym. The functions for generator
1066 // symbols are kept in the Link context.
1067 func (l *Loader) IsGeneratedSym(i Sym) bool {
1068 if !l.IsExternal(i) {
1071 return l.generatedSyms.Has(l.extIndex(i))
1074 // SetIsGeneratedSym marks symbols as generated symbols. Data shouldn't be
1075 // stored in generated symbols, and a function is registered and called for
1076 // each of these symbols.
1077 func (l *Loader) SetIsGeneratedSym(i Sym, v bool) {
1078 if !l.IsExternal(i) {
1079 panic("only external symbols can be generated")
1082 l.generatedSyms.Set(l.extIndex(i))
1084 l.generatedSyms.Unset(l.extIndex(i))
1088 func (l *Loader) AttrCgoExport(i Sym) bool {
1089 return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
1092 // AttrReadOnly returns true for a symbol whose underlying data
1093 // is stored via a read-only mmap.
1094 func (l *Loader) AttrReadOnly(i Sym) bool {
1095 if v, ok := l.attrReadOnly[i]; ok {
1098 if l.IsExternal(i) {
1099 pp := l.getPayload(i)
1101 return l.objs[pp.objidx].r.ReadOnly()
1105 r, _ := l.toLocal(i)
1109 // SetAttrReadOnly sets the "data is read only" property for a symbol
1110 // (see AttrReadOnly).
1111 func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
1112 l.attrReadOnly[i] = v
1115 // AttrSubSymbol returns true for symbols that are listed as a
1116 // sub-symbol of some other outer symbol. The sub/outer mechanism is
1117 // used when loading host objects (sections from the host object
1118 // become regular linker symbols and symbols go on the Sub list of
1119 // their section) and for constructing the global offset table when
1120 // internally linking a dynamic executable.
1122 // Note that in later stages of the linker, we set Outer(S) to some
1123 // container symbol C, but don't set Sub(C). Thus we have two
1124 // distinct scenarios:
1126 // - Outer symbol covers the address ranges of its sub-symbols.
1127 // Outer.Sub is set in this case.
1128 // - Outer symbol doesn't conver the address ranges. It is zero-sized
1129 // and doesn't have sub-symbols. In the case, the inner symbol is
1130 // not actually a "SubSymbol". (Tricky!)
1132 // This method returns TRUE only for sub-symbols in the first scenario.
1134 // FIXME: would be better to do away with this and have a better way
1135 // to represent container symbols.
1137 func (l *Loader) AttrSubSymbol(i Sym) bool {
1138 // we don't explicitly store this attribute any more -- return
1139 // a value based on the sub-symbol setting.
1144 return l.SubSym(o) != 0
1147 // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
1148 // clients should instead use the AddInteriorSym method to establish
1149 // containment relationships for host object symbols.
1151 // Returns whether the i-th symbol has ReflectMethod attribute set.
1152 func (l *Loader) IsReflectMethod(i Sym) bool {
1153 return l.SymAttr(i)&goobj.SymFlagReflectMethod != 0
1156 // Returns whether the i-th symbol is nosplit.
1157 func (l *Loader) IsNoSplit(i Sym) bool {
1158 return l.SymAttr(i)&goobj.SymFlagNoSplit != 0
1161 // Returns whether this is a Go type symbol.
1162 func (l *Loader) IsGoType(i Sym) bool {
1163 return l.SymAttr(i)&goobj.SymFlagGoType != 0
1166 // Returns whether this symbol should be included in typelink.
1167 func (l *Loader) IsTypelink(i Sym) bool {
1168 return l.SymAttr(i)&goobj.SymFlagTypelink != 0
1171 // Returns whether this symbol is an itab symbol.
1172 func (l *Loader) IsItab(i Sym) bool {
1173 if l.IsExternal(i) {
1176 r, li := l.toLocal(i)
1177 return r.Sym(li).IsItab()
1180 // Returns whether this symbol is a dictionary symbol.
1181 func (l *Loader) IsDict(i Sym) bool {
1182 if l.IsExternal(i) {
1185 r, li := l.toLocal(i)
1186 return r.Sym(li).IsDict()
1189 // Returns whether this symbol is a compiler-generated package init func.
1190 func (l *Loader) IsPkgInit(i Sym) bool {
1191 if l.IsExternal(i) {
1194 r, li := l.toLocal(i)
1195 return r.Sym(li).IsPkgInit()
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 // SymSect 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 offset of symbol s.
1451 func (l *Loader) SymPlt(s Sym) int32 {
1452 if v, ok := l.plt[s]; ok {
1458 // SetPlt sets the PLT offset of symbol i.
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 offset of symbol s.
1471 func (l *Loader) SymGot(s Sym) int32 {
1472 if v, ok := l.got[s]; ok {
1478 // SetGot sets the GOT offset of symbol i.
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 { return l.aux1(i, goobj.AuxGotype) }
1531 // SymUnit returns the compilation unit for a given symbol (which will
1532 // typically be nil for external or linker-manufactured symbols).
1533 func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
1534 if l.IsExternal(i) {
1535 pp := l.getPayload(i)
1537 r := l.objs[pp.objidx].r
1542 r, _ := l.toLocal(i)
1546 // SymPkg returns the package where the symbol came from (for
1547 // regular compiler-generated Go symbols), but in the case of
1548 // building with "-linkshared" (when a symbol is read from a
1549 // shared library), will hold the library name.
1550 // NOTE: this corresponds to sym.Symbol.File field.
1551 func (l *Loader) SymPkg(i Sym) string {
1552 if f, ok := l.symPkg[i]; ok {
1555 if l.IsExternal(i) {
1556 pp := l.getPayload(i)
1558 r := l.objs[pp.objidx].r
1559 return r.unit.Lib.Pkg
1563 r, _ := l.toLocal(i)
1564 return r.unit.Lib.Pkg
1567 // SetSymPkg sets the package/library for a symbol. This is
1568 // needed mainly for external symbols, specifically those imported
1569 // from shared libraries.
1570 func (l *Loader) SetSymPkg(i Sym, pkg string) {
1571 // reject bad symbols
1572 if i >= Sym(len(l.objSyms)) || i == 0 {
1573 panic("bad symbol index in SetSymPkg")
1578 // SymLocalentry returns an offset in bytes of the "local entry" of a symbol.
1579 func (l *Loader) SymLocalentry(i Sym) uint8 {
1580 return l.localentry[i]
1583 // SetSymLocalentry sets the "local entry" offset attribute for a symbol.
1584 func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
1585 // reject bad symbols
1586 if i >= Sym(len(l.objSyms)) || i == 0 {
1587 panic("bad symbol index in SetSymLocalentry")
1590 delete(l.localentry, i)
1592 l.localentry[i] = value
1596 // Returns the number of aux symbols given a global index.
1597 func (l *Loader) NAux(i Sym) int {
1598 if l.IsExternal(i) {
1601 r, li := l.toLocal(i)
1605 // Returns the "handle" to the j-th aux symbol of the i-th symbol.
1606 func (l *Loader) Aux(i Sym, j int) Aux {
1607 if l.IsExternal(i) {
1610 r, li := l.toLocal(i)
1611 if j >= r.NAux(li) {
1614 return Aux{r.Aux(li, j), r, l}
1617 // WasmImportSym returns the auxiliary WebAssembly import symbol associated with
1618 // a given function symbol. The aux sym only exists for Go function stubs that
1619 // have been annotated with the //go:wasmimport directive. The aux sym
1620 // contains the information necessary for the linker to add a WebAssembly
1621 // import statement.
1622 // (https://webassembly.github.io/spec/core/syntax/modules.html#imports)
1623 func (l *Loader) WasmImportSym(fnSymIdx Sym) (Sym, bool) {
1624 if l.SymType(fnSymIdx) != sym.STEXT {
1625 log.Fatalf("error: non-function sym %d/%s t=%s passed to WasmImportSym", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1627 r, li := l.toLocal(fnSymIdx)
1629 for i := range auxs {
1632 case goobj.AuxWasmImport:
1633 return l.resolve(r, a.Sym()), true
1640 // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
1641 // symbols associated with a given function symbol. Prior to the
1642 // introduction of the loader, this was done purely using name
1643 // lookups, e.f. for function with name XYZ we would then look up
1644 // go.info.XYZ, etc.
1645 func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
1646 if l.SymType(fnSymIdx) != sym.STEXT {
1647 log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1649 r, auxs := l.auxs(fnSymIdx)
1651 for i := range auxs {
1654 case goobj.AuxDwarfInfo:
1655 auxDwarfInfo = l.resolve(r, a.Sym())
1656 if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
1657 panic("aux dwarf info sym with wrong type")
1659 case goobj.AuxDwarfLoc:
1660 auxDwarfLoc = l.resolve(r, a.Sym())
1661 if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
1662 panic("aux dwarf loc sym with wrong type")
1664 case goobj.AuxDwarfRanges:
1665 auxDwarfRanges = l.resolve(r, a.Sym())
1666 if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
1667 panic("aux dwarf ranges sym with wrong type")
1669 case goobj.AuxDwarfLines:
1670 auxDwarfLines = l.resolve(r, a.Sym())
1671 if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
1672 panic("aux dwarf lines sym with wrong type")
1679 // AddInteriorSym sets up 'interior' as an interior symbol of
1680 // container/payload symbol 'container'. An interior symbol does not
1681 // itself have data, but gives a name to a subrange of the data in its
1682 // container symbol. The container itself may or may not have a name.
1683 // This method is intended primarily for use in the host object
1684 // loaders, to capture the semantics of symbols and sections in an
1685 // object file. When reading a host object file, we'll typically
1686 // encounter a static section symbol (ex: ".text") containing content
1687 // for a collection of functions, then a series of ELF (or macho, etc)
1688 // symbol table entries each of which points into a sub-section
1689 // (offset and length) of its corresponding container symbol. Within
1690 // the go linker we create a loader.Sym for the container (which is
1691 // expected to have the actual content/payload) and then a set of
1692 // interior loader.Sym's that point into a portion of the container.
1693 func (l *Loader) AddInteriorSym(container Sym, interior Sym) {
1694 // Container symbols are expected to have content/data.
1695 // NB: this restriction may turn out to be too strict (it's possible
1696 // to imagine a zero-sized container with an interior symbol pointing
1697 // into it); it's ok to relax or remove it if we counter an
1698 // oddball host object that triggers this.
1699 if l.SymSize(container) == 0 && len(l.Data(container)) == 0 {
1700 panic("unexpected empty container symbol")
1702 // The interior symbols for a container are not expected to have
1703 // content/data or relocations.
1704 if len(l.Data(interior)) != 0 {
1705 panic("unexpected non-empty interior symbol")
1707 // Interior symbol is expected to be in the symbol table.
1708 if l.AttrNotInSymbolTable(interior) {
1709 panic("interior symbol must be in symtab")
1711 // Only a single level of containment is allowed.
1712 if l.OuterSym(container) != 0 {
1713 panic("outer has outer itself")
1715 // Interior sym should not already have a sibling.
1716 if l.SubSym(interior) != 0 {
1717 panic("sub set for subsym")
1719 // Interior sym should not already point at a container.
1720 if l.OuterSym(interior) != 0 {
1721 panic("outer already set for subsym")
1723 l.sub[interior] = l.sub[container]
1724 l.sub[container] = interior
1725 l.outer[interior] = container
1728 // OuterSym gets the outer/container symbol.
1729 func (l *Loader) OuterSym(i Sym) Sym {
1733 // SubSym gets the subsymbol for host object loaded symbols.
1734 func (l *Loader) SubSym(i Sym) Sym {
1738 // growOuter grows the slice used to store outer symbol.
1739 func (l *Loader) growOuter(reqLen int) {
1740 curLen := len(l.outer)
1741 if reqLen > curLen {
1742 l.outer = append(l.outer, make([]Sym, reqLen-curLen)...)
1746 // SetCarrierSym declares that 'c' is the carrier or container symbol
1747 // for 's'. Carrier symbols are used in the linker to as a container
1748 // for a collection of sub-symbols where the content of the
1749 // sub-symbols is effectively concatenated to form the content of the
1750 // carrier. The carrier is given a name in the output symbol table
1751 // while the sub-symbol names are not. For example, the Go compiler
1752 // emits named string symbols (type SGOSTRING) when compiling a
1753 // package; after being deduplicated, these symbols are collected into
1754 // a single unit by assigning them a new carrier symbol named
1755 // "go:string.*" (which appears in the final symbol table for the
1756 // output load module).
1757 func (l *Loader) SetCarrierSym(s Sym, c Sym) {
1759 panic("invalid carrier in SetCarrierSym")
1762 panic("invalid sub-symbol in SetCarrierSym")
1764 // Carrier symbols are not expected to have content/data. It is
1765 // ok for them to have non-zero size (to allow for use of generator
1767 if len(l.Data(c)) != 0 {
1768 panic("unexpected non-empty carrier symbol")
1771 // relocsym's foldSubSymbolOffset requires that we only
1772 // have a single level of containment-- enforce here.
1773 if l.outer[c] != 0 {
1774 panic("invalid nested carrier sym")
1778 // Initialize Reachable bitmap and its siblings for running deadcode pass.
1779 func (l *Loader) InitReachable() {
1780 l.growAttrBitmaps(l.NSym() + 1)
1783 type symWithVal struct {
1787 type bySymValue []symWithVal
1789 func (s bySymValue) Len() int { return len(s) }
1790 func (s bySymValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1791 func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
1793 // SortSub walks through the sub-symbols for 's' and sorts them
1794 // in place by increasing value. Return value is the new
1795 // sub symbol for the specified outer symbol.
1796 func (l *Loader) SortSub(s Sym) Sym {
1798 if s == 0 || l.sub[s] == 0 {
1802 // Sort symbols using a slice first. Use a stable sort on the off
1803 // chance that there's more than once symbol with the same value,
1804 // so as to preserve reproducible builds.
1805 sl := []symWithVal{}
1806 for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
1807 sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
1809 sort.Stable(bySymValue(sl))
1811 // Then apply any changes needed to the sub map.
1813 for i := len(sl) - 1; i >= 0; i-- {
1819 // Update sub for outer symbol, then return
1824 // SortSyms sorts a list of symbols by their value.
1825 func (l *Loader) SortSyms(ss []Sym) {
1826 sort.SliceStable(ss, func(i, j int) bool { return l.SymValue(ss[i]) < l.SymValue(ss[j]) })
1829 // Insure that reachable bitmap and its siblings have enough size.
1830 func (l *Loader) growAttrBitmaps(reqLen int) {
1831 if reqLen > l.attrReachable.Len() {
1832 // These are indexed by global symbol
1833 l.attrReachable = growBitmap(reqLen, l.attrReachable)
1834 l.attrOnList = growBitmap(reqLen, l.attrOnList)
1835 l.attrLocal = growBitmap(reqLen, l.attrLocal)
1836 l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
1837 l.attrUsedInIface = growBitmap(reqLen, l.attrUsedInIface)
1838 l.attrSpecial = growBitmap(reqLen, l.attrSpecial)
1840 l.growExtAttrBitmaps()
1843 func (l *Loader) growExtAttrBitmaps() {
1844 // These are indexed by external symbol index (e.g. l.extIndex(i))
1845 extReqLen := len(l.payloads)
1846 if extReqLen > l.attrVisibilityHidden.Len() {
1847 l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
1848 l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
1849 l.attrShared = growBitmap(extReqLen, l.attrShared)
1850 l.attrExternal = growBitmap(extReqLen, l.attrExternal)
1851 l.generatedSyms = growBitmap(extReqLen, l.generatedSyms)
1855 func (relocs *Relocs) Count() int { return len(relocs.rs) }
1857 // At returns the j-th reloc for a global symbol.
1858 func (relocs *Relocs) At(j int) Reloc {
1859 if relocs.l.isExtReader(relocs.r) {
1860 return Reloc{&relocs.rs[j], relocs.r, relocs.l}
1862 return Reloc{&relocs.rs[j], relocs.r, relocs.l}
1865 // Relocs returns a Relocs object for the given global sym.
1866 func (l *Loader) Relocs(i Sym) Relocs {
1867 r, li := l.toLocal(i)
1869 panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
1871 return l.relocs(r, li)
1874 // relocs returns a Relocs object given a local sym index and reader.
1875 func (l *Loader) relocs(r *oReader, li uint32) Relocs {
1876 var rs []goobj.Reloc
1877 if l.isExtReader(r) {
1878 pp := l.payloads[li]
1891 func (l *Loader) auxs(i Sym) (*oReader, []goobj.Aux) {
1892 if l.IsExternal(i) {
1893 pp := l.getPayload(i)
1894 return l.objs[pp.objidx].r, pp.auxs
1896 r, li := l.toLocal(i)
1897 return r, r.Auxs(li)
1901 // Returns a specific aux symbol of type t for symbol i.
1902 func (l *Loader) aux1(i Sym, t uint8) Sym {
1903 r, auxs := l.auxs(i)
1904 for j := range auxs {
1907 return l.resolve(r, a.Sym())
1913 func (l *Loader) Pcsp(i Sym) Sym { return l.aux1(i, goobj.AuxPcsp) }
1915 // Returns all aux symbols of per-PC data for symbol i.
1916 // tmp is a scratch space for the pcdata slice.
1917 func (l *Loader) PcdataAuxs(i Sym, tmp []Sym) (pcsp, pcfile, pcline, pcinline Sym, pcdata []Sym) {
1919 r, auxs := l.auxs(i)
1920 for j := range auxs {
1924 pcsp = l.resolve(r, a.Sym())
1925 case goobj.AuxPcline:
1926 pcline = l.resolve(r, a.Sym())
1927 case goobj.AuxPcfile:
1928 pcfile = l.resolve(r, a.Sym())
1929 case goobj.AuxPcinline:
1930 pcinline = l.resolve(r, a.Sym())
1931 case goobj.AuxPcdata:
1932 pcdata = append(pcdata, l.resolve(r, a.Sym()))
1938 // Returns the number of pcdata for symbol i.
1939 func (l *Loader) NumPcdata(i Sym) int {
1941 _, auxs := l.auxs(i)
1942 for j := range auxs {
1944 if a.Type() == goobj.AuxPcdata {
1951 // Returns all funcdata symbols of symbol i.
1952 // tmp is a scratch space.
1953 func (l *Loader) Funcdata(i Sym, tmp []Sym) []Sym {
1955 r, auxs := l.auxs(i)
1956 for j := range auxs {
1958 if a.Type() == goobj.AuxFuncdata {
1959 fd = append(fd, l.resolve(r, a.Sym()))
1965 // Returns the number of funcdata for symbol i.
1966 func (l *Loader) NumFuncdata(i Sym) int {
1968 _, auxs := l.auxs(i)
1969 for j := range auxs {
1971 if a.Type() == goobj.AuxFuncdata {
1978 // FuncInfo provides hooks to access goobj.FuncInfo in the objects.
1979 type FuncInfo struct {
1983 lengths goobj.FuncInfoLengths
1986 func (fi *FuncInfo) Valid() bool { return fi.r != nil }
1988 func (fi *FuncInfo) Args() int {
1989 return int((*goobj.FuncInfo)(nil).ReadArgs(fi.data))
1992 func (fi *FuncInfo) Locals() int {
1993 return int((*goobj.FuncInfo)(nil).ReadLocals(fi.data))
1996 func (fi *FuncInfo) FuncID() abi.FuncID {
1997 return (*goobj.FuncInfo)(nil).ReadFuncID(fi.data)
2000 func (fi *FuncInfo) FuncFlag() abi.FuncFlag {
2001 return (*goobj.FuncInfo)(nil).ReadFuncFlag(fi.data)
2004 func (fi *FuncInfo) StartLine() int32 {
2005 return (*goobj.FuncInfo)(nil).ReadStartLine(fi.data)
2008 // Preload has to be called prior to invoking the various methods
2009 // below related to pcdata, funcdataoff, files, and inltree nodes.
2010 func (fi *FuncInfo) Preload() {
2011 fi.lengths = (*goobj.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
2014 func (fi *FuncInfo) NumFile() uint32 {
2015 if !fi.lengths.Initialized {
2016 panic("need to call Preload first")
2018 return fi.lengths.NumFile
2021 func (fi *FuncInfo) File(k int) goobj.CUFileIndex {
2022 if !fi.lengths.Initialized {
2023 panic("need to call Preload first")
2025 return (*goobj.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
2028 // TopFrame returns true if the function associated with this FuncInfo
2029 // is an entry point, meaning that unwinders should stop when they hit
2031 func (fi *FuncInfo) TopFrame() bool {
2032 return (fi.FuncFlag() & abi.FuncFlagTopFrame) != 0
2035 type InlTreeNode struct {
2037 File goobj.CUFileIndex
2043 func (fi *FuncInfo) NumInlTree() uint32 {
2044 if !fi.lengths.Initialized {
2045 panic("need to call Preload first")
2047 return fi.lengths.NumInlTree
2050 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
2051 if !fi.lengths.Initialized {
2052 panic("need to call Preload first")
2054 node := (*goobj.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
2056 Parent: node.Parent,
2059 Func: fi.l.resolve(fi.r, node.Func),
2060 ParentPC: node.ParentPC,
2064 func (l *Loader) FuncInfo(i Sym) FuncInfo {
2065 r, auxs := l.auxs(i)
2066 for j := range auxs {
2068 if a.Type() == goobj.AuxFuncInfo {
2069 b := r.Data(a.Sym().SymIdx)
2070 return FuncInfo{l, r, b, goobj.FuncInfoLengths{}}
2076 // Preload a package: adds autolib.
2077 // Does not add defined package or non-packaged symbols to the symbol table.
2078 // These are done in LoadSyms.
2079 // Does not read symbol data.
2080 // Returns the fingerprint of the object.
2081 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj.FingerprintType {
2082 roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
2084 log.Fatal("cannot read object file:", err)
2086 r := goobj.NewReaderFromBytes(roObject, readonly)
2088 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
2089 log.Fatalf("found object file %s in old format", f.File().Name())
2091 panic("cannot read object file")
2093 pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
2095 nhashed64def := r.NHashed64def()
2096 nhasheddef := r.NHasheddef()
2100 version: localSymVersion,
2101 pkgprefix: pkgprefix,
2102 syms: make([]Sym, ndef+nhashed64def+nhasheddef+r.NNonpkgdef()+r.NNonpkgref()),
2104 nhasheddef: nhasheddef,
2105 nhashed64def: nhashed64def,
2106 objidx: uint32(len(l.objs)),
2110 log.Fatalf("link: unlinkable object (from package %s) - compiler requires -p flag", lib.Pkg)
2114 lib.Autolib = append(lib.Autolib, r.Autolib()...)
2118 unit.FileTable = make([]string, nfile)
2119 for i := range unit.FileTable {
2120 unit.FileTable[i] = r.File(i)
2123 l.addObj(lib.Pkg, or)
2125 // The caller expects us consuming all the data
2126 f.MustSeek(length, io.SeekCurrent)
2128 return r.Fingerprint()
2131 // Holds the loader along with temporary states for loading symbols.
2132 type loadState struct {
2134 hashed64Syms map[uint64]symAndSize // short hashed (content-addressable) symbols, keyed by content hash
2135 hashedSyms map[goobj.HashType]symAndSize // hashed (content-addressable) symbols, keyed by content hash
2138 // Preload symbols of given kind from an object.
2139 func (st *loadState) preloadSyms(r *oReader, kind int) {
2141 var start, end uint32
2145 end = uint32(r.ndef)
2147 start = uint32(r.ndef)
2148 end = uint32(r.ndef + r.nhashed64def)
2150 start = uint32(r.ndef + r.nhashed64def)
2151 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2153 start = uint32(r.ndef + r.nhashed64def + r.nhasheddef)
2154 end = uint32(r.ndef + r.nhashed64def + r.nhasheddef + r.NNonpkgdef())
2156 panic("preloadSyms: bad kind")
2158 l.growAttrBitmaps(len(l.objSyms) + int(end-start))
2159 loadingRuntimePkg := r.unit.Lib.Pkg == "runtime"
2160 for i := start; i < end; i++ {
2164 if kind != hashed64Def && kind != hashedDef { // we don't need the name, etc. for hashed symbols
2165 name = osym.Name(r.Reader)
2166 v = abiToVer(osym.ABI(), r.version)
2168 gi := st.addSym(name, v, r, i, kind, osym)
2171 l.SetAttrLocal(gi, true)
2173 if osym.UsedInIface() {
2174 l.SetAttrUsedInIface(gi, true)
2176 if strings.HasPrefix(name, "runtime.") ||
2177 (loadingRuntimePkg && strings.HasPrefix(name, "type:")) {
2178 if bi := goobj.BuiltinIdx(name, int(osym.ABI())); bi != -1 {
2179 // This is a definition of a builtin symbol. Record where it is.
2180 l.builtinSyms[bi] = gi
2183 if a := int32(osym.Align()); a != 0 && a > l.SymAlign(gi) {
2184 l.SetSymAlign(gi, a)
2189 // Add syms, hashed (content-addressable) symbols, non-package symbols, and
2190 // references to external symbols (which are always named).
2191 func (l *Loader) LoadSyms(arch *sys.Arch) {
2192 // Allocate space for symbols, making a guess as to how much space we need.
2193 // This function was determined empirically by looking at the cmd/compile on
2194 // Darwin, and picking factors for hashed and hashed64 syms.
2195 var symSize, hashedSize, hashed64Size int
2196 for _, o := range l.objs[goObjStart:] {
2197 symSize += o.r.ndef + o.r.nhasheddef/2 + o.r.nhashed64def/2 + o.r.NNonpkgdef()
2198 hashedSize += o.r.nhasheddef / 2
2199 hashed64Size += o.r.nhashed64def / 2
2201 // Index 0 is invalid for symbols.
2202 l.objSyms = make([]objSym, 1, symSize)
2206 hashed64Syms: make(map[uint64]symAndSize, hashed64Size),
2207 hashedSyms: make(map[goobj.HashType]symAndSize, hashedSize),
2210 for _, o := range l.objs[goObjStart:] {
2211 st.preloadSyms(o.r, pkgDef)
2213 l.npkgsyms = l.NSym()
2214 for _, o := range l.objs[goObjStart:] {
2215 st.preloadSyms(o.r, hashed64Def)
2216 st.preloadSyms(o.r, hashedDef)
2217 st.preloadSyms(o.r, nonPkgDef)
2219 l.nhashedsyms = len(st.hashed64Syms) + len(st.hashedSyms)
2220 for _, o := range l.objs[goObjStart:] {
2221 loadObjRefs(l, o.r, arch)
2223 l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2224 l.outer = make([]Sym, l.NSym(), l.NSym()+1000)
2227 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2228 // load non-package refs
2229 ndef := uint32(r.NAlldef())
2230 for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2231 osym := r.Sym(ndef + i)
2232 name := osym.Name(r.Reader)
2233 v := abiToVer(osym.ABI(), r.version)
2234 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2235 gi := r.syms[ndef+i]
2237 l.SetAttrLocal(gi, true)
2239 if osym.UsedInIface() {
2240 l.SetAttrUsedInIface(gi, true)
2244 // referenced packages
2246 r.pkg = make([]uint32, npkg)
2247 for i := 1; i < npkg; i++ { // PkgIdx 0 is a dummy invalid package
2249 objidx, ok := l.objByPkg[pkg]
2251 log.Fatalf("%v: reference to nonexistent package %s", r.unit.Lib, pkg)
2256 // load flags of package refs
2257 for i, n := 0, r.NRefFlags(); i < n; i++ {
2259 gi := l.resolve(r, rf.Sym())
2260 if rf.Flag2()&goobj.SymFlagUsedInIface != 0 {
2261 l.SetAttrUsedInIface(gi, true)
2266 func abiToVer(abi uint16, localSymVersion int) int {
2268 if abi == goobj.SymABIstatic {
2271 } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2272 // Note that data symbols are "ABI0", which maps to version 0.
2275 log.Fatalf("invalid symbol ABI: %d", abi)
2280 // TopLevelSym tests a symbol (by name and kind) to determine whether
2281 // the symbol first class sym (participating in the link) or is an
2282 // anonymous aux or sub-symbol containing some sub-part or payload of
2284 func (l *Loader) TopLevelSym(s Sym) bool {
2285 return topLevelSym(l.SymName(s), l.SymType(s))
2288 // topLevelSym tests a symbol name and kind to determine whether
2289 // the symbol first class sym (participating in the link) or is an
2290 // anonymous aux or sub-symbol containing some sub-part or payload of
2292 func topLevelSym(sname string, skind sym.SymKind) bool {
2297 case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2304 // cloneToExternal takes the existing object file symbol (symIdx)
2305 // and creates a new external symbol payload that is a clone with
2306 // respect to name, version, type, relocations, etc. The idea here
2307 // is that if the linker decides it wants to update the contents of
2308 // a symbol originally discovered as part of an object file, it's
2309 // easier to do this if we make the updates to an external symbol
2311 func (l *Loader) cloneToExternal(symIdx Sym) {
2312 if l.IsExternal(symIdx) {
2313 panic("sym is already external, no need for clone")
2316 // Read the particulars from object.
2317 r, li := l.toLocal(symIdx)
2319 sname := osym.Name(r.Reader)
2320 sver := abiToVer(osym.ABI(), r.version)
2321 skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2323 // Create new symbol, update version and kind.
2324 pi := l.newPayload(sname, sver)
2325 pp := l.payloads[pi]
2328 pp.size = int64(osym.Siz())
2329 pp.objidx = r.objidx
2331 // If this is a def, then copy the guts. We expect this case
2332 // to be very rare (one case it may come up is with -X).
2333 if li < uint32(r.NAlldef()) {
2336 relocs := l.Relocs(symIdx)
2337 pp.relocs = make([]goobj.Reloc, relocs.Count())
2338 for i := range pp.relocs {
2339 // Copy the relocs slice.
2340 // Convert local reference to global reference.
2342 pp.relocs[i].Set(rel.Off(), rel.Siz(), uint16(rel.Type()), rel.Add(), goobj.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2346 pp.data = r.Data(li)
2349 // If we're overriding a data symbol, collect the associated
2350 // Gotype, so as to propagate it to the new symbol.
2354 // Install new payload to global index space.
2355 // (This needs to happen at the end, as the accessors above
2356 // need to access the old symbol content.)
2357 l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2358 l.extReader.syms = append(l.extReader.syms, symIdx)
2360 // Some attributes were encoded in the object file. Copy them over.
2361 l.SetAttrDuplicateOK(symIdx, r.Sym(li).Dupok())
2362 l.SetAttrShared(symIdx, r.Shared())
2365 // Copy the payload of symbol src to dst. Both src and dst must be external
2367 // The intended use case is that when building/linking against a shared library,
2368 // where we do symbol name mangling, the Go object file may have reference to
2369 // the original symbol name whereas the shared library provides a symbol with
2370 // the mangled name. When we do mangling, we copy payload of mangled to original.
2371 func (l *Loader) CopySym(src, dst Sym) {
2372 if !l.IsExternal(dst) {
2373 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2375 if !l.IsExternal(src) {
2376 panic("src is not external") //l.cloneToExternal(src)
2378 l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2379 l.SetSymPkg(dst, l.SymPkg(src))
2380 // TODO: other attributes?
2383 // CreateExtSym creates a new external symbol with the specified name
2384 // without adding it to any lookup tables, returning a Sym index for it.
2385 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2386 return l.newExtSym(name, ver)
2389 // CreateStaticSym creates a new static symbol with the specified name
2390 // without adding it to any lookup tables, returning a Sym index for it.
2391 func (l *Loader) CreateStaticSym(name string) Sym {
2392 // Assign a new unique negative version -- this is to mark the
2393 // symbol so that it is not included in the name lookup table.
2395 return l.newExtSym(name, l.anonVersion)
2398 func (l *Loader) FreeSym(i Sym) {
2399 if l.IsExternal(i) {
2400 pp := l.getPayload(i)
2401 *pp = extSymPayload{}
2405 // relocId is essentially a <S,R> tuple identifying the Rth
2406 // relocation of symbol S.
2407 type relocId struct {
2412 // SetRelocVariant sets the 'variant' property of a relocation on
2413 // some specific symbol.
2414 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2416 if relocs := l.Relocs(s); ri >= relocs.Count() {
2417 panic("invalid relocation ID")
2419 if l.relocVariant == nil {
2420 l.relocVariant = make(map[relocId]sym.RelocVariant)
2423 l.relocVariant[relocId{s, ri}] = v
2425 delete(l.relocVariant, relocId{s, ri})
2429 // RelocVariant returns the 'variant' property of a relocation on
2430 // some specific symbol.
2431 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2432 return l.relocVariant[relocId{s, ri}]
2435 // UndefinedRelocTargets iterates through the global symbol index
2436 // space, looking for symbols with relocations targeting undefined
2437 // references. The linker's loadlib method uses this to determine if
2438 // there are unresolved references to functions in system libraries
2439 // (for example, libgcc.a), presumably due to CGO code. Return value
2440 // is a pair of lists of loader.Sym's. First list corresponds to the
2441 // corresponding to the undefined symbols themselves, the second list
2442 // is the symbol that is making a reference to the undef. The "limit"
2443 // param controls the maximum number of results returned; if "limit"
2444 // is -1, then all undefs are returned.
2445 func (l *Loader) UndefinedRelocTargets(limit int) ([]Sym, []Sym) {
2446 result, fromr := []Sym{}, []Sym{}
2448 for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2449 relocs := l.Relocs(si)
2450 for ri := 0; ri < relocs.Count(); ri++ {
2453 if rs != 0 && l.SymType(rs) == sym.SXREF && l.SymName(rs) != ".got" {
2454 result = append(result, rs)
2455 fromr = append(fromr, si)
2456 if limit != -1 && len(result) >= limit {
2462 return result, fromr
2465 // AssignTextSymbolOrder populates the Textp slices within each
2466 // library and compilation unit, insuring that packages are laid down
2467 // in dependency order (internal first, then everything else). Return value
2468 // is a slice of all text syms.
2469 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2471 // Library Textp lists should be empty at this point.
2472 for _, lib := range libs {
2473 if len(lib.Textp) != 0 {
2474 panic("expected empty Textp slice for library")
2476 if len(lib.DupTextSyms) != 0 {
2477 panic("expected empty DupTextSyms slice for library")
2481 // Used to record which dupok symbol we've assigned to a unit.
2482 // Can't use the onlist attribute here because it will need to
2483 // clear for the later assignment of the sym.Symbol to a unit.
2484 // NB: we can convert to using onList once we no longer have to
2485 // call the regular addToTextp.
2486 assignedToUnit := MakeBitmap(l.NSym() + 1)
2488 // Start off textp with reachable external syms.
2490 for _, sym := range extsyms {
2491 if !l.attrReachable.Has(sym) {
2494 textp = append(textp, sym)
2497 // Walk through all text symbols from Go object files and append
2498 // them to their corresponding library's textp list.
2499 for _, o := range l.objs[goObjStart:] {
2502 for i, n := uint32(0), uint32(r.NAlldef()); i < n; i++ {
2503 gi := l.toGlobal(r, i)
2504 if !l.attrReachable.Has(gi) {
2508 st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2509 if st != sym.STEXT {
2512 dupok := osym.Dupok()
2513 if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2514 // A dupok text symbol is resolved to another package.
2515 // We still need to record its presence in the current
2516 // package, as the trampoline pass expects packages
2517 // are laid out in dependency order.
2518 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2519 continue // symbol in different object
2522 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2526 lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2530 // Now assemble global textp, and assign text symbols to units.
2531 for _, doInternal := range [2]bool{true, false} {
2532 for idx, lib := range libs {
2533 if intlibs[idx] != doInternal {
2536 lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2537 for i, list := range lists {
2538 for _, s := range list {
2540 if !assignedToUnit.Has(sym) {
2541 textp = append(textp, sym)
2542 unit := l.SymUnit(sym)
2544 unit.Textp = append(unit.Textp, s)
2545 assignedToUnit.Set(sym)
2547 // Dupok symbols may be defined in multiple packages; the
2548 // associated package for a dupok sym is chosen sort of
2549 // arbitrarily (the first containing package that the linker
2550 // loads). Canonicalizes its Pkg to the package with which
2551 // it will be laid down in text.
2552 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2553 l.SetSymPkg(sym, lib.Pkg)
2559 lib.DupTextSyms = nil
2566 // ErrorReporter is a helper class for reporting errors.
2567 type ErrorReporter struct {
2569 AfterErrorAction func()
2572 // Errorf method logs an error message.
2574 // After each error, the error actions function will be invoked; this
2575 // will either terminate the link immediately (if -h option given)
2576 // or it will keep a count and exit if more than 20 errors have been printed.
2578 // Logging an error means that on exit cmd/link will delete any
2579 // output file and return a non-zero error code.
2580 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2581 if s != 0 && reporter.ldr.SymName(s) != "" {
2582 // Note: Replace is needed here because symbol names might have % in them,
2583 // due to the use of LinkString for names of instantiating types.
2584 format = strings.Replace(reporter.ldr.SymName(s), "%", "%%", -1) + ": " + format
2586 format = fmt.Sprintf("sym %d: %s", s, format)
2589 fmt.Fprintf(os.Stderr, format, args...)
2590 reporter.AfterErrorAction()
2593 // GetErrorReporter returns the loader's associated error reporter.
2594 func (l *Loader) GetErrorReporter() *ErrorReporter {
2595 return l.errorReporter
2598 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2599 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2600 l.errorReporter.Errorf(s, format, args...)
2603 // Symbol statistics.
2604 func (l *Loader) Stat() string {
2605 s := fmt.Sprintf("%d symbols, %d reachable\n", l.NSym(), l.NReachableSym())
2606 s += fmt.Sprintf("\t%d package symbols, %d hashed symbols, %d non-package symbols, %d external symbols\n",
2607 l.npkgsyms, l.nhashedsyms, int(l.extStart)-l.npkgsyms-l.nhashedsyms, l.NSym()-int(l.extStart))
2612 func (l *Loader) Dump() {
2614 for _, obj := range l.objs[goObjStart:] {
2616 fmt.Println(obj.i, obj.r.unit.Lib)
2619 fmt.Println("extStart:", l.extStart)
2620 fmt.Println("Nsyms:", len(l.objSyms))
2622 for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2624 if l.IsExternal(i) {
2625 pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2628 if l.SymSect(i) != nil {
2629 sect = l.SymSect(i).Name
2631 fmt.Printf("%v %v %v %v %x %v\n", i, l.SymName(i), l.SymType(i), pi, l.SymValue(i), sect)
2633 fmt.Println("symsByName")
2634 for name, i := range l.symsByName[0] {
2635 fmt.Println(i, name, 0)
2637 for name, i := range l.symsByName[1] {
2638 fmt.Println(i, name, 1)
2640 fmt.Println("payloads:")
2641 for i := range l.payloads {
2643 fmt.Println(i, pp.name, pp.ver, pp.kind)