1 // Derived from Inferno utils/6l/obj.c and utils/6l/span.c
2 // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/obj.c
3 // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/span.c
5 // Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
6 // Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
7 // Portions Copyright © 1997-1999 Vita Nuova Limited
8 // Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
9 // Portions Copyright © 2004,2006 Bruce Ellis
10 // Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
11 // Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
12 // Portions Copyright © 2009 The Go Authors. All rights reserved.
14 // Permission is hereby granted, free of charge, to any person obtaining a copy
15 // of this software and associated documentation files (the "Software"), to deal
16 // in the Software without restriction, including without limitation the rights
17 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 // copies of the Software, and to permit persons to whom the Software is
19 // furnished to do so, subject to the following conditions:
21 // The above copyright notice and this permission notice shall be included in
22 // all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 "cmd/link/internal/loader"
40 "cmd/link/internal/sym"
53 // isRuntimeDepPkg reports whether pkg is the runtime package or its dependency
54 func isRuntimeDepPkg(pkg string) bool {
57 "sync/atomic", // runtime may call to sync/atomic, due to go:linkname
58 "internal/abi", // used by reflectcall (and maybe more)
59 "internal/bytealg", // for IndexByte
60 "internal/cpu": // for cpu features
63 return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test")
66 // Estimate the max size needed to hold any new trampolines created for this function. This
67 // is used to determine when the section can be split if it becomes too large, to ensure that
68 // the trampolines are in the same section as the function that uses them.
69 func maxSizeTrampolinesPPC64(ldr *loader.Loader, s loader.Sym, isTramp bool) uint64 {
70 // If thearch.Trampoline is nil, then trampoline support is not available on this arch.
71 // A trampoline does not need any dependent trampolines.
72 if thearch.Trampoline == nil || isTramp {
77 relocs := ldr.Relocs(s)
78 for ri := 0; ri < relocs.Count(); ri++ {
80 if r.Type().IsDirectCallOrJump() {
84 // Trampolines in ppc64 are 4 instructions.
88 // detect too-far jumps in function s, and add trampolines if necessary
89 // ARM, PPC64 & PPC64LE support trampoline insertion for internal and external linking
90 // On PPC64 & PPC64LE the text sections might be split but will still insert trampolines
92 func trampoline(ctxt *Link, s loader.Sym) {
93 if thearch.Trampoline == nil {
94 return // no need or no support of trampolines on this arch
98 relocs := ldr.Relocs(s)
99 for ri := 0; ri < relocs.Count(); ri++ {
101 if !r.Type().IsDirectCallOrJump() {
105 if !ldr.AttrReachable(rs) || ldr.SymType(rs) == sym.Sxxx {
106 continue // something is wrong. skip it here and we'll emit a better error later
108 rs = ldr.ResolveABIAlias(rs)
109 if ldr.SymValue(rs) == 0 && (ldr.SymType(rs) != sym.SDYNIMPORT && ldr.SymType(rs) != sym.SUNDEFEXT) {
110 if ldr.SymPkg(rs) == ldr.SymPkg(s) {
111 continue // symbols in the same package are laid out together
113 if isRuntimeDepPkg(ldr.SymPkg(s)) && isRuntimeDepPkg(ldr.SymPkg(rs)) {
114 continue // runtime packages are laid out together
118 thearch.Trampoline(ctxt, ldr, ri, rs, s)
123 // FoldSubSymbolOffset computes the offset of symbol s to its top-level outer
124 // symbol. Returns the top-level symbol and the offset.
125 // This is used in generating external relocations.
126 func FoldSubSymbolOffset(ldr *loader.Loader, s loader.Sym) (loader.Sym, int64) {
127 outer := ldr.OuterSym(s)
130 off += ldr.SymValue(s) - ldr.SymValue(outer)
136 // relocsym resolve relocations in "s", updating the symbol's content
138 // The main loop walks through the list of relocations attached to "s"
139 // and resolves them where applicable. Relocations are often
140 // architecture-specific, requiring calls into the 'archreloc' and/or
141 // 'archrelocvariant' functions for the architecture. When external
142 // linking is in effect, it may not be possible to completely resolve
143 // the address/offset for a symbol, in which case the goal is to lay
144 // the groundwork for turning a given relocation into an external reloc
145 // (to be applied by the external linker). For more on how relocations
146 // work in general, see
148 // "Linkers and Loaders", by John R. Levine (Morgan Kaufmann, 1999), ch. 7
150 // This is a performance-critical function for the linker; be careful
151 // to avoid introducing unnecessary allocations in the main loop.
152 func (st *relocSymState) relocsym(s loader.Sym, P []byte) {
154 relocs := ldr.Relocs(s)
155 if relocs.Count() == 0 {
160 nExtReloc := 0 // number of external relocations
161 for ri := 0; ri < relocs.Count(); ri++ {
164 siz := int32(r.Siz())
166 rs = ldr.ResolveABIAlias(rs)
168 if off < 0 || off+siz > int32(len(P)) {
171 rname = ldr.SymName(rs)
173 st.err.Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(P))
176 if siz == 0 { // informational relocation - no work to do
182 rst = ldr.SymType(rs)
185 if rs != 0 && ((rst == sym.Sxxx && !ldr.AttrVisibilityHidden(rs)) || rst == sym.SXREF) {
186 // When putting the runtime but not main into a shared library
187 // these symbols are undefined and that's OK.
188 if target.IsShared() || target.IsPlugin() {
189 if ldr.SymName(rs) == "main.main" || (!target.IsPlugin() && ldr.SymName(rs) == "main..inittask") {
190 sb := ldr.MakeSymbolUpdater(rs)
191 sb.SetType(sym.SDYNIMPORT)
192 } else if strings.HasPrefix(ldr.SymName(rs), "go.info.") {
193 // Skip go.info symbols. They are only needed to communicate
194 // DWARF info between the compiler and linker.
198 st.err.errorUnresolved(ldr, s, rs)
203 if rt >= objabi.ElfRelocOffset {
207 // We need to be able to reference dynimport symbols when linking against
208 // shared libraries, and AIX, Darwin, OpenBSD and Solaris always need it.
209 if !target.IsAIX() && !target.IsDarwin() && !target.IsSolaris() && !target.IsOpenbsd() && rs != 0 && rst == sym.SDYNIMPORT && !target.IsDynlinkingGo() && !ldr.AttrSubSymbol(rs) {
210 if !(target.IsPPC64() && target.IsExternal() && ldr.SymName(rs) == ".TOC.") {
211 st.err.Errorf(s, "unhandled relocation for %s (type %d (%s) rtype %d (%s))", ldr.SymName(rs), rst, rst, rt, sym.RelocName(target.Arch, rt))
214 if rs != 0 && rst != sym.STLSBSS && rt != objabi.R_WEAKADDROFF && rt != objabi.R_METHODOFF && !ldr.AttrReachable(rs) {
215 st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
218 var rv sym.RelocVariant
219 if target.IsPPC64() || target.IsS390X() {
220 rv = ldr.RelocVariant(s, ri)
223 // TODO(mundaym): remove this special case - see issue 14218.
224 if target.IsS390X() {
226 case objabi.R_PCRELDBL:
239 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
243 o = int64(target.Arch.ByteOrder.Uint16(P[off:]))
245 o = int64(target.Arch.ByteOrder.Uint32(P[off:]))
247 o = int64(target.Arch.ByteOrder.Uint64(P[off:]))
249 out, n, ok := thearch.Archreloc(target, ldr, syms, r, s, o)
250 if target.IsExternal() {
256 st.err.Errorf(s, "unknown reloc to %v: %d (%s)", ldr.SymName(rs), rt, sym.RelocName(target.Arch, rt))
258 case objabi.R_TLS_LE:
259 if target.IsExternal() && target.IsElf() {
262 if !target.IsAMD64() {
268 if target.IsElf() && target.IsARM() {
269 // On ELF ARM, the thread pointer is 8 bytes before
270 // the start of the thread-local data block, so add 8
271 // to the actual TLS offset (r->sym->value).
272 // This 8 seems to be a fundamental constant of
273 // ELF on ARM (or maybe Glibc on ARM); it is not
274 // related to the fact that our own TLS storage happens
275 // to take up 8 bytes.
276 o = 8 + ldr.SymValue(rs)
277 } else if target.IsElf() || target.IsPlan9() || target.IsDarwin() {
278 o = int64(syms.Tlsoffset) + r.Add()
279 } else if target.IsWindows() {
282 log.Fatalf("unexpected R_TLS_LE relocation for %v", target.HeadType)
284 case objabi.R_TLS_IE:
285 if target.IsExternal() && target.IsElf() {
288 if !target.IsAMD64() {
292 nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
296 if target.IsPIE() && target.IsElf() {
297 // We are linking the final executable, so we
298 // can optimize any TLS IE relocation to LE.
299 if thearch.TLSIEtoLE == nil {
300 log.Fatalf("internal linking of TLS IE not supported on %v", target.Arch.Family)
302 thearch.TLSIEtoLE(P, int(off), int(siz))
303 o = int64(syms.Tlsoffset)
305 log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", ldr.SymName(s))
308 if target.IsExternal() {
311 // set up addend for eventual relocation via outer symbol.
313 rs, off := FoldSubSymbolOffset(ldr, rs)
314 xadd := r.Add() + off
315 rst := ldr.SymType(rs)
316 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
317 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
322 if target.IsAMD64() {
325 } else if target.IsDarwin() {
326 if ldr.SymType(rs) != sym.SHOSTOBJ {
327 o += ldr.SymValue(rs)
329 } else if target.IsWindows() {
331 } else if target.IsAIX() {
332 o = ldr.SymValue(rs) + xadd
334 st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
340 // On AIX, a second relocation must be done by the loader,
341 // as section addresses can change once loaded.
342 // The "default" symbol address is still needed by the loader so
343 // the current relocation can't be skipped.
344 if target.IsAIX() && rst != sym.SDYNIMPORT {
345 // It's not possible to make a loader relocation in a
346 // symbol which is not inside .data section.
347 // FIXME: It should be forbidden to have R_ADDR from a
348 // symbol which isn't in .data. However, as .text has the
349 // same address once loaded, this is possible.
350 if ldr.SymSect(s).Seg == &Segdata {
351 Xcoffadddynrel(target, ldr, syms, s, r, ri)
355 o = ldr.SymValue(rs) + r.Add()
357 // On amd64, 4-byte offsets will be sign-extended, so it is impossible to
358 // access more than 2GB of static data; fail at link time is better than
359 // fail at runtime. See https://golang.org/issue/7980.
360 // Instead of special casing only amd64, we treat this as an error on all
361 // 64-bit architectures so as to be future-proof.
362 if int32(o) < 0 && target.Arch.PtrSize > 4 && siz == 4 {
363 st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x (%#x + %#x)", ldr.SymName(rs), uint64(o), ldr.SymValue(rs), r.Add())
366 case objabi.R_DWARFSECREF:
367 if ldr.SymSect(rs) == nil {
368 st.err.Errorf(s, "missing DWARF section for relocation target %s", ldr.SymName(rs))
371 if target.IsExternal() {
372 // On most platforms, the external linker needs to adjust DWARF references
373 // as it combines DWARF sections. However, on Darwin, dsymutil does the
374 // DWARF linking, and it understands how to follow section offsets.
375 // Leaving in the relocation records confuses it (see
376 // https://golang.org/issue/22068) so drop them for Darwin.
377 if !target.IsDarwin() {
381 xadd := r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
384 if target.IsElf() && target.IsAMD64() {
389 o = ldr.SymValue(rs) + r.Add() - int64(ldr.SymSect(rs).Vaddr)
390 case objabi.R_WEAKADDROFF, objabi.R_METHODOFF:
391 if !ldr.AttrReachable(rs) {
392 if rt == objabi.R_METHODOFF {
393 // Set it to a sentinel value. The runtime knows this is not pointing to
401 case objabi.R_ADDROFF:
402 // The method offset tables using this relocation expect the offset to be relative
403 // to the start of the first text section, even if there are multiple.
404 if ldr.SymSect(rs).Name == ".text" {
405 o = ldr.SymValue(rs) - int64(Segtext.Sections[0].Vaddr) + r.Add()
407 o = ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr) + r.Add()
410 case objabi.R_ADDRCUOFF:
411 // debug_range and debug_loc elements use this relocation type to get an
412 // offset from the start of the compile unit.
413 o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(loader.Sym(ldr.SymUnit(rs).Textp[0]))
415 // r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
416 case objabi.R_GOTPCREL:
417 if target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
422 if target.Is386() && target.IsExternal() && target.IsELF {
423 nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
426 case objabi.R_CALL, objabi.R_PCREL:
427 if target.IsExternal() && rs != 0 && rst == sym.SUNDEFEXT {
428 // pass through to the external linker.
433 if target.IsExternal() && rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
436 // set up addend for eventual relocation via outer symbol.
438 rs, off := FoldSubSymbolOffset(ldr, rs)
439 xadd := r.Add() + off - int64(siz) // relative to address after the relocated chunk
440 rst := ldr.SymType(rs)
441 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && ldr.SymSect(rs) == nil {
442 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
447 if target.IsAMD64() {
450 } else if target.IsDarwin() {
451 if rt == objabi.R_CALL {
452 if target.IsExternal() && rst == sym.SDYNIMPORT {
453 if target.IsAMD64() {
454 // AMD64 dynamic relocations are relative to the end of the relocation.
458 if rst != sym.SHOSTOBJ {
459 o += int64(uint64(ldr.SymValue(rs)) - ldr.SymSect(rs).Vaddr)
461 o -= int64(off) // relative to section offset, not symbol
466 } else if target.IsWindows() && target.IsAMD64() { // only amd64 needs PCREL
467 // PE/COFF's PC32 relocation uses the address after the relocated
468 // bytes as the base. Compensate by skewing the addend.
471 st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
482 o += r.Add() - (ldr.SymValue(s) + int64(off) + int64(siz))
484 o = ldr.SymSize(rs) + r.Add()
486 case objabi.R_XCOFFREF:
488 st.err.Errorf(s, "find XCOFF R_REF on non-XCOFF files")
490 if !target.IsExternal() {
491 st.err.Errorf(s, "find XCOFF R_REF with internal linking")
496 case objabi.R_DWARFFILEREF:
497 // We don't renumber files in dwarf.go:writelines anymore.
503 case objabi.R_GOTOFF:
504 o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(syms.GOT)
507 if target.IsPPC64() || target.IsS390X() {
508 if rv != sym.RV_NONE {
509 o = thearch.Archrelocvariant(target, ldr, r, rv, s, o)
515 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
517 P[off] = byte(int8(o))
519 if o != int64(int16(o)) {
520 st.err.Errorf(s, "relocation address for %s is too big: %#x", ldr.SymName(rs), o)
522 target.Arch.ByteOrder.PutUint16(P[off:], uint16(o))
524 if rt == objabi.R_PCREL || rt == objabi.R_CALL {
525 if o != int64(int32(o)) {
526 st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
529 if o != int64(int32(o)) && o != int64(uint32(o)) {
530 st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
533 target.Arch.ByteOrder.PutUint32(P[off:], uint32(o))
535 target.Arch.ByteOrder.PutUint64(P[off:], uint64(o))
538 if target.IsExternal() {
539 // We'll stream out the external relocations in asmb2 (e.g. elfrelocsect)
540 // and we only need the count here.
541 atomic.AddUint32(&ldr.SymSect(s).Relcount, uint32(nExtReloc))
545 // Convert a Go relocation to an external relocation.
546 func extreloc(ctxt *Link, ldr *loader.Loader, s loader.Sym, r loader.Reloc) (loader.ExtReloc, bool) {
547 var rr loader.ExtReloc
548 target := &ctxt.Target
549 siz := int32(r.Siz())
550 if siz == 0 { // informational relocation - no work to do
555 if rt >= objabi.ElfRelocOffset {
561 // TODO(mundaym): remove this special case - see issue 14218.
562 if target.IsS390X() {
564 case objabi.R_PCRELDBL:
571 return thearch.Extreloc(target, ldr, r, s)
573 case objabi.R_TLS_LE, objabi.R_TLS_IE:
575 rs := ldr.ResolveABIAlias(r.Sym())
586 // set up addend for eventual relocation via outer symbol.
587 rs := ldr.ResolveABIAlias(r.Sym())
588 rs, off := FoldSubSymbolOffset(ldr, rs)
589 rr.Xadd = r.Add() + off
592 case objabi.R_DWARFSECREF:
593 // On most platforms, the external linker needs to adjust DWARF references
594 // as it combines DWARF sections. However, on Darwin, dsymutil does the
595 // DWARF linking, and it understands how to follow section offsets.
596 // Leaving in the relocation records confuses it (see
597 // https://golang.org/issue/22068) so drop them for Darwin.
598 if target.IsDarwin() {
601 rs := ldr.ResolveABIAlias(r.Sym())
602 rr.Xsym = loader.Sym(ldr.SymSect(rs).Sym)
603 rr.Xadd = r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
605 // r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
606 case objabi.R_GOTPCREL, objabi.R_CALL, objabi.R_PCREL:
607 rs := ldr.ResolveABIAlias(r.Sym())
608 if rt == objabi.R_GOTPCREL && target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
610 rr.Xadd -= int64(siz) // relative to address after the relocated chunk
614 if rs != 0 && ldr.SymType(rs) == sym.SUNDEFEXT {
615 // pass through to the external linker.
618 rr.Xadd -= int64(siz)
623 if rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
624 // set up addend for eventual relocation via outer symbol.
626 rs, off := FoldSubSymbolOffset(ldr, rs)
627 rr.Xadd = r.Add() + off
628 rr.Xadd -= int64(siz) // relative to address after the relocated chunk
634 case objabi.R_XCOFFREF:
635 return ExtrelocSimple(ldr, r), true
637 // These reloc types don't need external relocations.
638 case objabi.R_ADDROFF, objabi.R_WEAKADDROFF, objabi.R_METHODOFF, objabi.R_ADDRCUOFF,
639 objabi.R_SIZE, objabi.R_CONST, objabi.R_GOTOFF:
645 // ExtrelocSimple creates a simple external relocation from r, with the same
646 // symbol and addend.
647 func ExtrelocSimple(ldr *loader.Loader, r loader.Reloc) loader.ExtReloc {
648 var rr loader.ExtReloc
649 rs := ldr.ResolveABIAlias(r.Sym())
657 // ExtrelocViaOuterSym creates an external relocation from r targeting the
658 // outer symbol and folding the subsymbol's offset into the addend.
659 func ExtrelocViaOuterSym(ldr *loader.Loader, r loader.Reloc, s loader.Sym) loader.ExtReloc {
660 // set up addend for eventual relocation via outer symbol.
661 var rr loader.ExtReloc
662 rs := ldr.ResolveABIAlias(r.Sym())
663 rs, off := FoldSubSymbolOffset(ldr, rs)
664 rr.Xadd = r.Add() + off
665 rst := ldr.SymType(rs)
666 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
667 ldr.Errorf(s, "missing section for %s", ldr.SymName(rs))
675 // relocSymState hold state information needed when making a series of
676 // successive calls to relocsym(). The items here are invariant
677 // (meaning that they are set up once initially and then don't change
678 // during the execution of relocsym), with the exception of a slice
679 // used to facilitate batch allocation of external relocations. Calls
680 // to relocsym happen in parallel; the assumption is that each
681 // parallel thread will have its own state object.
682 type relocSymState struct {
689 // makeRelocSymState creates a relocSymState container object to
690 // pass to relocsym(). If relocsym() calls happen in parallel,
691 // each parallel thread should have its own state object.
692 func (ctxt *Link) makeRelocSymState() *relocSymState {
693 return &relocSymState{
694 target: &ctxt.Target,
696 err: &ctxt.ErrorReporter,
697 syms: &ctxt.ArchSyms,
701 func windynrelocsym(ctxt *Link, rel *loader.SymbolBuilder, s loader.Sym) {
702 var su *loader.SymbolBuilder
703 relocs := ctxt.loader.Relocs(s)
704 for ri := 0; ri < relocs.Count(); ri++ {
707 continue // skip marker relocations
714 if !ctxt.loader.AttrReachable(targ) {
715 if rt == objabi.R_WEAKADDROFF {
718 ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s",
719 ctxt.loader.SymName(targ))
722 tplt := ctxt.loader.SymPlt(targ)
723 tgot := ctxt.loader.SymGot(targ)
724 if tplt == -2 && tgot != -2 { // make dynimport JMP table for PE object files.
725 tplt := int32(rel.Size())
726 ctxt.loader.SetPlt(targ, tplt)
729 su = ctxt.loader.MakeSymbolUpdater(s)
732 r.SetAdd(int64(tplt))
735 switch ctxt.Arch.Family {
737 ctxt.Errorf(s, "unsupported arch %v", ctxt.Arch.Family)
742 rel.AddAddrPlus(ctxt.Arch, targ, 0)
749 rel.AddAddrPlus4(ctxt.Arch, targ, 0)
752 } else if tplt >= 0 {
754 su = ctxt.loader.MakeSymbolUpdater(s)
757 r.SetAdd(int64(tplt))
762 // windynrelocsyms generates jump table to C library functions that will be
763 // added later. windynrelocsyms writes the table into .rel symbol.
764 func (ctxt *Link) windynrelocsyms() {
765 if !(ctxt.IsWindows() && iscgo && ctxt.IsInternal()) {
769 rel := ctxt.loader.CreateSymForUpdate(".rel", 0)
770 rel.SetType(sym.STEXT)
772 for _, s := range ctxt.Textp {
773 windynrelocsym(ctxt, rel, s)
776 ctxt.Textp = append(ctxt.Textp, rel.Sym())
779 func dynrelocsym(ctxt *Link, s loader.Sym) {
780 target := &ctxt.Target
782 syms := &ctxt.ArchSyms
783 relocs := ldr.Relocs(s)
784 for ri := 0; ri < relocs.Count(); ri++ {
787 continue // skip marker relocations
789 if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal {
790 // It's expected that some relocations will be done
791 // later by relocsym (R_TLS_LE, R_ADDROFF), so
792 // don't worry if Adddynrel returns false.
793 thearch.Adddynrel(target, ldr, syms, s, r, ri)
798 if rSym != 0 && ldr.SymType(rSym) == sym.SDYNIMPORT || r.Type() >= objabi.ElfRelocOffset {
799 if rSym != 0 && !ldr.AttrReachable(rSym) {
800 ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s", ldr.SymName(rSym))
802 if !thearch.Adddynrel(target, ldr, syms, s, r, ri) {
803 ctxt.Errorf(s, "unsupported dynamic relocation for symbol %s (type=%d (%s) stype=%d (%s))", ldr.SymName(rSym), r.Type(), sym.RelocName(ctxt.Arch, r.Type()), ldr.SymType(rSym), ldr.SymType(rSym))
809 func (state *dodataState) dynreloc(ctxt *Link) {
810 if ctxt.HeadType == objabi.Hwindows {
813 // -d suppresses dynamic loader format, so we may as well not
814 // compute these sections or mark their symbols as reachable.
819 for _, s := range ctxt.Textp {
822 for _, syms := range state.data {
823 for _, s := range syms {
832 func CodeblkPad(ctxt *Link, out *OutBuf, addr int64, size int64, pad []byte) {
833 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.Textp, addr, size, pad)
836 const blockSize = 1 << 20 // 1MB chunks written at a time.
838 // writeBlocks writes a specified chunk of symbols to the output buffer. It
839 // breaks the write up into ≥blockSize chunks to write them out, and schedules
840 // as many goroutines as necessary to accomplish this task. This call then
841 // blocks, waiting on the writes to complete. Note that we use the sem parameter
842 // to limit the number of concurrent writes taking place.
843 func writeBlocks(ctxt *Link, out *OutBuf, sem chan int, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
844 for i, s := range syms {
845 if ldr.SymValue(s) >= addr && !ldr.AttrSubSymbol(s) {
851 var wg sync.WaitGroup
852 max, lastAddr, written := int64(blockSize), addr+size, int64(0)
853 for addr < lastAddr {
854 // Find the last symbol we'd write.
856 for i, s := range syms {
857 if ldr.AttrSubSymbol(s) {
861 // If the next symbol's size would put us out of bounds on the total length,
863 end := ldr.SymValue(s) + ldr.SymSize(s)
868 // We're gonna write this symbol.
871 // If we cross over the max size, we've got enough symbols.
877 // If we didn't find any symbols to write, we're done here.
882 // Compute the length to write, including padding.
883 // We need to write to the end address (lastAddr), or the next symbol's
884 // start address, whichever comes first. If there is no more symbols,
885 // just write to lastAddr. This ensures we don't leave holes between the
886 // blocks or at the end.
888 if idx+1 < len(syms) {
889 // Find the next top-level symbol.
890 // Skip over sub symbols so we won't split a containter symbol
893 for ldr.AttrSubSymbol(next) {
897 length = ldr.SymValue(next) - addr
899 if length == 0 || length > lastAddr-addr {
900 length = lastAddr - addr
903 // Start the block output operator.
904 if o, err := out.View(uint64(out.Offset() + written)); err == nil {
907 go func(o *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
908 writeBlock(ctxt, o, ldr, syms, addr, size, pad)
911 }(o, ldr, syms, addr, length, pad)
912 } else { // output not mmaped, don't parallelize.
913 writeBlock(ctxt, out, ldr, syms, addr, length, pad)
916 // Prepare for the next loop.
926 func writeBlock(ctxt *Link, out *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
928 st := ctxt.makeRelocSymState()
930 // This doesn't distinguish the memory size from the file
931 // size, and it lays out the file based on Symbol.Value, which
932 // is the virtual address. DWARF compression changes file sizes,
933 // so dwarfcompress will fix this up later if necessary.
935 for _, s := range syms {
936 if ldr.AttrSubSymbol(s) {
939 val := ldr.SymValue(s)
944 ldr.Errorf(s, "phase error: addr=%#x but sym=%#x type=%v sect=%v", addr, val, ldr.SymType(s), ldr.SymSect(s).Name)
948 out.WriteStringPad("", int(val-addr), pad)
951 P := out.WriteSym(ldr, s)
953 if f, ok := ctxt.generatorSyms[s]; ok {
956 addr += int64(len(P))
957 siz := ldr.SymSize(s)
959 out.WriteStringPad("", int(val+siz-addr), pad)
963 ldr.Errorf(s, "phase error: addr=%#x value+size=%#x", addr, val+siz)
966 if val+siz >= eaddr {
972 out.WriteStringPad("", int(eaddr-addr), pad)
976 type writeFn func(*Link, *OutBuf, int64, int64)
978 // writeParallel handles scheduling parallel execution of data write functions.
979 func writeParallel(wg *sync.WaitGroup, fn writeFn, ctxt *Link, seek, vaddr, length uint64) {
980 if out, err := ctxt.Out.View(seek); err != nil {
981 ctxt.Out.SeekSet(int64(seek))
982 fn(ctxt, ctxt.Out, int64(vaddr), int64(length))
987 fn(ctxt, out, int64(vaddr), int64(length))
992 func datblk(ctxt *Link, out *OutBuf, addr, size int64) {
993 writeDatblkToOutBuf(ctxt, out, addr, size)
996 // Used only on Wasm for now.
997 func DatblkBytes(ctxt *Link, addr int64, size int64) []byte {
998 buf := make([]byte, size)
999 out := &OutBuf{heap: buf}
1000 writeDatblkToOutBuf(ctxt, out, addr, size)
1004 func writeDatblkToOutBuf(ctxt *Link, out *OutBuf, addr int64, size int64) {
1005 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.datap, addr, size, zeros[:])
1008 func dwarfblk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1009 // Concatenate the section symbol lists into a single list to pass
1012 // NB: ideally we would do a separate writeBlocks call for each
1013 // section, but this would run the risk of undoing any file offset
1014 // adjustments made during layout.
1016 for i := range dwarfp {
1017 n += len(dwarfp[i].syms)
1019 syms := make([]loader.Sym, 0, n)
1020 for i := range dwarfp {
1021 syms = append(syms, dwarfp[i].syms...)
1023 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, syms, addr, size, zeros[:])
1029 strdata = make(map[string]string)
1033 func addstrdata1(ctxt *Link, arg string) {
1034 eq := strings.Index(arg, "=")
1035 dot := strings.LastIndex(arg[:eq+1], ".")
1036 if eq < 0 || dot < 0 {
1037 Exitf("-X flag requires argument of the form importpath.name=value")
1040 if ctxt.BuildMode == BuildModePlugin && pkg == "main" {
1041 pkg = *flagPluginPath
1043 pkg = objabi.PathToPrefix(pkg)
1044 name := pkg + arg[dot:eq]
1046 if _, ok := strdata[name]; !ok {
1047 strnames = append(strnames, name)
1049 strdata[name] = value
1052 // addstrdata sets the initial value of the string variable name to value.
1053 func addstrdata(arch *sys.Arch, l *loader.Loader, name, value string) {
1054 s := l.Lookup(name, 0)
1058 if goType := l.SymGoType(s); goType == 0 {
1060 } else if typeName := l.SymName(goType); typeName != "type.string" {
1061 Errorf(nil, "%s: cannot set with -X: not a var of type string (%s)", name, typeName)
1064 if !l.AttrReachable(s) {
1065 return // don't bother setting unreachable variable
1067 bld := l.MakeSymbolUpdater(s)
1068 if bld.Type() == sym.SBSS {
1069 bld.SetType(sym.SDATA)
1072 p := fmt.Sprintf("%s.str", name)
1073 sbld := l.CreateSymForUpdate(p, 0)
1074 sbld.Addstring(value)
1075 sbld.SetType(sym.SRODATA)
1078 bld.SetData(make([]byte, 0, arch.PtrSize*2))
1079 bld.SetReadOnly(false)
1081 bld.AddAddrPlus(arch, sbld.Sym(), 0)
1082 bld.AddUint(arch, uint64(len(value)))
1085 func (ctxt *Link) dostrdata() {
1086 for _, name := range strnames {
1087 addstrdata(ctxt.Arch, ctxt.loader, name, strdata[name])
1091 // addgostring adds str, as a Go string value, to s. symname is the name of the
1092 // symbol used to define the string data and must be unique per linked object.
1093 func addgostring(ctxt *Link, ldr *loader.Loader, s *loader.SymbolBuilder, symname, str string) {
1094 sdata := ldr.CreateSymForUpdate(symname, 0)
1095 if sdata.Type() != sym.Sxxx {
1096 ctxt.Errorf(s.Sym(), "duplicate symname in addgostring: %s", symname)
1098 sdata.SetLocal(true)
1099 sdata.SetType(sym.SRODATA)
1100 sdata.SetSize(int64(len(str)))
1101 sdata.SetData([]byte(str))
1102 s.AddAddr(ctxt.Arch, sdata.Sym())
1103 s.AddUint(ctxt.Arch, uint64(len(str)))
1106 func addinitarrdata(ctxt *Link, ldr *loader.Loader, s loader.Sym) {
1107 p := ldr.SymName(s) + ".ptr"
1108 sp := ldr.CreateSymForUpdate(p, 0)
1109 sp.SetType(sym.SINITARR)
1111 sp.SetDuplicateOK(true)
1112 sp.AddAddr(ctxt.Arch, s)
1115 // symalign returns the required alignment for the given symbol s.
1116 func symalign(ldr *loader.Loader, s loader.Sym) int32 {
1117 min := int32(thearch.Minalign)
1118 align := ldr.SymAlign(s)
1121 } else if align != 0 {
1124 // FIXME: figure out a way to avoid checking by name here.
1125 sname := ldr.SymName(s)
1126 if strings.HasPrefix(sname, "go.string.") || strings.HasPrefix(sname, "type..namedata.") {
1127 // String data is just bytes.
1128 // If we align it, we waste a lot of space to padding.
1131 align = int32(thearch.Maxalign)
1132 ssz := ldr.SymSize(s)
1133 for int64(align) > ssz && align > min {
1136 ldr.SetSymAlign(s, align)
1140 func aligndatsize(state *dodataState, datsize int64, s loader.Sym) int64 {
1141 return Rnd(datsize, int64(symalign(state.ctxt.loader, s)))
1144 const debugGCProg = false
1146 type GCProg struct {
1148 sym *loader.SymbolBuilder
1152 func (p *GCProg) Init(ctxt *Link, name string) {
1154 p.sym = ctxt.loader.CreateSymForUpdate(name, 0)
1155 p.w.Init(p.writeByte())
1157 fmt.Fprintf(os.Stderr, "ld: start GCProg %s\n", name)
1158 p.w.Debug(os.Stderr)
1162 func (p *GCProg) writeByte() func(x byte) {
1163 return func(x byte) {
1168 func (p *GCProg) End(size int64) {
1169 p.w.ZeroUntil(size / int64(p.ctxt.Arch.PtrSize))
1172 fmt.Fprintf(os.Stderr, "ld: end GCProg\n")
1176 func (p *GCProg) AddSym(s loader.Sym) {
1177 ldr := p.ctxt.loader
1178 typ := ldr.SymGoType(s)
1180 // Things without pointers should be in sym.SNOPTRDATA or sym.SNOPTRBSS;
1181 // everything we see should have pointers and should therefore have a type.
1183 switch ldr.SymName(s) {
1184 case "runtime.data", "runtime.edata", "runtime.bss", "runtime.ebss":
1185 // Ignore special symbols that are sometimes laid out
1186 // as real symbols. See comment about dyld on darwin in
1187 // the address function.
1190 p.ctxt.Errorf(p.sym.Sym(), "missing Go type information for global symbol %s: size %d", ldr.SymName(s), ldr.SymSize(s))
1194 ptrsize := int64(p.ctxt.Arch.PtrSize)
1195 typData := ldr.Data(typ)
1196 nptr := decodetypePtrdata(p.ctxt.Arch, typData) / ptrsize
1199 fmt.Fprintf(os.Stderr, "gcprog sym: %s at %d (ptr=%d+%d)\n", ldr.SymName(s), ldr.SymValue(s), ldr.SymValue(s)/ptrsize, nptr)
1202 sval := ldr.SymValue(s)
1203 if decodetypeUsegcprog(p.ctxt.Arch, typData) == 0 {
1204 // Copy pointers from mask into program.
1205 mask := decodetypeGcmask(p.ctxt, typ)
1206 for i := int64(0); i < nptr; i++ {
1207 if (mask[i/8]>>uint(i%8))&1 != 0 {
1208 p.w.Ptr(sval/ptrsize + i)
1215 prog := decodetypeGcprog(p.ctxt, typ)
1216 p.w.ZeroUntil(sval / ptrsize)
1217 p.w.Append(prog[4:], nptr)
1220 // cutoff is the maximum data section size permitted by the linker
1221 // (see issue #9862).
1222 const cutoff = 2e9 // 2 GB (or so; looks better in errors than 2^31)
1224 func (state *dodataState) checkdatsize(symn sym.SymKind) {
1225 if state.datsize > cutoff {
1226 Errorf(nil, "too much data in section %v (over %v bytes)", symn, cutoff)
1230 // fixZeroSizedSymbols gives a few special symbols with zero size some space.
1231 func fixZeroSizedSymbols(ctxt *Link) {
1232 // The values in moduledata are filled out by relocations
1233 // pointing to the addresses of these special symbols.
1234 // Typically these symbols have no size and are not laid
1235 // out with their matching section.
1237 // However on darwin, dyld will find the special symbol
1238 // in the first loaded module, even though it is local.
1240 // (An hypothesis, formed without looking in the dyld sources:
1241 // these special symbols have no size, so their address
1242 // matches a real symbol. The dynamic linker assumes we
1243 // want the normal symbol with the same address and finds
1244 // it in the other module.)
1246 // To work around this we lay out the symbls whose
1247 // addresses are vital for multi-module programs to work
1248 // as normal symbols, and give them a little size.
1250 // On AIX, as all DATA sections are merged together, ld might not put
1251 // these symbols at the beginning of their respective section if there
1252 // aren't real symbols, their alignment might not match the
1253 // first symbol alignment. Therefore, there are explicitly put at the
1254 // beginning of their section with the same alignment.
1255 if !(ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) && !(ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
1260 bss := ldr.CreateSymForUpdate("runtime.bss", 0)
1262 ldr.SetAttrSpecial(bss.Sym(), false)
1264 ebss := ldr.CreateSymForUpdate("runtime.ebss", 0)
1265 ldr.SetAttrSpecial(ebss.Sym(), false)
1267 data := ldr.CreateSymForUpdate("runtime.data", 0)
1269 ldr.SetAttrSpecial(data.Sym(), false)
1271 edata := ldr.CreateSymForUpdate("runtime.edata", 0)
1272 ldr.SetAttrSpecial(edata.Sym(), false)
1274 if ctxt.HeadType == objabi.Haix {
1275 // XCOFFTOC symbols are part of .data section.
1276 edata.SetType(sym.SXCOFFTOC)
1279 types := ldr.CreateSymForUpdate("runtime.types", 0)
1280 types.SetType(sym.STYPE)
1282 ldr.SetAttrSpecial(types.Sym(), false)
1284 etypes := ldr.CreateSymForUpdate("runtime.etypes", 0)
1285 etypes.SetType(sym.SFUNCTAB)
1286 ldr.SetAttrSpecial(etypes.Sym(), false)
1288 if ctxt.HeadType == objabi.Haix {
1289 rodata := ldr.CreateSymForUpdate("runtime.rodata", 0)
1290 rodata.SetType(sym.SSTRING)
1292 ldr.SetAttrSpecial(rodata.Sym(), false)
1294 erodata := ldr.CreateSymForUpdate("runtime.erodata", 0)
1295 ldr.SetAttrSpecial(erodata.Sym(), false)
1299 // makeRelroForSharedLib creates a section of readonly data if necessary.
1300 func (state *dodataState) makeRelroForSharedLib(target *Link) {
1301 if !target.UseRelro() {
1305 // "read only" data with relocations needs to go in its own section
1306 // when building a shared library. We do this by boosting objects of
1307 // type SXXX with relocations to type SXXXRELRO.
1308 ldr := target.loader
1309 for _, symnro := range sym.ReadOnly {
1310 symnrelro := sym.RelROMap[symnro]
1312 ro := []loader.Sym{}
1313 relro := state.data[symnrelro]
1315 for _, s := range state.data[symnro] {
1316 relocs := ldr.Relocs(s)
1317 isRelro := relocs.Count() > 0
1318 switch state.symType(s) {
1319 case sym.STYPE, sym.STYPERELRO, sym.SGOFUNCRELRO:
1320 // Symbols are not sorted yet, so it is possible
1321 // that an Outer symbol has been changed to a
1322 // relro Type before it reaches here.
1325 if ldr.SymName(s) == "runtime.etypes" {
1326 // runtime.etypes must be at the end of
1332 state.setSymType(s, symnrelro)
1333 if outer := ldr.OuterSym(s); outer != 0 {
1334 state.setSymType(outer, symnrelro)
1336 relro = append(relro, s)
1342 // Check that we haven't made two symbols with the same .Outer into
1343 // different types (because references two symbols with non-nil Outer
1344 // become references to the outer symbol + offset it's vital that the
1345 // symbol and the outer end up in the same section).
1346 for _, s := range relro {
1347 if outer := ldr.OuterSym(s); outer != 0 {
1348 st := state.symType(s)
1349 ost := state.symType(outer)
1351 state.ctxt.Errorf(s, "inconsistent types for symbol and its Outer %s (%v != %v)",
1352 ldr.SymName(outer), st, ost)
1357 state.data[symnro] = ro
1358 state.data[symnrelro] = relro
1362 // dodataState holds bits of state information needed by dodata() and the
1363 // various helpers it calls. The lifetime of these items should not extend
1364 // past the end of dodata().
1365 type dodataState struct {
1368 // Data symbols bucketed by type.
1369 data [sym.SXREF][]loader.Sym
1370 // Max alignment for each flavor of data symbol.
1371 dataMaxAlign [sym.SXREF]int32
1372 // Overridden sym type
1373 symGroupType []sym.SymKind
1374 // Current data size so far.
1378 // A note on symType/setSymType below:
1380 // In the legacy linker, the types of symbols (notably data symbols) are
1381 // changed during the symtab() phase so as to insure that similar symbols
1382 // are bucketed together, then their types are changed back again during
1383 // dodata. Symbol to section assignment also plays tricks along these lines
1384 // in the case where a relro segment is needed.
1386 // The value returned from setType() below reflects the effects of
1387 // any overrides made by symtab and/or dodata.
1389 // symType returns the (possibly overridden) type of 's'.
1390 func (state *dodataState) symType(s loader.Sym) sym.SymKind {
1391 if int(s) < len(state.symGroupType) {
1392 if override := state.symGroupType[s]; override != 0 {
1396 return state.ctxt.loader.SymType(s)
1399 // setSymType sets a new override type for 's'.
1400 func (state *dodataState) setSymType(s loader.Sym, kind sym.SymKind) {
1404 if int(s) < len(state.symGroupType) {
1405 state.symGroupType[s] = kind
1407 su := state.ctxt.loader.MakeSymbolUpdater(s)
1412 func (ctxt *Link) dodata(symGroupType []sym.SymKind) {
1414 // Give zeros sized symbols space if necessary.
1415 fixZeroSizedSymbols(ctxt)
1417 // Collect data symbols by type into data.
1418 state := dodataState{ctxt: ctxt, symGroupType: symGroupType}
1420 for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
1421 if !ldr.AttrReachable(s) || ldr.AttrSpecial(s) || ldr.AttrSubSymbol(s) ||
1422 !ldr.TopLevelSym(s) {
1426 st := state.symType(s)
1428 if st <= sym.STEXT || st >= sym.SXREF {
1431 state.data[st] = append(state.data[st], s)
1433 // Similarly with checking the onlist attr.
1434 if ldr.AttrOnList(s) {
1435 log.Fatalf("symbol %s listed multiple times", ldr.SymName(s))
1437 ldr.SetAttrOnList(s, true)
1440 // Now that we have the data symbols, but before we start
1441 // to assign addresses, record all the necessary
1442 // dynamic relocations. These will grow the relocation
1443 // symbol, which is itself data.
1445 // On darwin, we need the symbol table numbers for dynreloc.
1446 if ctxt.HeadType == objabi.Hdarwin {
1449 state.dynreloc(ctxt)
1451 // Move any RO data with relocations to a separate section.
1452 state.makeRelroForSharedLib(ctxt)
1454 // Set alignment for the symbol with the largest known index,
1455 // so as to trigger allocation of the loader's internal
1456 // alignment array. This will avoid data races in the parallel
1458 lastSym := loader.Sym(ldr.NSym() - 1)
1459 ldr.SetSymAlign(lastSym, ldr.SymAlign(lastSym))
1462 var wg sync.WaitGroup
1463 for symn := range state.data {
1464 symn := sym.SymKind(symn)
1467 state.data[symn], state.dataMaxAlign[symn] = state.dodataSect(ctxt, symn, state.data[symn])
1474 // Make .rela and .rela.plt contiguous, the ELF ABI requires this
1475 // and Solaris actually cares.
1476 syms := state.data[sym.SELFROSECT]
1477 reli, plti := -1, -1
1478 for i, s := range syms {
1479 switch ldr.SymName(s) {
1480 case ".rel.plt", ".rela.plt":
1482 case ".rel", ".rela":
1486 if reli >= 0 && plti >= 0 && plti != reli+1 {
1487 var first, second int
1489 first, second = reli, plti
1491 first, second = plti, reli
1493 rel, plt := syms[reli], syms[plti]
1494 copy(syms[first+2:], syms[first+1:second])
1498 // Make sure alignment doesn't introduce a gap.
1499 // Setting the alignment explicitly prevents
1500 // symalign from basing it on the size and
1501 // getting it wrong.
1502 ldr.SetSymAlign(rel, int32(ctxt.Arch.RegSize))
1503 ldr.SetSymAlign(plt, int32(ctxt.Arch.RegSize))
1505 state.data[sym.SELFROSECT] = syms
1508 if ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal {
1509 // These symbols must have the same alignment as their section.
1510 // Otherwize, ld might change the layout of Go sections.
1511 ldr.SetSymAlign(ldr.Lookup("runtime.data", 0), state.dataMaxAlign[sym.SDATA])
1512 ldr.SetSymAlign(ldr.Lookup("runtime.bss", 0), state.dataMaxAlign[sym.SBSS])
1515 // Create *sym.Section objects and assign symbols to sections for
1516 // data/rodata (and related) symbols.
1517 state.allocateDataSections(ctxt)
1519 // Create *sym.Section objects and assign symbols to sections for
1521 state.allocateDwarfSections(ctxt)
1523 /* number the sections */
1526 for _, sect := range Segtext.Sections {
1530 for _, sect := range Segrodata.Sections {
1534 for _, sect := range Segrelrodata.Sections {
1538 for _, sect := range Segdata.Sections {
1542 for _, sect := range Segdwarf.Sections {
1548 // allocateDataSectionForSym creates a new sym.Section into which a a
1549 // single symbol will be placed. Here "seg" is the segment into which
1550 // the section will go, "s" is the symbol to be placed into the new
1551 // section, and "rwx" contains permissions for the section.
1552 func (state *dodataState) allocateDataSectionForSym(seg *sym.Segment, s loader.Sym, rwx int) *sym.Section {
1553 ldr := state.ctxt.loader
1554 sname := ldr.SymName(s)
1555 sect := addsection(ldr, state.ctxt.Arch, seg, sname, rwx)
1556 sect.Align = symalign(ldr, s)
1557 state.datsize = Rnd(state.datsize, int64(sect.Align))
1558 sect.Vaddr = uint64(state.datsize)
1562 // allocateNamedDataSection creates a new sym.Section for a category
1563 // of data symbols. Here "seg" is the segment into which the section
1564 // will go, "sName" is the name to give to the section, "types" is a
1565 // range of symbol types to be put into the section, and "rwx"
1566 // contains permissions for the section.
1567 func (state *dodataState) allocateNamedDataSection(seg *sym.Segment, sName string, types []sym.SymKind, rwx int) *sym.Section {
1568 sect := addsection(state.ctxt.loader, state.ctxt.Arch, seg, sName, rwx)
1569 if len(types) == 0 {
1571 } else if len(types) == 1 {
1572 sect.Align = state.dataMaxAlign[types[0]]
1574 for _, symn := range types {
1575 align := state.dataMaxAlign[symn]
1576 if sect.Align < align {
1581 state.datsize = Rnd(state.datsize, int64(sect.Align))
1582 sect.Vaddr = uint64(state.datsize)
1586 // assignDsymsToSection assigns a collection of data symbols to a
1587 // newly created section. "sect" is the section into which to place
1588 // the symbols, "syms" holds the list of symbols to assign,
1589 // "forceType" (if non-zero) contains a new sym type to apply to each
1590 // sym during the assignment, and "aligner" is a hook to call to
1591 // handle alignment during the assignment process.
1592 func (state *dodataState) assignDsymsToSection(sect *sym.Section, syms []loader.Sym, forceType sym.SymKind, aligner func(state *dodataState, datsize int64, s loader.Sym) int64) {
1593 ldr := state.ctxt.loader
1594 for _, s := range syms {
1595 state.datsize = aligner(state, state.datsize, s)
1596 ldr.SetSymSect(s, sect)
1597 if forceType != sym.Sxxx {
1598 state.setSymType(s, forceType)
1600 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1601 state.datsize += ldr.SymSize(s)
1603 sect.Length = uint64(state.datsize) - sect.Vaddr
1606 func (state *dodataState) assignToSection(sect *sym.Section, symn sym.SymKind, forceType sym.SymKind) {
1607 state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1608 state.checkdatsize(symn)
1611 // allocateSingleSymSections walks through the bucketed data symbols
1612 // with type 'symn', creates a new section for each sym, and assigns
1613 // the sym to a newly created section. Section name is set from the
1614 // symbol name. "Seg" is the segment into which to place the new
1615 // section, "forceType" is the new sym.SymKind to assign to the symbol
1616 // within the section, and "rwx" holds section permissions.
1617 func (state *dodataState) allocateSingleSymSections(seg *sym.Segment, symn sym.SymKind, forceType sym.SymKind, rwx int) {
1618 ldr := state.ctxt.loader
1619 for _, s := range state.data[symn] {
1620 sect := state.allocateDataSectionForSym(seg, s, rwx)
1621 ldr.SetSymSect(s, sect)
1622 state.setSymType(s, forceType)
1623 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1624 state.datsize += ldr.SymSize(s)
1625 sect.Length = uint64(state.datsize) - sect.Vaddr
1627 state.checkdatsize(symn)
1630 // allocateNamedSectionAndAssignSyms creates a new section with the
1631 // specified name, then walks through the bucketed data symbols with
1632 // type 'symn' and assigns each of them to this new section. "Seg" is
1633 // the segment into which to place the new section, "secName" is the
1634 // name to give to the new section, "forceType" (if non-zero) contains
1635 // a new sym type to apply to each sym during the assignment, and
1636 // "rwx" holds section permissions.
1637 func (state *dodataState) allocateNamedSectionAndAssignSyms(seg *sym.Segment, secName string, symn sym.SymKind, forceType sym.SymKind, rwx int) *sym.Section {
1639 sect := state.allocateNamedDataSection(seg, secName, []sym.SymKind{symn}, rwx)
1640 state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1644 // allocateDataSections allocates sym.Section objects for data/rodata
1645 // (and related) symbols, and then assigns symbols to those sections.
1646 func (state *dodataState) allocateDataSections(ctxt *Link) {
1647 // Allocate sections.
1648 // Data is processed before segtext, because we need
1649 // to see all symbols in the .data and .bss sections in order
1650 // to generate garbage collection information.
1652 // Writable data sections that do not need any specialized handling.
1653 writable := []sym.SymKind{
1660 for _, symn := range writable {
1661 state.allocateSingleSymSections(&Segdata, symn, sym.SDATA, 06)
1665 // .got (and .toc on ppc64)
1666 if len(state.data[sym.SELFGOT]) > 0 {
1667 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".got", sym.SELFGOT, sym.SDATA, 06)
1669 for _, s := range state.data[sym.SELFGOT] {
1670 // Resolve .TOC. symbol for this object file (ppc64)
1672 toc := ldr.Lookup(".TOC.", int(ldr.SymVersion(s)))
1674 ldr.SetSymSect(toc, sect)
1675 ldr.AddInteriorSym(s, toc)
1676 ldr.SetSymValue(toc, 0x8000)
1682 /* pointer-free data */
1683 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrdata", sym.SNOPTRDATA, sym.SDATA, 06)
1684 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrdata", 0), sect)
1685 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrdata", 0), sect)
1687 hasinitarr := ctxt.linkShared
1689 /* shared library initializer */
1690 switch ctxt.BuildMode {
1691 case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePlugin:
1695 if ctxt.HeadType == objabi.Haix {
1696 if len(state.data[sym.SINITARR]) > 0 {
1697 Errorf(nil, "XCOFF format doesn't allow .init_array section")
1701 if hasinitarr && len(state.data[sym.SINITARR]) > 0 {
1702 state.allocateNamedSectionAndAssignSyms(&Segdata, ".init_array", sym.SINITARR, sym.Sxxx, 06)
1706 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".data", sym.SDATA, sym.SDATA, 06)
1707 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.data", 0), sect)
1708 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.edata", 0), sect)
1709 dataGcEnd := state.datsize - int64(sect.Vaddr)
1711 // On AIX, TOC entries must be the last of .data
1712 // These aren't part of gc as they won't change during the runtime.
1713 state.assignToSection(sect, sym.SXCOFFTOC, sym.SDATA)
1714 state.checkdatsize(sym.SDATA)
1715 sect.Length = uint64(state.datsize) - sect.Vaddr
1718 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".bss", sym.SBSS, sym.Sxxx, 06)
1719 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.bss", 0), sect)
1720 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ebss", 0), sect)
1721 bssGcEnd := state.datsize - int64(sect.Vaddr)
1723 // Emit gcdata for bss symbols now that symbol values have been assigned.
1724 gcsToEmit := []struct {
1729 {"runtime.gcdata", sym.SDATA, dataGcEnd},
1730 {"runtime.gcbss", sym.SBSS, bssGcEnd},
1732 for _, g := range gcsToEmit {
1734 gc.Init(ctxt, g.symName)
1735 for _, s := range state.data[g.symKind] {
1741 /* pointer-free bss */
1742 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrbss", sym.SNOPTRBSS, sym.Sxxx, 06)
1743 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrbss", 0), sect)
1744 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrbss", 0), sect)
1745 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.end", 0), sect)
1747 // Coverage instrumentation counters for libfuzzer.
1748 if len(state.data[sym.SLIBFUZZER_EXTRA_COUNTER]) > 0 {
1749 state.allocateNamedSectionAndAssignSyms(&Segdata, "__libfuzzer_extra_counters", sym.SLIBFUZZER_EXTRA_COUNTER, sym.Sxxx, 06)
1752 if len(state.data[sym.STLSBSS]) > 0 {
1753 var sect *sym.Section
1754 // FIXME: not clear why it is sometimes necessary to suppress .tbss section creation.
1755 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && (ctxt.LinkMode == LinkExternal || !*FlagD) {
1756 sect = addsection(ldr, ctxt.Arch, &Segdata, ".tbss", 06)
1757 sect.Align = int32(ctxt.Arch.PtrSize)
1758 // FIXME: why does this need to be set to zero?
1763 for _, s := range state.data[sym.STLSBSS] {
1764 state.datsize = aligndatsize(state, state.datsize, s)
1766 ldr.SetSymSect(s, sect)
1768 ldr.SetSymValue(s, state.datsize)
1769 state.datsize += ldr.SymSize(s)
1771 state.checkdatsize(sym.STLSBSS)
1774 sect.Length = uint64(state.datsize)
1779 * We finished data, begin read-only data.
1780 * Not all systems support a separate read-only non-executable data section.
1781 * ELF and Windows PE systems do.
1782 * OS X and Plan 9 do not.
1783 * And if we're using external linking mode, the point is moot,
1784 * since it's not our decision; that code expects the sections in
1787 var segro *sym.Segment
1788 if ctxt.IsELF && ctxt.LinkMode == LinkInternal {
1790 } else if ctxt.HeadType == objabi.Hwindows {
1798 /* read-only executable ELF, Mach-O sections */
1799 if len(state.data[sym.STEXT]) != 0 {
1800 culprit := ldr.SymName(state.data[sym.STEXT][0])
1801 Errorf(nil, "dodata found an sym.STEXT symbol: %s", culprit)
1803 state.allocateSingleSymSections(&Segtext, sym.SELFRXSECT, sym.SRODATA, 05)
1804 state.allocateSingleSymSections(&Segtext, sym.SMACHOPLT, sym.SRODATA, 05)
1806 /* read-only data */
1807 sect = state.allocateNamedDataSection(segro, ".rodata", sym.ReadOnly, 04)
1808 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.rodata", 0), sect)
1809 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.erodata", 0), sect)
1810 if !ctxt.UseRelro() {
1811 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
1812 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
1814 for _, symn := range sym.ReadOnly {
1815 symnStartValue := state.datsize
1816 state.assignToSection(sect, symn, sym.SRODATA)
1817 setCarrierSize(symn, state.datsize-symnStartValue)
1818 if ctxt.HeadType == objabi.Haix {
1819 // Read-only symbols might be wrapped inside their outer
1821 // XCOFF symbol table needs to know the size of
1822 // these outer symbols.
1823 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
1827 /* read-only ELF, Mach-O sections */
1828 state.allocateSingleSymSections(segro, sym.SELFROSECT, sym.SRODATA, 04)
1830 // There is some data that are conceptually read-only but are written to by
1831 // relocations. On GNU systems, we can arrange for the dynamic linker to
1832 // mprotect sections after relocations are applied by giving them write
1833 // permissions in the object file and calling them ".data.rel.ro.FOO". We
1834 // divide the .rodata section between actual .rodata and .data.rel.ro.rodata,
1835 // but for the other sections that this applies to, we just write a read-only
1836 // .FOO section or a read-write .data.rel.ro.FOO section depending on the
1838 // TODO(mwhudson): It would make sense to do this more widely, but it makes
1839 // the system linker segfault on darwin.
1840 const relroPerm = 06
1841 const fallbackPerm = 04
1842 relroSecPerm := fallbackPerm
1843 genrelrosecname := func(suffix string) string {
1851 if ctxt.UseRelro() {
1852 segrelro := &Segrelrodata
1853 if ctxt.LinkMode == LinkExternal && !ctxt.IsAIX() && !ctxt.IsDarwin() {
1854 // Using a separate segment with an external
1855 // linker results in some programs moving
1856 // their data sections unexpectedly, which
1857 // corrupts the moduledata. So we use the
1858 // rodata segment and let the external linker
1859 // sort out a rel.ro segment.
1862 // Reset datsize for new segment.
1866 if !ctxt.IsDarwin() { // We don't need the special names on darwin.
1867 genrelrosecname = func(suffix string) string {
1868 return ".data.rel.ro" + suffix
1872 relroReadOnly := []sym.SymKind{}
1873 for _, symnro := range sym.ReadOnly {
1874 symn := sym.RelROMap[symnro]
1875 relroReadOnly = append(relroReadOnly, symn)
1878 relroSecPerm = relroPerm
1880 /* data only written by relocations */
1881 sect = state.allocateNamedDataSection(segrelro, genrelrosecname(""), relroReadOnly, relroSecPerm)
1883 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
1884 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
1886 for i, symnro := range sym.ReadOnly {
1887 if i == 0 && symnro == sym.STYPE && ctxt.HeadType != objabi.Haix {
1888 // Skip forward so that no type
1889 // reference uses a zero offset.
1890 // This is unlikely but possible in small
1891 // programs with no other read-only data.
1895 symn := sym.RelROMap[symnro]
1896 symnStartValue := state.datsize
1898 for _, s := range state.data[symn] {
1899 outer := ldr.OuterSym(s)
1900 if s != 0 && ldr.SymSect(outer) != nil && ldr.SymSect(outer) != sect {
1901 ctxt.Errorf(s, "s.Outer (%s) in different section from s, %s != %s", ldr.SymName(outer), ldr.SymSect(outer).Name, sect.Name)
1904 state.assignToSection(sect, symn, sym.SRODATA)
1905 setCarrierSize(symn, state.datsize-symnStartValue)
1906 if ctxt.HeadType == objabi.Haix {
1907 // Read-only symbols might be wrapped inside their outer
1909 // XCOFF symbol table needs to know the size of
1910 // these outer symbols.
1911 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
1915 sect.Length = uint64(state.datsize) - sect.Vaddr
1919 sect = state.allocateNamedDataSection(seg, genrelrosecname(".typelink"), []sym.SymKind{sym.STYPELINK}, relroSecPerm)
1921 typelink := ldr.CreateSymForUpdate("runtime.typelink", 0)
1922 ldr.SetSymSect(typelink.Sym(), sect)
1923 typelink.SetType(sym.SRODATA)
1924 state.datsize += typelink.Size()
1925 state.checkdatsize(sym.STYPELINK)
1926 sect.Length = uint64(state.datsize) - sect.Vaddr
1929 sect = state.allocateNamedDataSection(seg, genrelrosecname(".itablink"), []sym.SymKind{sym.SITABLINK}, relroSecPerm)
1931 itablink := ldr.CreateSymForUpdate("runtime.itablink", 0)
1932 ldr.SetSymSect(itablink.Sym(), sect)
1933 itablink.SetType(sym.SRODATA)
1934 state.datsize += itablink.Size()
1935 state.checkdatsize(sym.SITABLINK)
1936 sect.Length = uint64(state.datsize) - sect.Vaddr
1939 sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gosymtab"), sym.SSYMTAB, sym.SRODATA, relroSecPerm)
1940 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.symtab", 0), sect)
1941 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.esymtab", 0), sect)
1944 sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gopclntab"), sym.SPCLNTAB, sym.SRODATA, relroSecPerm)
1945 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0), sect)
1946 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pcheader", 0), sect)
1947 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.funcnametab", 0), sect)
1948 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.cutab", 0), sect)
1949 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.filetab", 0), sect)
1950 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pctab", 0), sect)
1951 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.functab", 0), sect)
1952 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.epclntab", 0), sect)
1953 setCarrierSize(sym.SPCLNTAB, int64(sect.Length))
1954 if ctxt.HeadType == objabi.Haix {
1955 xcoffUpdateOuterSize(ctxt, int64(sect.Length), sym.SPCLNTAB)
1958 // 6g uses 4-byte relocation offsets, so the entire segment must fit in 32 bits.
1959 if state.datsize != int64(uint32(state.datsize)) {
1960 Errorf(nil, "read-only data segment too large: %d", state.datsize)
1964 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
1965 siz += len(state.data[symn])
1967 ctxt.datap = make([]loader.Sym, 0, siz)
1968 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
1969 ctxt.datap = append(ctxt.datap, state.data[symn]...)
1973 // allocateDwarfSections allocates sym.Section objects for DWARF
1974 // symbols, and assigns symbols to sections.
1975 func (state *dodataState) allocateDwarfSections(ctxt *Link) {
1977 alignOne := func(state *dodataState, datsize int64, s loader.Sym) int64 { return datsize }
1980 for i := 0; i < len(dwarfp); i++ {
1981 // First the section symbol.
1982 s := dwarfp[i].secSym()
1983 sect := state.allocateNamedDataSection(&Segdwarf, ldr.SymName(s), []sym.SymKind{}, 04)
1984 ldr.SetSymSect(s, sect)
1985 sect.Sym = sym.LoaderSym(s)
1986 curType := ldr.SymType(s)
1987 state.setSymType(s, sym.SRODATA)
1988 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1989 state.datsize += ldr.SymSize(s)
1991 // Then any sub-symbols for the section symbol.
1992 subSyms := dwarfp[i].subSyms()
1993 state.assignDsymsToSection(sect, subSyms, sym.SRODATA, alignOne)
1995 for j := 0; j < len(subSyms); j++ {
1997 if ctxt.HeadType == objabi.Haix && curType == sym.SDWARFLOC {
1998 // Update the size of .debug_loc for this symbol's
2000 addDwsectCUSize(".debug_loc", ldr.SymPkg(s), uint64(ldr.SymSize(s)))
2003 sect.Length = uint64(state.datsize) - sect.Vaddr
2004 state.checkdatsize(curType)
2008 type symNameSize struct {
2015 func (state *dodataState) dodataSect(ctxt *Link, symn sym.SymKind, syms []loader.Sym) (result []loader.Sym, maxAlign int32) {
2016 var head, tail loader.Sym
2018 sl := make([]symNameSize, len(syms))
2019 for k, s := range syms {
2020 ss := ldr.SymSize(s)
2021 sl[k] = symNameSize{name: ldr.SymName(s), sz: ss, sym: s}
2022 ds := int64(len(ldr.Data(s)))
2025 ctxt.Errorf(s, "initialize bounds (%d < %d)", ss, ds)
2027 ctxt.Errorf(s, "negative size (%d bytes)", ss)
2029 ctxt.Errorf(s, "symbol too large (%d bytes)", ss)
2032 // If the usually-special section-marker symbols are being laid
2033 // out as regular symbols, put them either at the beginning or
2034 // end of their section.
2035 if (ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) || (ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
2036 switch ldr.SymName(s) {
2037 case "runtime.text", "runtime.bss", "runtime.data", "runtime.types", "runtime.rodata":
2040 case "runtime.etext", "runtime.ebss", "runtime.edata", "runtime.etypes", "runtime.erodata":
2047 // For ppc64, we want to interleave the .got and .toc sections
2048 // from input files. Both are type sym.SELFGOT, so in that case
2049 // we skip size comparison and fall through to the name
2050 // comparison (conveniently, .got sorts before .toc).
2051 checkSize := symn != sym.SELFGOT
2053 // Perform the sort.
2054 if symn != sym.SPCLNTAB {
2055 sort.Slice(sl, func(i, j int) bool {
2056 si, sj := sl[i].sym, sl[j].sym
2058 case si == head, sj == tail:
2060 case sj == head, si == tail:
2073 return iname < jname
2078 // PCLNTAB was built internally, and has the proper order based on value.
2079 // Sort the symbols as such.
2080 for k, s := range syms {
2081 sl[k].val = ldr.SymValue(s)
2083 sort.Slice(sl, func(i, j int) bool { return sl[i].val < sl[j].val })
2086 // Set alignment, construct result
2090 if s != head && s != tail {
2091 align := symalign(ldr, s)
2092 if maxAlign < align {
2096 syms = append(syms, s)
2099 return syms, maxAlign
2102 // Add buildid to beginning of text segment, on non-ELF systems.
2103 // Non-ELF binary formats are not always flexible enough to
2104 // give us a place to put the Go build ID. On those systems, we put it
2105 // at the very beginning of the text segment.
2106 // This ``header'' is read by cmd/go.
2107 func (ctxt *Link) textbuildid() {
2108 if ctxt.IsELF || ctxt.BuildMode == BuildModePlugin || *flagBuildid == "" {
2113 s := ldr.CreateSymForUpdate("go.buildid", 0)
2114 // The \xff is invalid UTF-8, meant to make it less likely
2115 // to find one of these accidentally.
2116 data := "\xff Go build ID: " + strconv.Quote(*flagBuildid) + "\n \xff"
2117 s.SetType(sym.STEXT)
2118 s.SetData([]byte(data))
2119 s.SetSize(int64(len(data)))
2121 ctxt.Textp = append(ctxt.Textp, 0)
2122 copy(ctxt.Textp[1:], ctxt.Textp)
2123 ctxt.Textp[0] = s.Sym()
2126 func (ctxt *Link) buildinfo() {
2127 if ctxt.linkShared || ctxt.BuildMode == BuildModePlugin {
2128 // -linkshared and -buildmode=plugin get confused
2129 // about the relocations in go.buildinfo
2130 // pointing at the other data sections.
2131 // The version information is only available in executables.
2136 s := ldr.CreateSymForUpdate(".go.buildinfo", 0)
2137 // On AIX, .go.buildinfo must be in the symbol table as
2138 // it has relocations.
2139 s.SetNotInSymbolTable(!ctxt.IsAIX())
2140 s.SetType(sym.SBUILDINFO)
2142 // The \xff is invalid UTF-8, meant to make it less likely
2143 // to find one of these accidentally.
2144 const prefix = "\xff Go buildinf:" // 14 bytes, plus 2 data bytes filled in below
2145 data := make([]byte, 32)
2147 data[len(prefix)] = byte(ctxt.Arch.PtrSize)
2148 data[len(prefix)+1] = 0
2149 if ctxt.Arch.ByteOrder == binary.BigEndian {
2150 data[len(prefix)+1] = 1
2153 s.SetSize(int64(len(data)))
2154 r, _ := s.AddRel(objabi.R_ADDR)
2156 r.SetSiz(uint8(ctxt.Arch.PtrSize))
2157 r.SetSym(ldr.LookupOrCreateSym("runtime.buildVersion", 0))
2158 r, _ = s.AddRel(objabi.R_ADDR)
2159 r.SetOff(16 + int32(ctxt.Arch.PtrSize))
2160 r.SetSiz(uint8(ctxt.Arch.PtrSize))
2161 r.SetSym(ldr.LookupOrCreateSym("runtime.modinfo", 0))
2164 // assign addresses to text
2165 func (ctxt *Link) textaddress() {
2166 addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2168 // Assign PCs in text segment.
2169 // Could parallelize, by assigning to text
2170 // and then letting threads copy down, but probably not worth it.
2171 sect := Segtext.Sections[0]
2173 sect.Align = int32(Funcalign)
2177 text := ctxt.xdefine("runtime.text", sym.STEXT, 0)
2178 etext := ctxt.xdefine("runtime.etext", sym.STEXT, 0)
2179 ldr.SetSymSect(text, sect)
2180 if ctxt.IsAIX() && ctxt.IsExternal() {
2181 // Setting runtime.text has a real symbol prevents ld to
2182 // change its base address resulting in wrong offsets for
2184 u := ldr.MakeSymbolUpdater(text)
2185 u.SetAlign(sect.Align)
2189 if (ctxt.DynlinkingGo() && ctxt.IsDarwin()) || (ctxt.IsAIX() && ctxt.IsExternal()) {
2190 ldr.SetSymSect(etext, sect)
2191 ctxt.Textp = append(ctxt.Textp, etext, 0)
2192 copy(ctxt.Textp[1:], ctxt.Textp)
2193 ctxt.Textp[0] = text
2196 va := uint64(Rnd(*FlagTextAddr, int64(Funcalign)))
2200 for _, s := range ctxt.Textp {
2201 sect, n, va = assignAddress(ctxt, sect, n, s, va, false)
2203 trampoline(ctxt, s) // resolve jumps, may add trampolines if jump too far
2205 // lay down trampolines after each function
2206 for ; ntramps < len(ctxt.tramps); ntramps++ {
2207 tramp := ctxt.tramps[ntramps]
2208 if ctxt.IsAIX() && strings.HasPrefix(ldr.SymName(tramp), "runtime.text.") {
2209 // Already set in assignAddress
2212 sect, n, va = assignAddress(ctxt, sect, n, tramp, va, true)
2216 sect.Length = va - sect.Vaddr
2217 ldr.SetSymSect(etext, sect)
2218 if ldr.SymValue(etext) == 0 {
2219 // Set the address of the start/end symbols, if not already
2220 // (i.e. not darwin+dynlink or AIX+external, see above).
2221 ldr.SetSymValue(etext, int64(va))
2222 ldr.SetSymValue(text, int64(Segtext.Sections[0].Vaddr))
2225 // merge tramps into Textp, keeping Textp in address order
2227 newtextp := make([]loader.Sym, 0, len(ctxt.Textp)+ntramps)
2229 for _, s := range ctxt.Textp {
2230 for ; i < ntramps && ldr.SymValue(ctxt.tramps[i]) < ldr.SymValue(s); i++ {
2231 newtextp = append(newtextp, ctxt.tramps[i])
2233 newtextp = append(newtextp, s)
2235 newtextp = append(newtextp, ctxt.tramps[i:ntramps]...)
2237 ctxt.Textp = newtextp
2241 // assigns address for a text symbol, returns (possibly new) section, its number, and the address
2242 func assignAddress(ctxt *Link, sect *sym.Section, n int, s loader.Sym, va uint64, isTramp bool) (*sym.Section, int, uint64) {
2244 if thearch.AssignAddress != nil {
2245 return thearch.AssignAddress(ldr, sect, n, s, va, isTramp)
2248 ldr.SetSymSect(s, sect)
2249 if ldr.AttrSubSymbol(s) {
2253 align := ldr.SymAlign(s)
2255 align = int32(Funcalign)
2257 va = uint64(Rnd(int64(va), int64(align)))
2258 if sect.Align < align {
2262 funcsize := uint64(MINFUNC) // spacing required for findfunctab
2263 if ldr.SymSize(s) > MINFUNC {
2264 funcsize = uint64(ldr.SymSize(s))
2267 // On ppc64x a text section should not be larger than 2^26 bytes due to the size of
2268 // call target offset field in the bl instruction. Splitting into smaller text
2269 // sections smaller than this limit allows the GNU linker to modify the long calls
2270 // appropriately. The limit allows for the space needed for tables inserted by the linker.
2272 // If this function doesn't fit in the current text section, then create a new one.
2274 // Only break at outermost syms.
2276 // For debugging purposes, allow text size limit to be cranked down,
2277 // so as to stress test the code that handles multiple text sections.
2278 var textSizelimit uint64 = 0x1c00000
2279 if *FlagDebugTextSize != 0 {
2280 textSizelimit = uint64(*FlagDebugTextSize)
2283 if ctxt.Arch.InFamily(sys.PPC64) && ldr.OuterSym(s) == 0 && ctxt.IsExternal() {
2284 // Sanity check: make sure the limit is larger than any
2285 // individual text symbol.
2286 if funcsize > textSizelimit {
2287 panic(fmt.Sprintf("error: ppc64 text size limit %d less than text symbol %s size of %d", textSizelimit, ldr.SymName(s), funcsize))
2290 if va-sect.Vaddr+funcsize+maxSizeTrampolinesPPC64(ldr, s, isTramp) > textSizelimit {
2291 // Set the length for the previous text section
2292 sect.Length = va - sect.Vaddr
2294 // Create new section, set the starting Vaddr
2295 sect = addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2297 ldr.SetSymSect(s, sect)
2299 // Create a symbol for the start of the secondary text sections
2300 ntext := ldr.CreateSymForUpdate(fmt.Sprintf("runtime.text.%d", n), 0)
2303 // runtime.text.X must be a real symbol on AIX.
2304 // Assign its address directly in order to be the
2305 // first symbol of this new section.
2306 ntext.SetType(sym.STEXT)
2307 ntext.SetSize(int64(MINFUNC))
2308 ntext.SetOnList(true)
2309 ctxt.tramps = append(ctxt.tramps, ntext.Sym())
2311 ntext.SetValue(int64(va))
2312 va += uint64(ntext.Size())
2314 if align := ldr.SymAlign(s); align != 0 {
2315 va = uint64(Rnd(int64(va), int64(align)))
2317 va = uint64(Rnd(int64(va), int64(Funcalign)))
2324 ldr.SetSymValue(s, 0)
2325 for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2326 ldr.SetSymValue(sub, ldr.SymValue(sub)+int64(va))
2334 // address assigns virtual addresses to all segments and sections and
2335 // returns all segments in file order.
2336 func (ctxt *Link) address() []*sym.Segment {
2337 var order []*sym.Segment // Layout order
2339 va := uint64(*FlagTextAddr)
2340 order = append(order, &Segtext)
2343 for _, s := range Segtext.Sections {
2344 va = uint64(Rnd(int64(va), int64(s.Align)))
2349 Segtext.Length = va - uint64(*FlagTextAddr)
2351 if len(Segrodata.Sections) > 0 {
2352 // align to page boundary so as not to mix
2353 // rodata and executable text.
2355 // Note: gold or GNU ld will reduce the size of the executable
2356 // file by arranging for the relro segment to end at a page
2357 // boundary, and overlap the end of the text segment with the
2358 // start of the relro segment in the file. The PT_LOAD segments
2359 // will be such that the last page of the text segment will be
2360 // mapped twice, once r-x and once starting out rw- and, after
2361 // relocation processing, changed to r--.
2363 // Ideally the last page of the text segment would not be
2364 // writable even for this short period.
2365 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2367 order = append(order, &Segrodata)
2369 Segrodata.Vaddr = va
2370 for _, s := range Segrodata.Sections {
2371 va = uint64(Rnd(int64(va), int64(s.Align)))
2376 Segrodata.Length = va - Segrodata.Vaddr
2378 if len(Segrelrodata.Sections) > 0 {
2379 // align to page boundary so as not to mix
2380 // rodata, rel-ro data, and executable text.
2381 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2382 if ctxt.HeadType == objabi.Haix {
2383 // Relro data are inside data segment on AIX.
2384 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2387 order = append(order, &Segrelrodata)
2388 Segrelrodata.Rwx = 06
2389 Segrelrodata.Vaddr = va
2390 for _, s := range Segrelrodata.Sections {
2391 va = uint64(Rnd(int64(va), int64(s.Align)))
2396 Segrelrodata.Length = va - Segrelrodata.Vaddr
2399 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2400 if ctxt.HeadType == objabi.Haix && len(Segrelrodata.Sections) == 0 {
2401 // Data sections are moved to an unreachable segment
2402 // to ensure that they are position-independent.
2403 // Already done if relro sections exist.
2404 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2406 order = append(order, &Segdata)
2409 var data *sym.Section
2410 var noptr *sym.Section
2411 var bss *sym.Section
2412 var noptrbss *sym.Section
2413 for i, s := range Segdata.Sections {
2414 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && s.Name == ".tbss" {
2417 vlen := int64(s.Length)
2418 if i+1 < len(Segdata.Sections) && !((ctxt.IsELF || ctxt.HeadType == objabi.Haix) && Segdata.Sections[i+1].Name == ".tbss") {
2419 vlen = int64(Segdata.Sections[i+1].Vaddr - s.Vaddr)
2423 Segdata.Length = va - Segdata.Vaddr
2424 if s.Name == ".data" {
2427 if s.Name == ".noptrdata" {
2430 if s.Name == ".bss" {
2433 if s.Name == ".noptrbss" {
2438 // Assign Segdata's Filelen omitting the BSS. We do this here
2439 // simply because right now we know where the BSS starts.
2440 Segdata.Filelen = bss.Vaddr - Segdata.Vaddr
2442 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2443 order = append(order, &Segdwarf)
2446 for i, s := range Segdwarf.Sections {
2447 vlen := int64(s.Length)
2448 if i+1 < len(Segdwarf.Sections) {
2449 vlen = int64(Segdwarf.Sections[i+1].Vaddr - s.Vaddr)
2453 if ctxt.HeadType == objabi.Hwindows {
2454 va = uint64(Rnd(int64(va), PEFILEALIGN))
2456 Segdwarf.Length = va - Segdwarf.Vaddr
2461 rodata = ldr.SymSect(ldr.LookupOrCreateSym("runtime.rodata", 0))
2462 symtab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.symtab", 0))
2463 pclntab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0))
2464 types = ldr.SymSect(ldr.LookupOrCreateSym("runtime.types", 0))
2467 for _, s := range ctxt.datap {
2468 if sect := ldr.SymSect(s); sect != nil {
2469 ldr.AddToSymValue(s, int64(sect.Vaddr))
2471 v := ldr.SymValue(s)
2472 for sub := ldr.SubSym(s); sub != 0; sub = ldr.SubSym(sub) {
2473 ldr.AddToSymValue(sub, v)
2477 for _, si := range dwarfp {
2478 for _, s := range si.syms {
2479 if sect := ldr.SymSect(s); sect != nil {
2480 ldr.AddToSymValue(s, int64(sect.Vaddr))
2482 sub := ldr.SubSym(s)
2484 panic(fmt.Sprintf("unexpected sub-sym for %s %s", ldr.SymName(s), ldr.SymType(s).String()))
2486 v := ldr.SymValue(s)
2487 for ; sub != 0; sub = ldr.SubSym(sub) {
2488 ldr.AddToSymValue(s, v)
2493 if ctxt.BuildMode == BuildModeShared {
2494 s := ldr.LookupOrCreateSym("go.link.abihashbytes", 0)
2495 sect := ldr.SymSect(ldr.LookupOrCreateSym(".note.go.abihash", 0))
2496 ldr.SetSymSect(s, sect)
2497 ldr.SetSymValue(s, int64(sect.Vaddr+16))
2500 // If there are multiple text sections, create runtime.text.n for
2501 // their section Vaddr, using n for index
2503 for _, sect := range Segtext.Sections[1:] {
2504 if sect.Name != ".text" {
2507 symname := fmt.Sprintf("runtime.text.%d", n)
2508 if ctxt.HeadType != objabi.Haix || ctxt.LinkMode != LinkExternal {
2509 // Addresses are already set on AIX with external linker
2510 // because these symbols are part of their sections.
2511 ctxt.xdefine(symname, sym.STEXT, int64(sect.Vaddr))
2516 ctxt.xdefine("runtime.rodata", sym.SRODATA, int64(rodata.Vaddr))
2517 ctxt.xdefine("runtime.erodata", sym.SRODATA, int64(rodata.Vaddr+rodata.Length))
2518 ctxt.xdefine("runtime.types", sym.SRODATA, int64(types.Vaddr))
2519 ctxt.xdefine("runtime.etypes", sym.SRODATA, int64(types.Vaddr+types.Length))
2521 s := ldr.Lookup("runtime.gcdata", 0)
2522 ldr.SetAttrLocal(s, true)
2523 ctxt.xdefine("runtime.egcdata", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2524 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcdata", 0), ldr.SymSect(s))
2526 s = ldr.LookupOrCreateSym("runtime.gcbss", 0)
2527 ldr.SetAttrLocal(s, true)
2528 ctxt.xdefine("runtime.egcbss", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2529 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcbss", 0), ldr.SymSect(s))
2531 ctxt.xdefine("runtime.symtab", sym.SRODATA, int64(symtab.Vaddr))
2532 ctxt.xdefine("runtime.esymtab", sym.SRODATA, int64(symtab.Vaddr+symtab.Length))
2533 ctxt.xdefine("runtime.pclntab", sym.SRODATA, int64(pclntab.Vaddr))
2534 ctxt.defineInternal("runtime.pcheader", sym.SRODATA)
2535 ctxt.defineInternal("runtime.funcnametab", sym.SRODATA)
2536 ctxt.defineInternal("runtime.cutab", sym.SRODATA)
2537 ctxt.defineInternal("runtime.filetab", sym.SRODATA)
2538 ctxt.defineInternal("runtime.pctab", sym.SRODATA)
2539 ctxt.defineInternal("runtime.functab", sym.SRODATA)
2540 ctxt.xdefine("runtime.epclntab", sym.SRODATA, int64(pclntab.Vaddr+pclntab.Length))
2541 ctxt.xdefine("runtime.noptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr))
2542 ctxt.xdefine("runtime.enoptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr+noptr.Length))
2543 ctxt.xdefine("runtime.bss", sym.SBSS, int64(bss.Vaddr))
2544 ctxt.xdefine("runtime.ebss", sym.SBSS, int64(bss.Vaddr+bss.Length))
2545 ctxt.xdefine("runtime.data", sym.SDATA, int64(data.Vaddr))
2546 ctxt.xdefine("runtime.edata", sym.SDATA, int64(data.Vaddr+data.Length))
2547 ctxt.xdefine("runtime.noptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr))
2548 ctxt.xdefine("runtime.enoptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr+noptrbss.Length))
2549 ctxt.xdefine("runtime.end", sym.SBSS, int64(Segdata.Vaddr+Segdata.Length))
2551 if ctxt.IsSolaris() {
2552 // On Solaris, in the runtime it sets the external names of the
2553 // end symbols. Unset them and define separate symbols, so we
2555 etext := ldr.Lookup("runtime.etext", 0)
2556 edata := ldr.Lookup("runtime.edata", 0)
2557 end := ldr.Lookup("runtime.end", 0)
2558 ldr.SetSymExtname(etext, "runtime.etext")
2559 ldr.SetSymExtname(edata, "runtime.edata")
2560 ldr.SetSymExtname(end, "runtime.end")
2561 ctxt.xdefine("_etext", ldr.SymType(etext), ldr.SymValue(etext))
2562 ctxt.xdefine("_edata", ldr.SymType(edata), ldr.SymValue(edata))
2563 ctxt.xdefine("_end", ldr.SymType(end), ldr.SymValue(end))
2564 ldr.SetSymSect(ldr.Lookup("_etext", 0), ldr.SymSect(etext))
2565 ldr.SetSymSect(ldr.Lookup("_edata", 0), ldr.SymSect(edata))
2566 ldr.SetSymSect(ldr.Lookup("_end", 0), ldr.SymSect(end))
2572 // layout assigns file offsets and lengths to the segments in order.
2573 // Returns the file size containing all the segments.
2574 func (ctxt *Link) layout(order []*sym.Segment) uint64 {
2575 var prev *sym.Segment
2576 for _, seg := range order {
2578 seg.Fileoff = uint64(HEADR)
2580 switch ctxt.HeadType {
2582 // Assuming the previous segment was
2583 // aligned, the following rounding
2584 // should ensure that this segment's
2585 // VA ≡ Fileoff mod FlagRound.
2586 seg.Fileoff = uint64(Rnd(int64(prev.Fileoff+prev.Filelen), int64(*FlagRound)))
2587 if seg.Vaddr%uint64(*FlagRound) != seg.Fileoff%uint64(*FlagRound) {
2588 Exitf("bad segment rounding (Vaddr=%#x Fileoff=%#x FlagRound=%#x)", seg.Vaddr, seg.Fileoff, *FlagRound)
2590 case objabi.Hwindows:
2591 seg.Fileoff = prev.Fileoff + uint64(Rnd(int64(prev.Filelen), PEFILEALIGN))
2593 seg.Fileoff = prev.Fileoff + prev.Filelen
2596 if seg != &Segdata {
2597 // Link.address already set Segdata.Filelen to
2599 seg.Filelen = seg.Length
2603 return prev.Fileoff + prev.Filelen
2606 // add a trampoline with symbol s (to be laid down after the current function)
2607 func (ctxt *Link) AddTramp(s *loader.SymbolBuilder) {
2608 s.SetType(sym.STEXT)
2609 s.SetReachable(true)
2611 ctxt.tramps = append(ctxt.tramps, s.Sym())
2612 if *FlagDebugTramp > 0 && ctxt.Debugvlog > 0 {
2613 ctxt.Logf("trampoline %s inserted\n", s.Name())
2617 // compressSyms compresses syms and returns the contents of the
2618 // compressed section. If the section would get larger, it returns nil.
2619 func compressSyms(ctxt *Link, syms []loader.Sym) []byte {
2622 for _, sym := range syms {
2623 total += ldr.SymSize(sym)
2626 var buf bytes.Buffer
2627 buf.Write([]byte("ZLIB"))
2628 var sizeBytes [8]byte
2629 binary.BigEndian.PutUint64(sizeBytes[:], uint64(total))
2630 buf.Write(sizeBytes[:])
2632 var relocbuf []byte // temporary buffer for applying relocations
2634 // Using zlib.BestSpeed achieves very nearly the same
2635 // compression levels of zlib.DefaultCompression, but takes
2636 // substantially less time. This is important because DWARF
2637 // compression can be a significant fraction of link time.
2638 z, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
2640 log.Fatalf("NewWriterLevel failed: %s", err)
2642 st := ctxt.makeRelocSymState()
2643 for _, s := range syms {
2644 // Symbol data may be read-only. Apply relocations in a
2645 // temporary buffer, and immediately write it out.
2647 relocs := ldr.Relocs(s)
2648 if relocs.Count() != 0 {
2649 relocbuf = append(relocbuf[:0], P...)
2653 if _, err := z.Write(P); err != nil {
2654 log.Fatalf("compression failed: %s", err)
2656 for i := ldr.SymSize(s) - int64(len(P)); i > 0; {
2658 if i < int64(len(b)) {
2661 n, err := z.Write(b)
2663 log.Fatalf("compression failed: %s", err)
2668 if err := z.Close(); err != nil {
2669 log.Fatalf("compression failed: %s", err)
2671 if int64(buf.Len()) >= total {
2672 // Compression didn't save any space.