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 // Reloc contains the payload for a specific relocation.
42 // TODO: replace this with sym.Reloc, once we change the
43 // relocation target from "*sym.Symbol" to "loader.Sym" in sym.Reloc.
45 Off int32 // offset to rewrite
46 Size uint8 // number of bytes to rewrite: 0, 1, 2, or 4
47 Type objabi.RelocType // the relocation type
49 Sym Sym // global index of symbol the reloc addresses
52 // ExtReloc contains the payload for an external relocation.
53 type ExtReloc struct {
54 Idx int // index of the original relocation
59 // ExtRelocView is a view of an external relocation.
60 // It is intended to be constructed on the fly, such as ExtRelocs.At.
61 // It is not the data structure used to store the payload internally.
62 type ExtRelocView struct {
67 // Reloc2 holds a "handle" to access a relocation record from an
74 // External reloc types may not fit into a uint8 which the Go object file uses.
75 // Store it here, instead of in the byte of goobj2.Reloc2.
76 // For Go symbols this will always be zero.
77 // goobj2.Reloc2.Type() + typ is always the right type, for both Go and external
82 func (rel Reloc2) Type() objabi.RelocType { return objabi.RelocType(rel.Reloc.Type()) + rel.typ }
83 func (rel Reloc2) Sym() Sym { return rel.l.resolve(rel.r, rel.Reloc.Sym()) }
84 func (rel Reloc2) SetSym(s Sym) { rel.Reloc.SetSym(goobj2.SymRef{PkgIdx: 0, SymIdx: uint32(s)}) }
86 func (rel Reloc2) SetType(t objabi.RelocType) {
87 if t != objabi.RelocType(uint8(t)) {
88 panic("SetType: type doesn't fit into Reloc2")
90 rel.Reloc.SetType(uint8(t))
92 // should use SymbolBuilder.SetRelocType
93 panic("wrong method to set reloc type")
97 // Aux2 holds a "handle" to access an aux symbol record from an
105 func (a Aux2) Sym() Sym { return a.l.resolve(a.r, a.Aux.Sym()) }
107 // oReader is a wrapper type of obj.Reader, along with some
108 // extra information.
109 // TODO: rename to objReader once the old one is gone?
110 type oReader struct {
112 unit *sym.CompilationUnit
113 version int // version of static symbol
114 flags uint32 // read from object file
116 syms []Sym // Sym's global index, indexed by local index
117 ndef int // cache goobj2.Reader.NSym()
118 objidx uint32 // index of this reader in the objs slice
126 // objSym represents a symbol in an object file. It is a tuple of
127 // the object and the symbol's local index.
128 // For external symbols, objidx is the index of l.extReader (extObj),
129 // s is its index into the payload array.
130 // {0, 0} represents the nil symbol.
132 objidx uint32 // index of the object (in l.objs array)
133 s uint32 // local index
136 type nameVer struct {
144 func (bm Bitmap) Set(i Sym) {
145 n, r := uint(i)/32, uint(i)%32
149 // unset the i-th bit.
150 func (bm Bitmap) Unset(i Sym) {
151 n, r := uint(i)/32, uint(i)%32
155 // whether the i-th bit is set.
156 func (bm Bitmap) Has(i Sym) bool {
157 n, r := uint(i)/32, uint(i)%32
158 return bm[n]&(1<<r) != 0
161 // return current length of bitmap in bits.
162 func (bm Bitmap) Len() int {
166 // return the number of bits set.
167 func (bm Bitmap) Count() int {
169 for _, x := range bm {
170 s += bits.OnesCount32(x)
175 func MakeBitmap(n int) Bitmap {
176 return make(Bitmap, (n+31)/32)
179 // growBitmap insures that the specified bitmap has enough capacity,
180 // reallocating (doubling the size) if needed.
181 func growBitmap(reqLen int, b Bitmap) Bitmap {
184 b = append(b, MakeBitmap(reqLen+1-curLen)...)
189 // A Loader loads new object files and resolves indexed symbol references.
191 // Notes on the layout of global symbol index space:
193 // - Go object files are read before host object files; each Go object
194 // read adds its defined package symbols to the global index space.
195 // Nonpackage symbols are not yet added.
197 // - In loader.LoadNonpkgSyms, add non-package defined symbols and
198 // references in all object files to the global index space.
200 // - Host object file loading happens; the host object loader does a
201 // name/version lookup for each symbol it finds; this can wind up
202 // extending the external symbol index space range. The host object
203 // loader stores symbol payloads in loader.payloads using SymbolBuilder.
205 // - Each symbol gets a unique global index. For duplicated and
206 // overwriting/overwritten symbols, the second (or later) appearance
207 // of the symbol gets the same global index as the first appearance.
209 start map[*oReader]Sym // map from object file to its start index
210 objs []objIdx // sorted by start index (i.e. objIdx.i)
211 extStart Sym // from this index on, the symbols are externally defined
212 builtinSyms []Sym // global index of builtin symbols
214 objSyms []objSym // global index mapping to local index
216 symsByName [2]map[string]Sym // map symbol name to index, two maps are for ABI0 and ABIInternal
217 extStaticSyms map[nameVer]Sym // externally defined static symbols, keyed by name
219 extReader *oReader // a dummy oReader, for external symbols
220 payloadBatch []extSymPayload
221 payloads []*extSymPayload // contents of linker-materialized external syms
222 values []int64 // symbol values, indexed by global sym index
224 sects []*sym.Section // sections
225 symSects []uint16 // symbol's section, index to sects array
227 align []uint8 // symbol 2^N alignment, indexed by global index
229 outdata [][]byte // symbol's data in the output buffer
230 extRelocs [][]ExtReloc // symbol's external relocations
232 itablink map[Sym]struct{} // itablink[j] defined if j is go.itablink.*
233 deferReturnTramp map[Sym]bool // whether the symbol is a trampoline of a deferreturn call
235 objByPkg map[string]*oReader // map package path to its Go object reader
237 anonVersion int // most recently assigned ext static sym pseudo-version
239 // Bitmaps and other side structures used to store data used to store
240 // symbol flags/attributes; these are to be accessed via the
241 // corresponding loader "AttrXXX" and "SetAttrXXX" methods. Please
242 // visit the comments on these methods for more details on the
243 // semantics / interpretation of the specific flags or attribute.
244 attrReachable Bitmap // reachable symbols, indexed by global index
245 attrOnList Bitmap // "on list" symbols, indexed by global index
246 attrLocal Bitmap // "local" symbols, indexed by global index
247 attrNotInSymbolTable Bitmap // "not in symtab" symbols, indexed by glob idx
248 attrVisibilityHidden Bitmap // hidden symbols, indexed by ext sym index
249 attrDuplicateOK Bitmap // dupOK symbols, indexed by ext sym index
250 attrShared Bitmap // shared symbols, indexed by ext sym index
251 attrExternal Bitmap // external symbols, indexed by ext sym index
253 attrReadOnly map[Sym]bool // readonly data for this sym
254 attrTopFrame map[Sym]struct{} // top frame symbols
255 attrSpecial map[Sym]struct{} // "special" frame symbols
256 attrCgoExportDynamic map[Sym]struct{} // "cgo_export_dynamic" symbols
257 attrCgoExportStatic map[Sym]struct{} // "cgo_export_static" symbols
259 // Outer and Sub relations for symbols.
260 // TODO: figure out whether it's more efficient to just have these
261 // as fields on extSymPayload (note that this won't be a viable
262 // strategy if somewhere in the linker we set sub/outer for a
263 // non-external sym).
267 dynimplib map[Sym]string // stores Dynimplib symbol attribute
268 dynimpvers map[Sym]string // stores Dynimpvers symbol attribute
269 localentry map[Sym]uint8 // stores Localentry symbol attribute
270 extname map[Sym]string // stores Extname symbol attribute
271 elfType map[Sym]elf.SymType // stores elf type symbol property
272 elfSym map[Sym]int32 // stores elf sym symbol property
273 localElfSym map[Sym]int32 // stores "local" elf sym symbol property
274 symPkg map[Sym]string // stores package for symbol, or library for shlib-derived syms
275 plt map[Sym]int32 // stores dynimport for pe objects
276 got map[Sym]int32 // stores got for pe objects
277 dynid map[Sym]int32 // stores Dynid for symbol
279 relocVariant map[relocId]sym.RelocVariant // stores variant relocs
281 // Used to implement field tracking; created during deadcode if
282 // field tracking is enabled. Reachparent[K] contains the index of
283 // the symbol that triggered the marking of symbol K as live.
288 strictDupMsgs int // number of strict-dup warning/errors, when FlagStrictDups is enabled
290 elfsetstring elfsetstringFunc
292 errorReporter *ErrorReporter
308 type elfsetstringFunc func(str string, off int)
310 // extSymPayload holds the payload (data + relocations) for linker-synthesized
311 // external symbols (note that symbol value is stored in a separate slice).
312 type extSymPayload struct {
313 name string // TODO: would this be better as offset into str table?
317 objidx uint32 // index of original object if sym made by cloneToExternal
318 relocs []goobj2.Reloc
319 reltypes []objabi.RelocType // relocation types
326 FlagStrictDups = 1 << iota
329 func NewLoader(flags uint32, elfsetstring elfsetstringFunc, reporter *ErrorReporter) *Loader {
330 nbuiltin := goobj2.NBuiltin()
331 extReader := &oReader{objidx: extObj}
333 start: make(map[*oReader]Sym),
334 objs: []objIdx{{}, {extReader, 0}}, // reserve index 0 for nil symbol, 1 for external symbols
335 objSyms: make([]objSym, 1, 100000), // reserve index 0 for nil symbol
336 extReader: extReader,
337 symsByName: [2]map[string]Sym{make(map[string]Sym, 100000), make(map[string]Sym, 50000)}, // preallocate ~2MB for ABI0 and ~1MB for ABI1 symbols
338 objByPkg: make(map[string]*oReader),
339 outer: make(map[Sym]Sym),
340 sub: make(map[Sym]Sym),
341 dynimplib: make(map[Sym]string),
342 dynimpvers: make(map[Sym]string),
343 localentry: make(map[Sym]uint8),
344 extname: make(map[Sym]string),
345 attrReadOnly: make(map[Sym]bool),
346 elfType: make(map[Sym]elf.SymType),
347 elfSym: make(map[Sym]int32),
348 localElfSym: make(map[Sym]int32),
349 symPkg: make(map[Sym]string),
350 plt: make(map[Sym]int32),
351 got: make(map[Sym]int32),
352 dynid: make(map[Sym]int32),
353 attrTopFrame: make(map[Sym]struct{}),
354 attrSpecial: make(map[Sym]struct{}),
355 attrCgoExportDynamic: make(map[Sym]struct{}),
356 attrCgoExportStatic: make(map[Sym]struct{}),
357 itablink: make(map[Sym]struct{}),
358 deferReturnTramp: make(map[Sym]bool),
359 extStaticSyms: make(map[nameVer]Sym),
360 builtinSyms: make([]Sym, nbuiltin),
362 elfsetstring: elfsetstring,
363 errorReporter: reporter,
364 sects: []*sym.Section{nil}, // reserve index 0 for nil section
370 // Add object file r, return the start index.
371 func (l *Loader) addObj(pkg string, r *oReader) Sym {
372 if _, ok := l.start[r]; ok {
373 panic("already added")
375 pkg = objabi.PathToPrefix(pkg) // the object file contains escaped package path
376 if _, ok := l.objByPkg[pkg]; !ok {
379 i := Sym(len(l.objSyms))
381 l.objs = append(l.objs, objIdx{r, i})
385 // Add a symbol from an object file, return the global index and whether it is added.
386 // If the symbol already exist, it returns the index of that symbol.
387 func (l *Loader) AddSym(name string, ver int, r *oReader, li uint32, kind int, dupok bool, typ sym.SymKind) (Sym, bool) {
389 panic("AddSym called after external symbol is created")
391 i := Sym(len(l.objSyms))
392 addToGlobal := func() {
393 l.objSyms = append(l.objSyms, objSym{r.objidx, li})
397 return i, true // unnamed aux symbol
399 if ver == r.version {
400 // Static symbol. Add its global index but don't
401 // add to name lookup table, as it cannot be
402 // referenced by name.
407 // Defined package symbols cannot be dup to each other.
408 // We load all the package symbols first, so we don't need
409 // to check dup here.
410 // We still add it to the lookup table, as it may still be
411 // referenced by name (e.g. through linkname).
412 l.symsByName[ver][name] = i
417 // Non-package (named) symbol. Check if it already exists.
418 oldi, existed := l.symsByName[ver][name]
420 l.symsByName[ver][name] = i
424 // symbol already exists
426 if l.flags&FlagStrictDups != 0 {
427 l.checkdup(name, r, li, oldi)
431 oldr, oldli := l.toLocal(oldi)
432 oldsym := oldr.Sym(oldli)
436 overwrite := r.DataSize(li) != 0
438 // new symbol overwrites old symbol.
439 oldtyp := sym.AbiSymKindToSymKind[objabi.SymKind(oldsym.Type())]
440 if !(oldtyp.IsData() && oldr.DataSize(oldli) == 0) {
441 log.Fatalf("duplicated definition of symbol " + name)
443 l.objSyms[oldi] = objSym{r.objidx, li}
445 // old symbol overwrites new symbol.
446 if !typ.IsData() { // only allow overwriting data symbol
447 log.Fatalf("duplicated definition of symbol " + name)
453 // newExtSym creates a new external sym with the specified
455 func (l *Loader) newExtSym(name string, ver int) Sym {
456 i := Sym(len(l.objSyms))
460 l.growValues(int(i) + 1)
461 l.growAttrBitmaps(int(i) + 1)
462 pi := l.newPayload(name, ver)
463 l.objSyms = append(l.objSyms, objSym{l.extReader.objidx, uint32(pi)})
464 l.extReader.syms = append(l.extReader.syms, i)
468 // LookupOrCreateSym looks up the symbol with the specified name/version,
469 // returning its Sym index if found. If the lookup fails, a new external
470 // Sym will be created, entered into the lookup tables, and returned.
471 func (l *Loader) LookupOrCreateSym(name string, ver int) Sym {
472 i := l.Lookup(name, ver)
476 i = l.newExtSym(name, ver)
477 static := ver >= sym.SymVerStatic || ver < 0
479 l.extStaticSyms[nameVer{name, ver}] = i
481 l.symsByName[ver][name] = i
486 func (l *Loader) IsExternal(i Sym) bool {
488 return l.isExtReader(r)
491 func (l *Loader) isExtReader(r *oReader) bool {
492 return r == l.extReader
495 // For external symbol, return its index in the payloads array.
496 // XXX result is actually not a global index. We (ab)use the Sym type
497 // so we don't need conversion for accessing bitmaps.
498 func (l *Loader) extIndex(i Sym) Sym {
499 _, li := l.toLocal(i)
503 // Get a new payload for external symbol, return its index in
504 // the payloads array.
505 func (l *Loader) newPayload(name string, ver int) int {
506 pi := len(l.payloads)
507 pp := l.allocPayload()
510 l.payloads = append(l.payloads, pp)
511 l.growExtAttrBitmaps()
515 // getPayload returns a pointer to the extSymPayload struct for an
516 // external symbol if the symbol has a payload. Will panic if the
517 // symbol in question is bogus (zero or not an external sym).
518 func (l *Loader) getPayload(i Sym) *extSymPayload {
519 if !l.IsExternal(i) {
520 panic(fmt.Sprintf("bogus symbol index %d in getPayload", i))
523 return l.payloads[pi]
526 // allocPayload allocates a new payload.
527 func (l *Loader) allocPayload() *extSymPayload {
528 batch := l.payloadBatch
530 batch = make([]extSymPayload, 1000)
533 l.payloadBatch = batch[1:]
537 func (ms *extSymPayload) Grow(siz int64) {
538 if int64(int(siz)) != siz {
539 log.Fatalf("symgrow size %d too long", siz)
541 if int64(len(ms.data)) >= siz {
544 if cap(ms.data) < int(siz) {
546 ms.data = append(ms.data, make([]byte, int(siz)+1-cl)...)
547 ms.data = ms.data[0:cl]
549 ms.data = ms.data[:siz]
552 // Convert a local index to a global index.
553 func (l *Loader) toGlobal(r *oReader, i uint32) Sym {
557 // Convert a global index to a local index.
558 func (l *Loader) toLocal(i Sym) (*oReader, uint32) {
559 return l.objs[l.objSyms[i].objidx].r, l.objSyms[i].s
562 // Resolve a local symbol reference. Return global index.
563 func (l *Loader) resolve(r *oReader, s goobj2.SymRef) Sym {
565 switch p := s.PkgIdx; p {
566 case goobj2.PkgIdxInvalid:
567 // {0, X} with non-zero X is never a valid sym reference from a Go object.
568 // We steal this space for symbol references from external objects.
569 // In this case, X is just the global index.
570 if l.isExtReader(r) {
577 case goobj2.PkgIdxNone:
578 i := int(s.SymIdx) + r.ndef
580 case goobj2.PkgIdxBuiltin:
581 return l.builtinSyms[s.SymIdx]
582 case goobj2.PkgIdxSelf:
587 rr, ok = l.objByPkg[pkg]
589 log.Fatalf("reference of nonexisted package %s, from %v", pkg, r.unit.Lib)
592 return l.toGlobal(rr, s.SymIdx)
595 // Look up a symbol by name, return global index, or 0 if not found.
596 // This is more like Syms.ROLookup than Lookup -- it doesn't create
598 func (l *Loader) Lookup(name string, ver int) Sym {
599 if ver >= sym.SymVerStatic || ver < 0 {
600 return l.extStaticSyms[nameVer{name, ver}]
602 return l.symsByName[ver][name]
605 // Check that duplicate symbols have same contents.
606 func (l *Loader) checkdup(name string, r *oReader, li uint32, dup Sym) {
608 rdup, ldup := l.toLocal(dup)
609 pdup := rdup.Data(ldup)
610 if bytes.Equal(p, pdup) {
613 reason := "same length but different contents"
614 if len(p) != len(pdup) {
615 reason = fmt.Sprintf("new length %d != old length %d", len(p), len(pdup))
617 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)
619 // For the moment, allow DWARF subprogram DIEs for
620 // auto-generated wrapper functions. What seems to happen
621 // here is that we get different line numbers on formal
622 // params; I am guessing that the pos is being inherited
623 // from the spot where the wrapper is needed.
624 allowed := strings.HasPrefix(name, "go.info.go.interface") ||
625 strings.HasPrefix(name, "go.info.go.builtin") ||
626 strings.HasPrefix(name, "go.debuglines")
632 func (l *Loader) NStrictDupMsgs() int { return l.strictDupMsgs }
634 // Number of total symbols.
635 func (l *Loader) NSym() int {
636 return len(l.objSyms)
639 // Number of defined Go symbols.
640 func (l *Loader) NDef() int {
641 return int(l.extStart)
644 // Number of reachable symbols.
645 func (l *Loader) NReachableSym() int {
646 return l.attrReachable.Count()
649 // Returns the raw (unpatched) name of the i-th symbol.
650 func (l *Loader) RawSymName(i Sym) string {
652 pp := l.getPayload(i)
655 r, li := l.toLocal(i)
656 return r.Sym(li).Name(r.Reader)
659 // Returns the (patched) name of the i-th symbol.
660 func (l *Loader) SymName(i Sym) string {
662 pp := l.getPayload(i)
665 r, li := l.toLocal(i)
666 name := r.Sym(li).Name(r.Reader)
667 if !r.NeedNameExpansion() {
670 return strings.Replace(name, "\"\".", r.pkgprefix, -1)
673 // Returns the version of the i-th symbol.
674 func (l *Loader) SymVersion(i Sym) int {
676 pp := l.getPayload(i)
679 r, li := l.toLocal(i)
680 return int(abiToVer(r.Sym(li).ABI(), r.version))
683 func (l *Loader) IsFileLocal(i Sym) bool { return l.SymVersion(i) >= sym.SymVerStatic }
685 // Returns the type of the i-th symbol.
686 func (l *Loader) SymType(i Sym) sym.SymKind {
688 pp := l.getPayload(i)
694 r, li := l.toLocal(i)
695 return sym.AbiSymKindToSymKind[objabi.SymKind(r.Sym(li).Type())]
698 // Returns the attributes of the i-th symbol.
699 func (l *Loader) SymAttr(i Sym) uint8 {
701 // TODO: do something? External symbols have different representation of attributes.
702 // For now, ReflectMethod, NoSplit, GoType, and Typelink are used and they cannot be
703 // set by external symbol.
706 r, li := l.toLocal(i)
707 return r.Sym(li).Flag()
710 // Returns the size of the i-th symbol.
711 func (l *Loader) SymSize(i Sym) int64 {
713 pp := l.getPayload(i)
716 r, li := l.toLocal(i)
717 return int64(r.Sym(li).Siz())
720 // AttrReachable returns true for symbols that are transitively
721 // referenced from the entry points. Unreachable symbols are not
722 // written to the output.
723 func (l *Loader) AttrReachable(i Sym) bool {
724 return l.attrReachable.Has(i)
727 // SetAttrReachable sets the reachability property for a symbol (see
729 func (l *Loader) SetAttrReachable(i Sym, v bool) {
731 l.attrReachable.Set(i)
733 l.attrReachable.Unset(i)
737 // AttrOnList returns true for symbols that are on some list (such as
738 // the list of all text symbols, or one of the lists of data symbols)
739 // and is consulted to avoid bugs where a symbol is put on a list
741 func (l *Loader) AttrOnList(i Sym) bool {
742 return l.attrOnList.Has(i)
745 // SetAttrOnList sets the "on list" property for a symbol (see
747 func (l *Loader) SetAttrOnList(i Sym, v bool) {
751 l.attrOnList.Unset(i)
755 // AttrLocal returns true for symbols that are only visible within the
756 // module (executable or shared library) being linked. This attribute
757 // is applied to thunks and certain other linker-generated symbols.
758 func (l *Loader) AttrLocal(i Sym) bool {
759 return l.attrLocal.Has(i)
762 // SetAttrLocal the "local" property for a symbol (see AttrLocal above).
763 func (l *Loader) SetAttrLocal(i Sym, v bool) {
771 // SymAddr checks that a symbol is reachable, and returns its value.
772 func (l *Loader) SymAddr(i Sym) int64 {
773 if !l.AttrReachable(i) {
774 panic("unreachable symbol in symaddr")
779 // AttrNotInSymbolTable returns true for symbols that should not be
780 // added to the symbol table of the final generated load module.
781 func (l *Loader) AttrNotInSymbolTable(i Sym) bool {
782 return l.attrNotInSymbolTable.Has(i)
785 // SetAttrNotInSymbolTable the "not in symtab" property for a symbol
786 // (see AttrNotInSymbolTable above).
787 func (l *Loader) SetAttrNotInSymbolTable(i Sym, v bool) {
789 l.attrNotInSymbolTable.Set(i)
791 l.attrNotInSymbolTable.Unset(i)
795 // AttrVisibilityHidden symbols returns true for ELF symbols with
796 // visibility set to STV_HIDDEN. They become local symbols in
797 // the final executable. Only relevant when internally linking
798 // on an ELF platform.
799 func (l *Loader) AttrVisibilityHidden(i Sym) bool {
800 if !l.IsExternal(i) {
803 return l.attrVisibilityHidden.Has(l.extIndex(i))
806 // SetAttrVisibilityHidden sets the "hidden visibility" property for a
807 // symbol (see AttrVisibilityHidden).
808 func (l *Loader) SetAttrVisibilityHidden(i Sym, v bool) {
809 if !l.IsExternal(i) {
810 panic("tried to set visibility attr on non-external symbol")
813 l.attrVisibilityHidden.Set(l.extIndex(i))
815 l.attrVisibilityHidden.Unset(l.extIndex(i))
819 // AttrDuplicateOK returns true for a symbol that can be present in
820 // multiple object files.
821 func (l *Loader) AttrDuplicateOK(i Sym) bool {
822 if !l.IsExternal(i) {
823 // TODO: if this path winds up being taken frequently, it
824 // might make more sense to copy the flag value out of the object
825 // into a larger bitmap during preload.
826 r, li := l.toLocal(i)
827 return r.Sym(li).Dupok()
829 return l.attrDuplicateOK.Has(l.extIndex(i))
832 // SetAttrDuplicateOK sets the "duplicate OK" property for an external
833 // symbol (see AttrDuplicateOK).
834 func (l *Loader) SetAttrDuplicateOK(i Sym, v bool) {
835 if !l.IsExternal(i) {
836 panic("tried to set dupok attr on non-external symbol")
839 l.attrDuplicateOK.Set(l.extIndex(i))
841 l.attrDuplicateOK.Unset(l.extIndex(i))
845 // AttrShared returns true for symbols compiled with the -shared option.
846 func (l *Loader) AttrShared(i Sym) bool {
847 if !l.IsExternal(i) {
848 // TODO: if this path winds up being taken frequently, it
849 // might make more sense to copy the flag value out of the
850 // object into a larger bitmap during preload.
854 return l.attrShared.Has(l.extIndex(i))
857 // SetAttrShared sets the "shared" property for an external
858 // symbol (see AttrShared).
859 func (l *Loader) SetAttrShared(i Sym, v bool) {
860 if !l.IsExternal(i) {
861 panic(fmt.Sprintf("tried to set shared attr on non-external symbol %d %s", i, l.SymName(i)))
864 l.attrShared.Set(l.extIndex(i))
866 l.attrShared.Unset(l.extIndex(i))
870 // AttrExternal returns true for function symbols loaded from host
872 func (l *Loader) AttrExternal(i Sym) bool {
873 if !l.IsExternal(i) {
876 return l.attrExternal.Has(l.extIndex(i))
879 // SetAttrExternal sets the "external" property for an host object
880 // symbol (see AttrExternal).
881 func (l *Loader) SetAttrExternal(i Sym, v bool) {
882 if !l.IsExternal(i) {
883 panic(fmt.Sprintf("tried to set external attr on non-external symbol %q", l.RawSymName(i)))
886 l.attrExternal.Set(l.extIndex(i))
888 l.attrExternal.Unset(l.extIndex(i))
892 // AttrTopFrame returns true for a function symbol that is an entry
893 // point, meaning that unwinders should stop when they hit this
895 func (l *Loader) AttrTopFrame(i Sym) bool {
896 _, ok := l.attrTopFrame[i]
900 // SetAttrTopFrame sets the "top frame" property for a symbol (see
902 func (l *Loader) SetAttrTopFrame(i Sym, v bool) {
904 l.attrTopFrame[i] = struct{}{}
906 delete(l.attrTopFrame, i)
910 // AttrSpecial returns true for a symbols that do not have their
911 // address (i.e. Value) computed by the usual mechanism of
912 // data.go:dodata() & data.go:address().
913 func (l *Loader) AttrSpecial(i Sym) bool {
914 _, ok := l.attrSpecial[i]
918 // SetAttrSpecial sets the "special" property for a symbol (see
920 func (l *Loader) SetAttrSpecial(i Sym, v bool) {
922 l.attrSpecial[i] = struct{}{}
924 delete(l.attrSpecial, i)
928 // AttrCgoExportDynamic returns true for a symbol that has been
929 // specially marked via the "cgo_export_dynamic" compiler directive
930 // written by cgo (in response to //export directives in the source).
931 func (l *Loader) AttrCgoExportDynamic(i Sym) bool {
932 _, ok := l.attrCgoExportDynamic[i]
936 // SetAttrCgoExportDynamic sets the "cgo_export_dynamic" for a symbol
937 // (see AttrCgoExportDynamic).
938 func (l *Loader) SetAttrCgoExportDynamic(i Sym, v bool) {
940 l.attrCgoExportDynamic[i] = struct{}{}
942 delete(l.attrCgoExportDynamic, i)
946 // AttrCgoExportStatic returns true for a symbol that has been
947 // specially marked via the "cgo_export_static" directive
949 func (l *Loader) AttrCgoExportStatic(i Sym) bool {
950 _, ok := l.attrCgoExportStatic[i]
954 // SetAttrCgoExportStatic sets the "cgo_export_static" for a symbol
955 // (see AttrCgoExportStatic).
956 func (l *Loader) SetAttrCgoExportStatic(i Sym, v bool) {
958 l.attrCgoExportStatic[i] = struct{}{}
960 delete(l.attrCgoExportStatic, i)
964 func (l *Loader) AttrCgoExport(i Sym) bool {
965 return l.AttrCgoExportDynamic(i) || l.AttrCgoExportStatic(i)
968 // AttrReadOnly returns true for a symbol whose underlying data
969 // is stored via a read-only mmap.
970 func (l *Loader) AttrReadOnly(i Sym) bool {
971 if v, ok := l.attrReadOnly[i]; ok {
975 pp := l.getPayload(i)
977 return l.objs[pp.objidx].r.ReadOnly()
985 // SetAttrReadOnly sets the "data is read only" property for a symbol
986 // (see AttrReadOnly).
987 func (l *Loader) SetAttrReadOnly(i Sym, v bool) {
988 l.attrReadOnly[i] = v
991 // AttrSubSymbol returns true for symbols that are listed as a
992 // sub-symbol of some other outer symbol. The sub/outer mechanism is
993 // used when loading host objects (sections from the host object
994 // become regular linker symbols and symbols go on the Sub list of
995 // their section) and for constructing the global offset table when
996 // internally linking a dynamic executable.
998 // Note that in later stages of the linker, we set Outer(S) to some
999 // container symbol C, but don't set Sub(C). Thus we have two
1000 // distinct scenarios:
1002 // - Outer symbol covers the address ranges of its sub-symbols.
1003 // Outer.Sub is set in this case.
1004 // - Outer symbol doesn't conver the address ranges. It is zero-sized
1005 // and doesn't have sub-symbols. In the case, the inner symbol is
1006 // not actually a "SubSymbol". (Tricky!)
1008 // This method returns TRUE only for sub-symbols in the first scenario.
1010 // FIXME: would be better to do away with this and have a better way
1011 // to represent container symbols.
1013 func (l *Loader) AttrSubSymbol(i Sym) bool {
1014 // we don't explicitly store this attribute any more -- return
1015 // a value based on the sub-symbol setting.
1020 return l.SubSym(o) != 0
1023 // Note that we don't have a 'SetAttrSubSymbol' method in the loader;
1024 // clients should instead use the PrependSub method to establish
1025 // outer/sub relationships for host object symbols.
1027 // Returns whether the i-th symbol has ReflectMethod attribute set.
1028 func (l *Loader) IsReflectMethod(i Sym) bool {
1029 return l.SymAttr(i)&goobj2.SymFlagReflectMethod != 0
1032 // Returns whether the i-th symbol is nosplit.
1033 func (l *Loader) IsNoSplit(i Sym) bool {
1034 return l.SymAttr(i)&goobj2.SymFlagNoSplit != 0
1037 // Returns whether this is a Go type symbol.
1038 func (l *Loader) IsGoType(i Sym) bool {
1039 return l.SymAttr(i)&goobj2.SymFlagGoType != 0
1042 // Returns whether this symbol should be included in typelink.
1043 func (l *Loader) IsTypelink(i Sym) bool {
1044 return l.SymAttr(i)&goobj2.SymFlagTypelink != 0
1047 // Returns whether this is a "go.itablink.*" symbol.
1048 func (l *Loader) IsItabLink(i Sym) bool {
1049 if _, ok := l.itablink[i]; ok {
1055 // Return whether this is a trampoline of a deferreturn call.
1056 func (l *Loader) IsDeferReturnTramp(i Sym) bool {
1057 return l.deferReturnTramp[i]
1060 // Set that i is a trampoline of a deferreturn call.
1061 func (l *Loader) SetIsDeferReturnTramp(i Sym, v bool) {
1062 l.deferReturnTramp[i] = v
1065 // growValues grows the slice used to store symbol values.
1066 func (l *Loader) growValues(reqLen int) {
1067 curLen := len(l.values)
1068 if reqLen > curLen {
1069 l.values = append(l.values, make([]int64, reqLen+1-curLen)...)
1073 // SymValue returns the value of the i-th symbol. i is global index.
1074 func (l *Loader) SymValue(i Sym) int64 {
1078 // SetSymValue sets the value of the i-th symbol. i is global index.
1079 func (l *Loader) SetSymValue(i Sym, val int64) {
1083 // AddToSymValue adds to the value of the i-th symbol. i is the global index.
1084 func (l *Loader) AddToSymValue(i Sym, val int64) {
1088 // Returns the symbol content of the i-th symbol. i is global index.
1089 func (l *Loader) Data(i Sym) []byte {
1090 if l.IsExternal(i) {
1091 pp := l.getPayload(i)
1097 r, li := l.toLocal(i)
1101 // Returns the data of the i-th symbol in the output buffer.
1102 func (l *Loader) OutData(i Sym) []byte {
1103 if int(i) < len(l.outdata) && l.outdata[i] != nil {
1109 // SetOutData sets the position of the data of the i-th symbol in the output buffer.
1110 // i is global index.
1111 func (l *Loader) SetOutData(i Sym, data []byte) {
1112 if l.IsExternal(i) {
1113 pp := l.getPayload(i)
1122 // InitOutData initializes the slice used to store symbol output data.
1123 func (l *Loader) InitOutData() {
1124 l.outdata = make([][]byte, l.extStart)
1127 // SetExtRelocs sets the external relocations of the i-th symbol. i is global index.
1128 func (l *Loader) SetExtRelocs(i Sym, relocs []ExtReloc) {
1129 l.extRelocs[i] = relocs
1132 // InitExtRelocs initialize the slice used to store external relocations.
1133 func (l *Loader) InitExtRelocs() {
1134 l.extRelocs = make([][]ExtReloc, l.NSym())
1137 // SymAlign returns the alignment for a symbol.
1138 func (l *Loader) SymAlign(i Sym) int32 {
1139 if int(i) >= len(l.align) {
1140 // align is extended lazily -- it the sym in question is
1141 // outside the range of the existing slice, then we assume its
1142 // alignment has not yet been set.
1145 // TODO: would it make sense to return an arch-specific
1146 // alignment depending on section type? E.g. STEXT => 32,
1152 return int32(1 << (abits - 1))
1155 // SetSymAlign sets the alignment for a symbol.
1156 func (l *Loader) SetSymAlign(i Sym, align int32) {
1157 // Reject nonsense alignments.
1158 if align < 0 || align&(align-1) != 0 {
1159 panic("bad alignment value")
1161 if int(i) >= len(l.align) {
1162 l.align = append(l.align, make([]uint8, l.NSym()-len(l.align))...)
1167 l.align[i] = uint8(bits.Len32(uint32(align)))
1170 // SymValue returns the section of the i-th symbol. i is global index.
1171 func (l *Loader) SymSect(i Sym) *sym.Section {
1172 if int(i) >= len(l.symSects) {
1173 // symSects is extended lazily -- it the sym in question is
1174 // outside the range of the existing slice, then we assume its
1175 // section has not yet been set.
1178 return l.sects[l.symSects[i]]
1181 // SetSymSect sets the section of the i-th symbol. i is global index.
1182 func (l *Loader) SetSymSect(i Sym, sect *sym.Section) {
1183 if int(i) >= len(l.symSects) {
1184 l.symSects = append(l.symSects, make([]uint16, l.NSym()-len(l.symSects))...)
1186 l.symSects[i] = sect.Index
1189 // growSects grows the slice used to store symbol sections.
1190 func (l *Loader) growSects(reqLen int) {
1191 curLen := len(l.symSects)
1192 if reqLen > curLen {
1193 l.symSects = append(l.symSects, make([]uint16, reqLen+1-curLen)...)
1197 // NewSection creates a new (output) section.
1198 func (l *Loader) NewSection() *sym.Section {
1199 sect := new(sym.Section)
1201 if idx != int(uint16(idx)) {
1202 panic("too many sections created")
1204 sect.Index = uint16(idx)
1205 l.sects = append(l.sects, sect)
1209 // SymDynImplib returns the "dynimplib" attribute for the specified
1210 // symbol, making up a portion of the info for a symbol specified
1211 // on a "cgo_import_dynamic" compiler directive.
1212 func (l *Loader) SymDynimplib(i Sym) string {
1213 return l.dynimplib[i]
1216 // SetSymDynimplib sets the "dynimplib" attribute for a symbol.
1217 func (l *Loader) SetSymDynimplib(i Sym, value string) {
1218 // reject bad symbols
1219 if i >= Sym(len(l.objSyms)) || i == 0 {
1220 panic("bad symbol index in SetDynimplib")
1223 delete(l.dynimplib, i)
1225 l.dynimplib[i] = value
1229 // SymDynimpvers returns the "dynimpvers" attribute for the specified
1230 // symbol, making up a portion of the info for a symbol specified
1231 // on a "cgo_import_dynamic" compiler directive.
1232 func (l *Loader) SymDynimpvers(i Sym) string {
1233 return l.dynimpvers[i]
1236 // SetSymDynimpvers sets the "dynimpvers" attribute for a symbol.
1237 func (l *Loader) SetSymDynimpvers(i Sym, value string) {
1238 // reject bad symbols
1239 if i >= Sym(len(l.objSyms)) || i == 0 {
1240 panic("bad symbol index in SetDynimpvers")
1243 delete(l.dynimpvers, i)
1245 l.dynimpvers[i] = value
1249 // SymExtname returns the "extname" value for the specified
1251 func (l *Loader) SymExtname(i Sym) string {
1252 if s, ok := l.extname[i]; ok {
1258 // SetSymExtname sets the "extname" attribute for a symbol.
1259 func (l *Loader) SetSymExtname(i Sym, value string) {
1260 // reject bad symbols
1261 if i >= Sym(len(l.objSyms)) || i == 0 {
1262 panic("bad symbol index in SetExtname")
1265 delete(l.extname, i)
1267 l.extname[i] = value
1271 // SymElfType returns the previously recorded ELF type for a symbol
1272 // (used only for symbols read from shared libraries by ldshlibsyms).
1273 // It is not set for symbols defined by the packages being linked or
1274 // by symbols read by ldelf (and so is left as elf.STT_NOTYPE).
1275 func (l *Loader) SymElfType(i Sym) elf.SymType {
1276 if et, ok := l.elfType[i]; ok {
1279 return elf.STT_NOTYPE
1282 // SetSymElfType sets the elf type attribute for a symbol.
1283 func (l *Loader) SetSymElfType(i Sym, et elf.SymType) {
1284 // reject bad symbols
1285 if i >= Sym(len(l.objSyms)) || i == 0 {
1286 panic("bad symbol index in SetSymElfType")
1288 if et == elf.STT_NOTYPE {
1289 delete(l.elfType, i)
1295 // SymElfSym returns the ELF symbol index for a given loader
1296 // symbol, assigned during ELF symtab generation.
1297 func (l *Loader) SymElfSym(i Sym) int32 {
1301 // SetSymElfSym sets the elf symbol index for a symbol.
1302 func (l *Loader) SetSymElfSym(i Sym, es int32) {
1304 panic("bad sym index")
1313 // SymLocalElfSym returns the "local" ELF symbol index for a given loader
1314 // symbol, assigned during ELF symtab generation.
1315 func (l *Loader) SymLocalElfSym(i Sym) int32 {
1316 return l.localElfSym[i]
1319 // SetSymLocalElfSym sets the "local" elf symbol index for a symbol.
1320 func (l *Loader) SetSymLocalElfSym(i Sym, es int32) {
1322 panic("bad sym index")
1325 delete(l.localElfSym, i)
1327 l.localElfSym[i] = es
1331 // SymPlt returns the plt value for pe symbols.
1332 func (l *Loader) SymPlt(s Sym) int32 {
1333 if v, ok := l.plt[s]; ok {
1339 // SetPlt sets the plt value for pe symbols.
1340 func (l *Loader) SetPlt(i Sym, v int32) {
1341 if i >= Sym(len(l.objSyms)) || i == 0 {
1342 panic("bad symbol for SetPlt")
1351 // SymGot returns the got value for pe symbols.
1352 func (l *Loader) SymGot(s Sym) int32 {
1353 if v, ok := l.got[s]; ok {
1359 // SetGot sets the got value for pe symbols.
1360 func (l *Loader) SetGot(i Sym, v int32) {
1361 if i >= Sym(len(l.objSyms)) || i == 0 {
1362 panic("bad symbol for SetGot")
1371 // SymDynid returns the "dynid" property for the specified symbol.
1372 func (l *Loader) SymDynid(i Sym) int32 {
1373 if s, ok := l.dynid[i]; ok {
1379 // SetSymDynid sets the "dynid" property for a symbol.
1380 func (l *Loader) SetSymDynid(i Sym, val int32) {
1381 // reject bad symbols
1382 if i >= Sym(len(l.objSyms)) || i == 0 {
1383 panic("bad symbol index in SetSymDynid")
1392 // DynIdSyms returns the set of symbols for which dynID is set to an
1393 // interesting (non-default) value. This is expected to be a fairly
1395 func (l *Loader) DynidSyms() []Sym {
1396 sl := make([]Sym, 0, len(l.dynid))
1397 for s := range l.dynid {
1400 sort.Slice(sl, func(i, j int) bool { return sl[i] < sl[j] })
1404 // SymGoType returns the 'Gotype' property for a given symbol (set by
1405 // the Go compiler for variable symbols). This version relies on
1406 // reading aux symbols for the target sym -- it could be that a faster
1407 // approach would be to check for gotype during preload and copy the
1408 // results in to a map (might want to try this at some point and see
1409 // if it helps speed things up).
1410 func (l *Loader) SymGoType(i Sym) Sym {
1412 var auxs []goobj2.Aux
1413 if l.IsExternal(i) {
1414 pp := l.getPayload(i)
1415 r = l.objs[pp.objidx].r
1419 r, li = l.toLocal(i)
1422 for j := range auxs {
1425 case goobj2.AuxGotype:
1426 return l.resolve(r, a.Sym())
1432 // SymUnit returns the compilation unit for a given symbol (which will
1433 // typically be nil for external or linker-manufactured symbols).
1434 func (l *Loader) SymUnit(i Sym) *sym.CompilationUnit {
1435 if l.IsExternal(i) {
1436 pp := l.getPayload(i)
1438 r := l.objs[pp.objidx].r
1443 r, _ := l.toLocal(i)
1447 // SymPkg returns the package where the symbol came from (for
1448 // regular compiler-generated Go symbols), but in the case of
1449 // building with "-linkshared" (when a symbol is read from a
1450 // shared library), will hold the library name.
1451 // NOTE: this correspondes to sym.Symbol.File field.
1452 func (l *Loader) SymPkg(i Sym) string {
1453 if f, ok := l.symPkg[i]; ok {
1456 if l.IsExternal(i) {
1457 pp := l.getPayload(i)
1459 r := l.objs[pp.objidx].r
1460 return r.unit.Lib.Pkg
1464 r, _ := l.toLocal(i)
1465 return r.unit.Lib.Pkg
1468 // SetSymPkg sets the package/library for a symbol. This is
1469 // needed mainly for external symbols, specifically those imported
1470 // from shared libraries.
1471 func (l *Loader) SetSymPkg(i Sym, pkg string) {
1472 // reject bad symbols
1473 if i >= Sym(len(l.objSyms)) || i == 0 {
1474 panic("bad symbol index in SetSymPkg")
1479 // SymLocalentry returns the "local entry" value for the specified
1481 func (l *Loader) SymLocalentry(i Sym) uint8 {
1482 return l.localentry[i]
1485 // SetSymLocalentry sets the "local entry" attribute for a symbol.
1486 func (l *Loader) SetSymLocalentry(i Sym, value uint8) {
1487 // reject bad symbols
1488 if i >= Sym(len(l.objSyms)) || i == 0 {
1489 panic("bad symbol index in SetSymLocalentry")
1492 delete(l.localentry, i)
1494 l.localentry[i] = value
1498 // Returns the number of aux symbols given a global index.
1499 func (l *Loader) NAux(i Sym) int {
1500 if l.IsExternal(i) {
1503 r, li := l.toLocal(i)
1507 // Returns the "handle" to the j-th aux symbol of the i-th symbol.
1508 func (l *Loader) Aux2(i Sym, j int) Aux2 {
1509 if l.IsExternal(i) {
1512 r, li := l.toLocal(i)
1513 if j >= r.NAux(li) {
1516 return Aux2{r.Aux(li, j), r, l}
1519 // GetFuncDwarfAuxSyms collects and returns the auxiliary DWARF
1520 // symbols associated with a given function symbol. Prior to the
1521 // introduction of the loader, this was done purely using name
1522 // lookups, e.f. for function with name XYZ we would then look up
1523 // go.info.XYZ, etc.
1524 // FIXME: once all of dwarfgen is converted over to the loader,
1525 // it would save some space to make these aux symbols nameless.
1526 func (l *Loader) GetFuncDwarfAuxSyms(fnSymIdx Sym) (auxDwarfInfo, auxDwarfLoc, auxDwarfRanges, auxDwarfLines Sym) {
1527 if l.SymType(fnSymIdx) != sym.STEXT {
1528 log.Fatalf("error: non-function sym %d/%s t=%s passed to GetFuncDwarfAuxSyms", fnSymIdx, l.SymName(fnSymIdx), l.SymType(fnSymIdx).String())
1530 if l.IsExternal(fnSymIdx) {
1531 // Current expectation is that any external function will
1532 // not have auxsyms.
1535 r, li := l.toLocal(fnSymIdx)
1537 for i := range auxs {
1540 case goobj2.AuxDwarfInfo:
1541 auxDwarfInfo = l.resolve(r, a.Sym())
1542 if l.SymType(auxDwarfInfo) != sym.SDWARFFCN {
1543 panic("aux dwarf info sym with wrong type")
1545 case goobj2.AuxDwarfLoc:
1546 auxDwarfLoc = l.resolve(r, a.Sym())
1547 if l.SymType(auxDwarfLoc) != sym.SDWARFLOC {
1548 panic("aux dwarf loc sym with wrong type")
1550 case goobj2.AuxDwarfRanges:
1551 auxDwarfRanges = l.resolve(r, a.Sym())
1552 if l.SymType(auxDwarfRanges) != sym.SDWARFRANGE {
1553 panic("aux dwarf ranges sym with wrong type")
1555 case goobj2.AuxDwarfLines:
1556 auxDwarfLines = l.resolve(r, a.Sym())
1557 if l.SymType(auxDwarfLines) != sym.SDWARFLINES {
1558 panic("aux dwarf lines sym with wrong type")
1565 // PrependSub prepends 'sub' onto the sub list for outer symbol 'outer'.
1566 // Will panic if 'sub' already has an outer sym or sub sym.
1567 // FIXME: should this be instead a method on SymbolBuilder?
1568 func (l *Loader) PrependSub(outer Sym, sub Sym) {
1569 // NB: this presupposes that an outer sym can't be a sub symbol of
1570 // some other outer-outer sym (I'm assuming this is true, but I
1571 // haven't tested exhaustively).
1572 if l.OuterSym(outer) != 0 {
1573 panic("outer has outer itself")
1575 if l.SubSym(sub) != 0 {
1576 panic("sub set for subsym")
1578 if l.OuterSym(sub) != 0 {
1579 panic("outer already set for subsym")
1581 l.sub[sub] = l.sub[outer]
1583 l.outer[sub] = outer
1586 // OuterSym gets the outer symbol for host object loaded symbols.
1587 func (l *Loader) OuterSym(i Sym) Sym {
1588 // FIXME: add check for isExternal?
1592 // SubSym gets the subsymbol for host object loaded symbols.
1593 func (l *Loader) SubSym(i Sym) Sym {
1594 // NB: note -- no check for l.isExternal(), since I am pretty sure
1595 // that later phases in the linker set subsym for "type." syms
1599 // SetOuterSym sets the outer symbol of i to o (without setting
1601 func (l *Loader) SetOuterSym(i Sym, o Sym) {
1604 // relocsym's foldSubSymbolOffset requires that we only
1605 // have a single level of containment-- enforce here.
1606 if l.outer[o] != 0 {
1607 panic("multiply nested outer sym")
1614 // Initialize Reachable bitmap and its siblings for running deadcode pass.
1615 func (l *Loader) InitReachable() {
1616 l.growAttrBitmaps(l.NSym() + 1)
1619 type symWithVal struct {
1623 type bySymValue []symWithVal
1625 func (s bySymValue) Len() int { return len(s) }
1626 func (s bySymValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
1627 func (s bySymValue) Less(i, j int) bool { return s[i].v < s[j].v }
1629 // SortSub walks through the sub-symbols for 's' and sorts them
1630 // in place by increasing value. Return value is the new
1631 // sub symbol for the specified outer symbol.
1632 func (l *Loader) SortSub(s Sym) Sym {
1634 if s == 0 || l.sub[s] == 0 {
1638 // Sort symbols using a slice first. Use a stable sort on the off
1639 // chance that there's more than once symbol with the same value,
1640 // so as to preserve reproducible builds.
1641 sl := []symWithVal{}
1642 for ss := l.sub[s]; ss != 0; ss = l.sub[ss] {
1643 sl = append(sl, symWithVal{s: ss, v: l.SymValue(ss)})
1645 sort.Stable(bySymValue(sl))
1647 // Then apply any changes needed to the sub map.
1649 for i := len(sl) - 1; i >= 0; i-- {
1655 // Update sub for outer symbol, then return
1660 // Insure that reachable bitmap and its siblings have enough size.
1661 func (l *Loader) growAttrBitmaps(reqLen int) {
1662 if reqLen > l.attrReachable.Len() {
1663 // These are indexed by global symbol
1664 l.attrReachable = growBitmap(reqLen, l.attrReachable)
1665 l.attrOnList = growBitmap(reqLen, l.attrOnList)
1666 l.attrLocal = growBitmap(reqLen, l.attrLocal)
1667 l.attrNotInSymbolTable = growBitmap(reqLen, l.attrNotInSymbolTable)
1669 l.growExtAttrBitmaps()
1672 func (l *Loader) growExtAttrBitmaps() {
1673 // These are indexed by external symbol index (e.g. l.extIndex(i))
1674 extReqLen := len(l.payloads)
1675 if extReqLen > l.attrVisibilityHidden.Len() {
1676 l.attrVisibilityHidden = growBitmap(extReqLen, l.attrVisibilityHidden)
1677 l.attrDuplicateOK = growBitmap(extReqLen, l.attrDuplicateOK)
1678 l.attrShared = growBitmap(extReqLen, l.attrShared)
1679 l.attrExternal = growBitmap(extReqLen, l.attrExternal)
1683 func (relocs *Relocs) Count() int { return len(relocs.rs) }
1685 // At2 returns the j-th reloc for a global symbol.
1686 func (relocs *Relocs) At2(j int) Reloc2 {
1687 if relocs.l.isExtReader(relocs.r) {
1688 pp := relocs.l.payloads[relocs.li]
1689 return Reloc2{&relocs.rs[j], relocs.r, relocs.l, pp.reltypes[j]}
1691 return Reloc2{&relocs.rs[j], relocs.r, relocs.l, 0}
1694 // Relocs returns a Relocs object for the given global sym.
1695 func (l *Loader) Relocs(i Sym) Relocs {
1696 r, li := l.toLocal(i)
1698 panic(fmt.Sprintf("trying to get oreader for invalid sym %d\n\n", i))
1700 return l.relocs(r, li)
1703 // Relocs returns a Relocs object given a local sym index and reader.
1704 func (l *Loader) relocs(r *oReader, li uint32) Relocs {
1705 var rs []goobj2.Reloc
1706 if l.isExtReader(r) {
1707 pp := l.payloads[li]
1720 // ExtRelocs returns the external relocations of the i-th symbol.
1721 func (l *Loader) ExtRelocs(i Sym) ExtRelocs {
1722 return ExtRelocs{l.Relocs(i), l.extRelocs[i]}
1725 // ExtRelocs represents the set of external relocations of a symbol.
1726 type ExtRelocs struct {
1731 func (ers ExtRelocs) Count() int { return len(ers.es) }
1733 func (ers ExtRelocs) At(j int) ExtRelocView {
1735 return ExtRelocView{ers.rs.At2(i), &ers.es[j]}
1738 // RelocByOff implements sort.Interface for sorting relocations by offset.
1740 type RelocByOff []Reloc
1742 func (x RelocByOff) Len() int { return len(x) }
1743 func (x RelocByOff) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
1744 func (x RelocByOff) Less(i, j int) bool { return x[i].Off < x[j].Off }
1746 // FuncInfo provides hooks to access goobj2.FuncInfo in the objects.
1747 type FuncInfo struct {
1752 lengths goobj2.FuncInfoLengths
1755 func (fi *FuncInfo) Valid() bool { return fi.r != nil }
1757 func (fi *FuncInfo) Args() int {
1758 return int((*goobj2.FuncInfo)(nil).ReadArgs(fi.data))
1761 func (fi *FuncInfo) Locals() int {
1762 return int((*goobj2.FuncInfo)(nil).ReadLocals(fi.data))
1765 func (fi *FuncInfo) Pcsp() []byte {
1766 pcsp, end := (*goobj2.FuncInfo)(nil).ReadPcsp(fi.data)
1767 return fi.r.BytesAt(fi.r.PcdataBase()+pcsp, int(end-pcsp))
1770 func (fi *FuncInfo) Pcfile() []byte {
1771 pcf, end := (*goobj2.FuncInfo)(nil).ReadPcfile(fi.data)
1772 return fi.r.BytesAt(fi.r.PcdataBase()+pcf, int(end-pcf))
1775 func (fi *FuncInfo) Pcline() []byte {
1776 pcln, end := (*goobj2.FuncInfo)(nil).ReadPcline(fi.data)
1777 return fi.r.BytesAt(fi.r.PcdataBase()+pcln, int(end-pcln))
1780 // Preload has to be called prior to invoking the various methods
1781 // below related to pcdata, funcdataoff, files, and inltree nodes.
1782 func (fi *FuncInfo) Preload() {
1783 fi.lengths = (*goobj2.FuncInfo)(nil).ReadFuncInfoLengths(fi.data)
1786 func (fi *FuncInfo) Pcinline() []byte {
1787 if !fi.lengths.Initialized {
1788 panic("need to call Preload first")
1790 pcinl, end := (*goobj2.FuncInfo)(nil).ReadPcinline(fi.data, fi.lengths.PcdataOff)
1791 return fi.r.BytesAt(fi.r.PcdataBase()+pcinl, int(end-pcinl))
1794 func (fi *FuncInfo) NumPcdata() uint32 {
1795 if !fi.lengths.Initialized {
1796 panic("need to call Preload first")
1798 return fi.lengths.NumPcdata
1801 func (fi *FuncInfo) Pcdata(k int) []byte {
1802 if !fi.lengths.Initialized {
1803 panic("need to call Preload first")
1805 pcdat, end := (*goobj2.FuncInfo)(nil).ReadPcdata(fi.data, fi.lengths.PcdataOff, uint32(k))
1806 return fi.r.BytesAt(fi.r.PcdataBase()+pcdat, int(end-pcdat))
1809 func (fi *FuncInfo) NumFuncdataoff() uint32 {
1810 if !fi.lengths.Initialized {
1811 panic("need to call Preload first")
1813 return fi.lengths.NumFuncdataoff
1816 func (fi *FuncInfo) Funcdataoff(k int) int64 {
1817 if !fi.lengths.Initialized {
1818 panic("need to call Preload first")
1820 return (*goobj2.FuncInfo)(nil).ReadFuncdataoff(fi.data, fi.lengths.FuncdataoffOff, uint32(k))
1823 func (fi *FuncInfo) Funcdata(syms []Sym) []Sym {
1824 if !fi.lengths.Initialized {
1825 panic("need to call Preload first")
1827 if int(fi.lengths.NumFuncdataoff) > cap(syms) {
1828 syms = make([]Sym, 0, fi.lengths.NumFuncdataoff)
1832 for j := range fi.auxs {
1834 if a.Type() == goobj2.AuxFuncdata {
1835 syms = append(syms, fi.l.resolve(fi.r, a.Sym()))
1841 func (fi *FuncInfo) NumFile() uint32 {
1842 if !fi.lengths.Initialized {
1843 panic("need to call Preload first")
1845 return fi.lengths.NumFile
1848 func (fi *FuncInfo) File(k int) Sym {
1849 if !fi.lengths.Initialized {
1850 panic("need to call Preload first")
1852 sr := (*goobj2.FuncInfo)(nil).ReadFile(fi.data, fi.lengths.FileOff, uint32(k))
1853 return fi.l.resolve(fi.r, sr)
1856 type InlTreeNode struct {
1864 func (fi *FuncInfo) NumInlTree() uint32 {
1865 if !fi.lengths.Initialized {
1866 panic("need to call Preload first")
1868 return fi.lengths.NumInlTree
1871 func (fi *FuncInfo) InlTree(k int) InlTreeNode {
1872 if !fi.lengths.Initialized {
1873 panic("need to call Preload first")
1875 node := (*goobj2.FuncInfo)(nil).ReadInlTree(fi.data, fi.lengths.InlTreeOff, uint32(k))
1877 Parent: node.Parent,
1878 File: fi.l.resolve(fi.r, node.File),
1880 Func: fi.l.resolve(fi.r, node.Func),
1881 ParentPC: node.ParentPC,
1885 func (l *Loader) FuncInfo(i Sym) FuncInfo {
1887 var auxs []goobj2.Aux
1888 if l.IsExternal(i) {
1889 pp := l.getPayload(i)
1893 r = l.objs[pp.objidx].r
1897 r, li = l.toLocal(i)
1900 for j := range auxs {
1902 if a.Type() == goobj2.AuxFuncInfo {
1903 b := r.Data(a.Sym().SymIdx)
1904 return FuncInfo{l, r, b, auxs, goobj2.FuncInfoLengths{}}
1910 // Preload a package: add autolibs, add defined package symbols to the symbol table.
1911 // Does not add non-package symbols yet, which will be done in LoadNonpkgSyms.
1912 // Does not read symbol data.
1913 // Returns the fingerprint of the object.
1914 func (l *Loader) Preload(localSymVersion int, f *bio.Reader, lib *sym.Library, unit *sym.CompilationUnit, length int64) goobj2.FingerprintType {
1915 roObject, readonly, err := f.Slice(uint64(length)) // TODO: no need to map blocks that are for tools only (e.g. RefName)
1917 log.Fatal("cannot read object file:", err)
1919 r := goobj2.NewReaderFromBytes(roObject, readonly)
1921 if len(roObject) >= 8 && bytes.Equal(roObject[:8], []byte("\x00go114ld")) {
1922 log.Fatalf("found object file %s in old format", f.File().Name())
1924 panic("cannot read object file")
1926 pkgprefix := objabi.PathToPrefix(lib.Pkg) + "."
1928 nnonpkgdef := r.NNonpkgdef()
1929 or := &oReader{r, unit, localSymVersion, r.Flags(), pkgprefix, make([]Sym, ndef+nnonpkgdef+r.NNonpkgref()), ndef, uint32(len(l.objs))}
1932 lib.Autolib = append(lib.Autolib, r.Autolib()...)
1935 nfile := r.NDwarfFile()
1936 unit.DWARFFileTable = make([]string, nfile)
1937 for i := range unit.DWARFFileTable {
1938 unit.DWARFFileTable[i] = r.DwarfFile(i)
1941 l.addObj(lib.Pkg, or)
1942 l.preloadSyms(or, pkgDef)
1944 // The caller expects us consuming all the data
1945 f.MustSeek(length, os.SEEK_CUR)
1947 return r.Fingerprint()
1950 // Preload symbols of given kind from an object.
1951 func (l *Loader) preloadSyms(r *oReader, kind int) {
1952 ndef := uint32(r.NSym())
1953 nnonpkgdef := uint32(r.NNonpkgdef())
1954 var start, end uint32
1961 end = ndef + nnonpkgdef
1963 panic("preloadSyms: bad kind")
1965 l.growAttrBitmaps(len(l.objSyms) + int(end-start))
1966 needNameExpansion := r.NeedNameExpansion()
1967 for i := start; i < end; i++ {
1969 name := osym.Name(r.Reader)
1970 if needNameExpansion {
1971 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
1973 v := abiToVer(osym.ABI(), r.version)
1974 dupok := osym.Dupok()
1975 gi, added := l.AddSym(name, v, r, i, kind, dupok, sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())])
1980 if osym.TopFrame() {
1981 l.SetAttrTopFrame(gi, true)
1984 l.SetAttrLocal(gi, true)
1986 if strings.HasPrefix(name, "go.itablink.") {
1987 l.itablink[gi] = struct{}{}
1989 if strings.HasPrefix(name, "runtime.") {
1990 if bi := goobj2.BuiltinIdx(name, v); bi != -1 {
1991 // This is a definition of a builtin symbol. Record where it is.
1992 l.builtinSyms[bi] = gi
1995 if a := osym.Align(); a != 0 {
1996 l.SetSymAlign(gi, int32(a))
2001 // Add non-package symbols and references to external symbols (which are always
2003 func (l *Loader) LoadNonpkgSyms(arch *sys.Arch) {
2004 for _, o := range l.objs[goObjStart:] {
2005 l.preloadSyms(o.r, nonPkgDef)
2007 for _, o := range l.objs[goObjStart:] {
2008 loadObjRefs(l, o.r, arch)
2010 l.values = make([]int64, l.NSym(), l.NSym()+1000) // +1000 make some room for external symbols
2013 func loadObjRefs(l *Loader, r *oReader, arch *sys.Arch) {
2014 ndef := uint32(r.NSym() + r.NNonpkgdef())
2015 needNameExpansion := r.NeedNameExpansion()
2016 for i, n := uint32(0), uint32(r.NNonpkgref()); i < n; i++ {
2017 osym := r.Sym(ndef + i)
2018 name := osym.Name(r.Reader)
2019 if needNameExpansion {
2020 name = strings.Replace(name, "\"\".", r.pkgprefix, -1)
2022 v := abiToVer(osym.ABI(), r.version)
2023 r.syms[ndef+i] = l.LookupOrCreateSym(name, v)
2024 gi := r.syms[ndef+i]
2026 l.SetAttrLocal(gi, true)
2028 l.preprocess(arch, gi, name)
2032 func abiToVer(abi uint16, localSymVersion int) int {
2034 if abi == goobj2.SymABIstatic {
2037 } else if abiver := sym.ABIToVersion(obj.ABI(abi)); abiver != -1 {
2038 // Note that data symbols are "ABI0", which maps to version 0.
2041 log.Fatalf("invalid symbol ABI: %d", abi)
2046 // preprocess looks for integer/floating point constant symbols whose
2047 // content is encoded into the symbol name, and promotes them into
2048 // real symbols with RODATA type and a payload that matches the
2050 func (l *Loader) preprocess(arch *sys.Arch, s Sym, name string) {
2051 if name != "" && name[0] == '$' && len(name) > 5 && l.SymType(s) == 0 && len(l.Data(s)) == 0 {
2052 x, err := strconv.ParseUint(name[5:], 16, 64)
2054 log.Panicf("failed to parse $-symbol %s: %v", name, err)
2056 su := l.MakeSymbolUpdater(s)
2057 su.SetType(sym.SRODATA)
2061 if uint64(uint32(x)) != x {
2062 log.Panicf("$-symbol %s too large: %d", name, x)
2064 su.AddUint32(arch, uint32(x))
2065 case "$f64.", "$i64.":
2066 su.AddUint64(arch, x)
2068 log.Panicf("unrecognized $-symbol: %s", name)
2073 // ResolveABIAlias given a symbol returns the ABI alias target of that
2074 // symbol. If the sym in question is not an alias, the sym itself is
2076 func (l *Loader) ResolveABIAlias(s Sym) Sym {
2080 if l.SymType(s) != sym.SABIALIAS {
2083 relocs := l.Relocs(s)
2084 target := relocs.At2(0).Sym()
2085 if l.SymType(target) == sym.SABIALIAS {
2086 panic(fmt.Sprintf("ABI alias %s references another ABI alias %s", l.SymName(s), l.SymName(target)))
2091 // TopLevelSym tests a symbol (by name and kind) to determine whether
2092 // the symbol first class sym (participating in the link) or is an
2093 // anonymous aux or sub-symbol containing some sub-part or payload of
2095 func (l *Loader) TopLevelSym(s Sym) bool {
2096 return topLevelSym(l.RawSymName(s), l.SymType(s))
2099 // topLevelSym tests a symbol name and kind to determine whether
2100 // the symbol first class sym (participating in the link) or is an
2101 // anonymous aux or sub-symbol containing some sub-part or payload of
2103 func topLevelSym(sname string, skind sym.SymKind) bool {
2108 case sym.SDWARFFCN, sym.SDWARFABSFCN, sym.SDWARFTYPE, sym.SDWARFCONST, sym.SDWARFCUINFO, sym.SDWARFRANGE, sym.SDWARFLOC, sym.SDWARFLINES, sym.SGOFUNC:
2115 // cloneToExternal takes the existing object file symbol (symIdx)
2116 // and creates a new external symbol payload that is a clone with
2117 // respect to name, version, type, relocations, etc. The idea here
2118 // is that if the linker decides it wants to update the contents of
2119 // a symbol originally discovered as part of an object file, it's
2120 // easier to do this if we make the updates to an external symbol
2122 func (l *Loader) cloneToExternal(symIdx Sym) {
2123 if l.IsExternal(symIdx) {
2124 panic("sym is already external, no need for clone")
2127 // Read the particulars from object.
2128 r, li := l.toLocal(symIdx)
2130 sname := osym.Name(r.Reader)
2131 if r.NeedNameExpansion() {
2132 sname = strings.Replace(sname, "\"\".", r.pkgprefix, -1)
2134 sver := abiToVer(osym.ABI(), r.version)
2135 skind := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2137 // Create new symbol, update version and kind.
2138 pi := l.newPayload(sname, sver)
2139 pp := l.payloads[pi]
2142 pp.size = int64(osym.Siz())
2143 pp.objidx = r.objidx
2145 // If this is a def, then copy the guts. We expect this case
2146 // to be very rare (one case it may come up is with -X).
2147 if li < uint32(r.NSym()+r.NNonpkgdef()) {
2150 relocs := l.Relocs(symIdx)
2151 pp.relocs = make([]goobj2.Reloc, relocs.Count())
2152 pp.reltypes = make([]objabi.RelocType, relocs.Count())
2153 for i := range pp.relocs {
2154 // Copy the relocs slice.
2155 // Convert local reference to global reference.
2156 rel := relocs.At2(i)
2157 pp.relocs[i].Set(rel.Off(), rel.Siz(), 0, rel.Add(), goobj2.SymRef{PkgIdx: 0, SymIdx: uint32(rel.Sym())})
2158 pp.reltypes[i] = rel.Type()
2162 pp.data = r.Data(li)
2165 // If we're overriding a data symbol, collect the associated
2166 // Gotype, so as to propagate it to the new symbol.
2170 // Install new payload to global index space.
2171 // (This needs to happen at the end, as the accessors above
2172 // need to access the old symbol content.)
2173 l.objSyms[symIdx] = objSym{l.extReader.objidx, uint32(pi)}
2174 l.extReader.syms = append(l.extReader.syms, symIdx)
2177 // Copy the payload of symbol src to dst. Both src and dst must be external
2179 // The intended use case is that when building/linking against a shared library,
2180 // where we do symbol name mangling, the Go object file may have reference to
2181 // the original symbol name whereas the shared library provides a symbol with
2182 // the mangled name. When we do mangling, we copy payload of mangled to original.
2183 func (l *Loader) CopySym(src, dst Sym) {
2184 if !l.IsExternal(dst) {
2185 panic("dst is not external") //l.newExtSym(l.SymName(dst), l.SymVersion(dst))
2187 if !l.IsExternal(src) {
2188 panic("src is not external") //l.cloneToExternal(src)
2190 l.payloads[l.extIndex(dst)] = l.payloads[l.extIndex(src)]
2191 l.SetSymPkg(dst, l.SymPkg(src))
2192 // TODO: other attributes?
2195 // CopyAttributes copies over all of the attributes of symbol 'src' to
2197 func (l *Loader) CopyAttributes(src Sym, dst Sym) {
2198 l.SetAttrReachable(dst, l.AttrReachable(src))
2199 l.SetAttrOnList(dst, l.AttrOnList(src))
2200 l.SetAttrLocal(dst, l.AttrLocal(src))
2201 l.SetAttrNotInSymbolTable(dst, l.AttrNotInSymbolTable(src))
2202 if l.IsExternal(dst) {
2203 l.SetAttrVisibilityHidden(dst, l.AttrVisibilityHidden(src))
2204 l.SetAttrDuplicateOK(dst, l.AttrDuplicateOK(src))
2205 l.SetAttrShared(dst, l.AttrShared(src))
2206 l.SetAttrExternal(dst, l.AttrExternal(src))
2208 // Some attributes are modifiable only for external symbols.
2209 // In such cases, don't try to transfer over the attribute
2210 // from the source even if there is a clash. This comes up
2211 // when copying attributes from a dupOK ABI wrapper symbol to
2212 // the real target symbol (which may not be marked dupOK).
2214 l.SetAttrTopFrame(dst, l.AttrTopFrame(src))
2215 l.SetAttrSpecial(dst, l.AttrSpecial(src))
2216 l.SetAttrCgoExportDynamic(dst, l.AttrCgoExportDynamic(src))
2217 l.SetAttrCgoExportStatic(dst, l.AttrCgoExportStatic(src))
2218 l.SetAttrReadOnly(dst, l.AttrReadOnly(src))
2221 // CreateExtSym creates a new external symbol with the specified name
2222 // without adding it to any lookup tables, returning a Sym index for it.
2223 func (l *Loader) CreateExtSym(name string, ver int) Sym {
2224 return l.newExtSym(name, ver)
2227 // CreateStaticSym creates a new static symbol with the specified name
2228 // without adding it to any lookup tables, returning a Sym index for it.
2229 func (l *Loader) CreateStaticSym(name string) Sym {
2230 // Assign a new unique negative version -- this is to mark the
2231 // symbol so that it is not included in the name lookup table.
2233 return l.newExtSym(name, l.anonVersion)
2236 func (l *Loader) FreeSym(i Sym) {
2237 if l.IsExternal(i) {
2238 pp := l.getPayload(i)
2239 *pp = extSymPayload{}
2243 // relocId is essentially a <S,R> tuple identifying the Rth
2244 // relocation of symbol S.
2245 type relocId struct {
2250 // SetRelocVariant sets the 'variant' property of a relocation on
2251 // some specific symbol.
2252 func (l *Loader) SetRelocVariant(s Sym, ri int, v sym.RelocVariant) {
2254 if relocs := l.Relocs(s); ri >= relocs.Count() {
2255 panic("invalid relocation ID")
2257 if l.relocVariant == nil {
2258 l.relocVariant = make(map[relocId]sym.RelocVariant)
2261 l.relocVariant[relocId{s, ri}] = v
2263 delete(l.relocVariant, relocId{s, ri})
2267 // RelocVariant returns the 'variant' property of a relocation on
2268 // some specific symbol.
2269 func (l *Loader) RelocVariant(s Sym, ri int) sym.RelocVariant {
2270 return l.relocVariant[relocId{s, ri}]
2273 // UndefinedRelocTargets iterates through the global symbol index
2274 // space, looking for symbols with relocations targeting undefined
2275 // references. The linker's loadlib method uses this to determine if
2276 // there are unresolved references to functions in system libraries
2277 // (for example, libgcc.a), presumably due to CGO code. Return
2278 // value is a list of loader.Sym's corresponding to the undefined
2279 // cross-refs. The "limit" param controls the maximum number of
2280 // results returned; if "limit" is -1, then all undefs are returned.
2281 func (l *Loader) UndefinedRelocTargets(limit int) []Sym {
2283 for si := Sym(1); si < Sym(len(l.objSyms)); si++ {
2284 relocs := l.Relocs(si)
2285 for ri := 0; ri < relocs.Count(); ri++ {
2288 if rs != 0 && l.SymType(rs) == sym.SXREF && l.RawSymName(rs) != ".got" {
2289 result = append(result, rs)
2290 if limit != -1 && len(result) >= limit {
2299 // AssignTextSymbolOrder populates the Textp slices within each
2300 // library and compilation unit, insuring that packages are laid down
2301 // in dependency order (internal first, then everything else). Return value
2302 // is a slice of all text syms.
2303 func (l *Loader) AssignTextSymbolOrder(libs []*sym.Library, intlibs []bool, extsyms []Sym) []Sym {
2305 // Library Textp lists should be empty at this point.
2306 for _, lib := range libs {
2307 if len(lib.Textp) != 0 {
2308 panic("expected empty Textp slice for library")
2310 if len(lib.DupTextSyms) != 0 {
2311 panic("expected empty DupTextSyms slice for library")
2315 // Used to record which dupok symbol we've assigned to a unit.
2316 // Can't use the onlist attribute here because it will need to
2317 // clear for the later assignment of the sym.Symbol to a unit.
2318 // NB: we can convert to using onList once we no longer have to
2319 // call the regular addToTextp.
2320 assignedToUnit := MakeBitmap(l.NSym() + 1)
2322 // Start off textp with reachable external syms.
2324 for _, sym := range extsyms {
2325 if !l.attrReachable.Has(sym) {
2328 textp = append(textp, sym)
2331 // Walk through all text symbols from Go object files and append
2332 // them to their corresponding library's textp list.
2333 for _, o := range l.objs[goObjStart:] {
2336 for i, n := uint32(0), uint32(r.NSym()+r.NNonpkgdef()); i < n; i++ {
2337 gi := l.toGlobal(r, i)
2338 if !l.attrReachable.Has(gi) {
2342 st := sym.AbiSymKindToSymKind[objabi.SymKind(osym.Type())]
2343 if st != sym.STEXT {
2346 dupok := osym.Dupok()
2347 if r2, i2 := l.toLocal(gi); r2 != r || i2 != i {
2348 // A dupok text symbol is resolved to another package.
2349 // We still need to record its presence in the current
2350 // package, as the trampoline pass expects packages
2351 // are laid out in dependency order.
2352 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2353 continue // symbol in different object
2356 lib.DupTextSyms = append(lib.DupTextSyms, sym.LoaderSym(gi))
2360 lib.Textp = append(lib.Textp, sym.LoaderSym(gi))
2364 // Now assemble global textp, and assign text symbols to units.
2365 for _, doInternal := range [2]bool{true, false} {
2366 for idx, lib := range libs {
2367 if intlibs[idx] != doInternal {
2370 lists := [2][]sym.LoaderSym{lib.Textp, lib.DupTextSyms}
2371 for i, list := range lists {
2372 for _, s := range list {
2374 if l.attrReachable.Has(sym) && !assignedToUnit.Has(sym) {
2375 textp = append(textp, sym)
2376 unit := l.SymUnit(sym)
2378 unit.Textp = append(unit.Textp, s)
2379 assignedToUnit.Set(sym)
2381 // Dupok symbols may be defined in multiple packages; the
2382 // associated package for a dupok sym is chosen sort of
2383 // arbitrarily (the first containing package that the linker
2384 // loads). Canonicalizes its Pkg to the package with which
2385 // it will be laid down in text.
2386 if i == 1 /* DupTextSyms2 */ && l.SymPkg(sym) != lib.Pkg {
2387 l.SetSymPkg(sym, lib.Pkg)
2393 lib.DupTextSyms = nil
2400 // ErrorReporter is a helper class for reporting errors.
2401 type ErrorReporter struct {
2403 AfterErrorAction func()
2406 // Errorf method logs an error message.
2408 // After each error, the error actions function will be invoked; this
2409 // will either terminate the link immediately (if -h option given)
2410 // or it will keep a count and exit if more than 20 errors have been printed.
2412 // Logging an error means that on exit cmd/link will delete any
2413 // output file and return a non-zero error code.
2415 func (reporter *ErrorReporter) Errorf(s Sym, format string, args ...interface{}) {
2416 if s != 0 && reporter.ldr.SymName(s) != "" {
2417 format = reporter.ldr.SymName(s) + ": " + format
2419 format = fmt.Sprintf("sym %d: %s", s, format)
2422 fmt.Fprintf(os.Stderr, format, args...)
2423 reporter.AfterErrorAction()
2426 // GetErrorReporter returns the loader's associated error reporter.
2427 func (l *Loader) GetErrorReporter() *ErrorReporter {
2428 return l.errorReporter
2431 // Errorf method logs an error message. See ErrorReporter.Errorf for details.
2432 func (l *Loader) Errorf(s Sym, format string, args ...interface{}) {
2433 l.errorReporter.Errorf(s, format, args...)
2437 func (l *Loader) Dump() {
2439 for _, obj := range l.objs[goObjStart:] {
2441 fmt.Println(obj.i, obj.r.unit.Lib)
2444 fmt.Println("extStart:", l.extStart)
2445 fmt.Println("Nsyms:", len(l.objSyms))
2447 for i := Sym(1); i < Sym(len(l.objSyms)); i++ {
2448 pi := interface{}("")
2449 if l.IsExternal(i) {
2450 pi = fmt.Sprintf("<ext %d>", l.extIndex(i))
2452 fmt.Println(i, l.SymName(i), l.SymType(i), pi)
2454 fmt.Println("symsByName")
2455 for name, i := range l.symsByName[0] {
2456 fmt.Println(i, name, 0)
2458 for name, i := range l.symsByName[1] {
2459 fmt.Println(i, name, 1)
2461 fmt.Println("payloads:")
2462 for i := range l.payloads {
2464 fmt.Println(i, pp.name, pp.ver, pp.kind)