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/loadpe"
41 "cmd/link/internal/sym"
55 // isRuntimeDepPkg reports whether pkg is the runtime package or its dependency.
56 func isRuntimeDepPkg(pkg string) bool {
59 "sync/atomic", // runtime may call to sync/atomic, due to go:linkname
60 "internal/abi", // used by reflectcall (and maybe more)
61 "internal/bytealg", // for IndexByte
62 "internal/cpu": // for cpu features
65 return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test")
68 // Estimate the max size needed to hold any new trampolines created for this function. This
69 // is used to determine when the section can be split if it becomes too large, to ensure that
70 // the trampolines are in the same section as the function that uses them.
71 func maxSizeTrampolines(ctxt *Link, ldr *loader.Loader, s loader.Sym, isTramp bool) uint64 {
72 // If thearch.Trampoline is nil, then trampoline support is not available on this arch.
73 // A trampoline does not need any dependent trampolines.
74 if thearch.Trampoline == nil || isTramp {
79 relocs := ldr.Relocs(s)
80 for ri := 0; ri < relocs.Count(); ri++ {
82 if r.Type().IsDirectCallOrJump() {
89 return n * 20 // Trampolines in ARM range from 3 to 5 instructions.
91 return n * 12 // Trampolines in ARM64 are 3 instructions.
93 return n * 16 // Trampolines in PPC64 are 4 instructions.
94 case ctxt.IsRISCV64():
95 return n * 8 // Trampolines in RISCV64 are 2 instructions.
100 // Detect too-far jumps in function s, and add trampolines if necessary.
101 // ARM, PPC64, PPC64LE and RISCV64 support trampoline insertion for internal
102 // and external linking. On PPC64 and PPC64LE the text sections might be split
103 // but will still insert trampolines where necessary.
104 func trampoline(ctxt *Link, s loader.Sym) {
105 if thearch.Trampoline == nil {
106 return // no need or no support of trampolines on this arch
110 relocs := ldr.Relocs(s)
111 for ri := 0; ri < relocs.Count(); ri++ {
114 if !rt.IsDirectCallOrJump() && !isPLTCall(rt) {
118 if !ldr.AttrReachable(rs) || ldr.SymType(rs) == sym.Sxxx {
119 continue // something is wrong. skip it here and we'll emit a better error later
122 if ldr.SymValue(rs) == 0 && ldr.SymType(rs) != sym.SDYNIMPORT && ldr.SymType(rs) != sym.SUNDEFEXT {
123 // Symbols in the same package are laid out together.
124 // Except that if SymPkg(s) == "", it is a host object symbol
125 // which may call an external symbol via PLT.
126 if ldr.SymPkg(s) != "" && ldr.SymPkg(rs) == ldr.SymPkg(s) {
127 // RISC-V is only able to reach +/-1MiB via a JAL instruction.
128 // We need to generate a trampoline when an address is
129 // currently unknown.
130 if !ctxt.Target.IsRISCV64() {
134 // Runtime packages are laid out together.
135 if isRuntimeDepPkg(ldr.SymPkg(s)) && isRuntimeDepPkg(ldr.SymPkg(rs)) {
139 thearch.Trampoline(ctxt, ldr, ri, rs, s)
143 // whether rt is a (host object) relocation that will be turned into
145 func isPLTCall(rt objabi.RelocType) bool {
149 case objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_CALL26),
150 objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_JUMP26),
151 objabi.MachoRelocOffset + MACHO_ARM64_RELOC_BRANCH26*2 + pcrel:
155 case objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_CALL),
156 objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_PC24),
157 objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_JUMP24):
160 // TODO: other architectures.
164 // FoldSubSymbolOffset computes the offset of symbol s to its top-level outer
165 // symbol. Returns the top-level symbol and the offset.
166 // This is used in generating external relocations.
167 func FoldSubSymbolOffset(ldr *loader.Loader, s loader.Sym) (loader.Sym, int64) {
168 outer := ldr.OuterSym(s)
171 off += ldr.SymValue(s) - ldr.SymValue(outer)
177 // relocsym resolve relocations in "s", updating the symbol's content
179 // The main loop walks through the list of relocations attached to "s"
180 // and resolves them where applicable. Relocations are often
181 // architecture-specific, requiring calls into the 'archreloc' and/or
182 // 'archrelocvariant' functions for the architecture. When external
183 // linking is in effect, it may not be possible to completely resolve
184 // the address/offset for a symbol, in which case the goal is to lay
185 // the groundwork for turning a given relocation into an external reloc
186 // (to be applied by the external linker). For more on how relocations
187 // work in general, see
189 // "Linkers and Loaders", by John R. Levine (Morgan Kaufmann, 1999), ch. 7
191 // This is a performance-critical function for the linker; be careful
192 // to avoid introducing unnecessary allocations in the main loop.
193 func (st *relocSymState) relocsym(s loader.Sym, P []byte) {
195 relocs := ldr.Relocs(s)
196 if relocs.Count() == 0 {
201 nExtReloc := 0 // number of external relocations
202 for ri := 0; ri < relocs.Count(); ri++ {
205 siz := int32(r.Siz())
209 if off < 0 || off+siz > int32(len(P)) {
212 rname = ldr.SymName(rs)
214 st.err.Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(P))
217 if siz == 0 { // informational relocation - no work to do
223 rst = ldr.SymType(rs)
226 if rs != 0 && (rst == sym.Sxxx || rst == sym.SXREF) {
227 // When putting the runtime but not main into a shared library
228 // these symbols are undefined and that's OK.
229 if target.IsShared() || target.IsPlugin() {
230 if ldr.SymName(rs) == "main.main" || (!target.IsPlugin() && ldr.SymName(rs) == "main..inittask") {
231 sb := ldr.MakeSymbolUpdater(rs)
232 sb.SetType(sym.SDYNIMPORT)
233 } else if strings.HasPrefix(ldr.SymName(rs), "go:info.") {
234 // Skip go.info symbols. They are only needed to communicate
235 // DWARF info between the compiler and linker.
238 } else if target.IsPPC64() && ldr.SymName(rs) == ".TOC." {
239 // TOC symbol doesn't have a type but we do assign a value
240 // (see the address pass) and we can resolve it.
241 // TODO: give it a type.
243 st.err.errorUnresolved(ldr, s, rs)
248 if rt >= objabi.ElfRelocOffset {
252 // We need to be able to reference dynimport symbols when linking against
253 // shared libraries, and AIX, Darwin, OpenBSD and Solaris always need it.
254 if !target.IsAIX() && !target.IsDarwin() && !target.IsSolaris() && !target.IsOpenbsd() && rs != 0 && rst == sym.SDYNIMPORT && !target.IsDynlinkingGo() && !ldr.AttrSubSymbol(rs) {
255 if !(target.IsPPC64() && target.IsExternal() && ldr.SymName(rs) == ".TOC.") {
256 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))
259 if rs != 0 && rst != sym.STLSBSS && !weak && rt != objabi.R_METHODOFF && !ldr.AttrReachable(rs) {
260 st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
263 var rv sym.RelocVariant
264 if target.IsPPC64() || target.IsS390X() {
265 rv = ldr.RelocVariant(s, ri)
268 // TODO(mundaym): remove this special case - see issue 14218.
269 if target.IsS390X() {
271 case objabi.R_PCRELDBL:
284 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
288 o = int64(target.Arch.ByteOrder.Uint16(P[off:]))
290 o = int64(target.Arch.ByteOrder.Uint32(P[off:]))
292 o = int64(target.Arch.ByteOrder.Uint64(P[off:]))
294 out, n, ok := thearch.Archreloc(target, ldr, syms, r, s, o)
295 if target.IsExternal() {
301 st.err.Errorf(s, "unknown reloc to %v: %d (%s)", ldr.SymName(rs), rt, sym.RelocName(target.Arch, rt))
303 case objabi.R_TLS_LE:
304 if target.IsExternal() && target.IsElf() {
307 if !target.IsAMD64() {
313 if target.IsElf() && target.IsARM() {
314 // On ELF ARM, the thread pointer is 8 bytes before
315 // the start of the thread-local data block, so add 8
316 // to the actual TLS offset (r->sym->value).
317 // This 8 seems to be a fundamental constant of
318 // ELF on ARM (or maybe Glibc on ARM); it is not
319 // related to the fact that our own TLS storage happens
320 // to take up 8 bytes.
321 o = 8 + ldr.SymValue(rs)
322 } else if target.IsElf() || target.IsPlan9() || target.IsDarwin() {
323 o = int64(syms.Tlsoffset) + r.Add()
324 } else if target.IsWindows() {
327 log.Fatalf("unexpected R_TLS_LE relocation for %v", target.HeadType)
329 case objabi.R_TLS_IE:
330 if target.IsExternal() && target.IsElf() {
333 if !target.IsAMD64() {
337 nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
341 if target.IsPIE() && target.IsElf() {
342 // We are linking the final executable, so we
343 // can optimize any TLS IE relocation to LE.
344 if thearch.TLSIEtoLE == nil {
345 log.Fatalf("internal linking of TLS IE not supported on %v", target.Arch.Family)
347 thearch.TLSIEtoLE(P, int(off), int(siz))
348 o = int64(syms.Tlsoffset)
350 log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", ldr.SymName(s))
352 case objabi.R_ADDR, objabi.R_PEIMAGEOFF:
353 if weak && !ldr.AttrReachable(rs) {
354 // Redirect it to runtime.unreachableMethod, which will throw if called.
355 rs = syms.unreachableMethod
357 if target.IsExternal() {
360 // set up addend for eventual relocation via outer symbol.
362 rs, off := FoldSubSymbolOffset(ldr, rs)
363 xadd := r.Add() + off
364 rst := ldr.SymType(rs)
365 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
366 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
371 if target.IsAMD64() {
374 } else if target.IsDarwin() {
375 if ldr.SymType(s).IsDWARF() {
376 // We generally use symbol-targeted relocations.
377 // DWARF tools seem to only handle section-targeted relocations,
378 // so generate section-targeted relocations in DWARF sections.
379 // See also machoreloc1.
380 o += ldr.SymValue(rs)
382 } else if target.IsWindows() {
384 } else if target.IsAIX() {
385 o = ldr.SymValue(rs) + xadd
387 st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
393 // On AIX, a second relocation must be done by the loader,
394 // as section addresses can change once loaded.
395 // The "default" symbol address is still needed by the loader so
396 // the current relocation can't be skipped.
397 if target.IsAIX() && rst != sym.SDYNIMPORT {
398 // It's not possible to make a loader relocation in a
399 // symbol which is not inside .data section.
400 // FIXME: It should be forbidden to have R_ADDR from a
401 // symbol which isn't in .data. However, as .text has the
402 // same address once loaded, this is possible.
403 if ldr.SymSect(s).Seg == &Segdata {
404 Xcoffadddynrel(target, ldr, syms, s, r, ri)
408 o = ldr.SymValue(rs) + r.Add()
409 if rt == objabi.R_PEIMAGEOFF {
410 // The R_PEIMAGEOFF offset is a RVA, so subtract
411 // the base address for the executable.
415 // On amd64, 4-byte offsets will be sign-extended, so it is impossible to
416 // access more than 2GB of static data; fail at link time is better than
417 // fail at runtime. See https://golang.org/issue/7980.
418 // Instead of special casing only amd64, we treat this as an error on all
419 // 64-bit architectures so as to be future-proof.
420 if int32(o) < 0 && target.Arch.PtrSize > 4 && siz == 4 {
421 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())
424 case objabi.R_DWARFSECREF:
425 if ldr.SymSect(rs) == nil {
426 st.err.Errorf(s, "missing DWARF section for relocation target %s", ldr.SymName(rs))
429 if target.IsExternal() {
430 // On most platforms, the external linker needs to adjust DWARF references
431 // as it combines DWARF sections. However, on Darwin, dsymutil does the
432 // DWARF linking, and it understands how to follow section offsets.
433 // Leaving in the relocation records confuses it (see
434 // https://golang.org/issue/22068) so drop them for Darwin.
435 if !target.IsDarwin() {
439 xadd := r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
442 if target.IsElf() && target.IsAMD64() {
447 o = ldr.SymValue(rs) + r.Add() - int64(ldr.SymSect(rs).Vaddr)
448 case objabi.R_METHODOFF:
449 if !ldr.AttrReachable(rs) {
450 // Set it to a sentinel value. The runtime knows this is not pointing to
456 case objabi.R_ADDROFF:
457 if weak && !ldr.AttrReachable(rs) {
460 sect := ldr.SymSect(rs)
462 if rst == sym.SDYNIMPORT {
463 st.err.Errorf(s, "cannot target DYNIMPORT sym in section-relative reloc: %s", ldr.SymName(rs))
464 } else if rst == sym.SUNDEFEXT {
465 st.err.Errorf(s, "undefined symbol in relocation: %s", ldr.SymName(rs))
467 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
472 // The method offset tables using this relocation expect the offset to be relative
473 // to the start of the first text section, even if there are multiple.
474 if sect.Name == ".text" {
475 o = ldr.SymValue(rs) - int64(Segtext.Sections[0].Vaddr) + r.Add()
477 o = ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr) + r.Add()
480 case objabi.R_ADDRCUOFF:
481 // debug_range and debug_loc elements use this relocation type to get an
482 // offset from the start of the compile unit.
483 o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(loader.Sym(ldr.SymUnit(rs).Textp[0]))
485 // r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
486 case objabi.R_GOTPCREL:
487 if target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
492 if target.Is386() && target.IsExternal() && target.IsELF {
493 nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
496 case objabi.R_CALL, objabi.R_PCREL:
497 if target.IsExternal() && rs != 0 && rst == sym.SUNDEFEXT {
498 // pass through to the external linker.
503 if target.IsExternal() && rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
506 // set up addend for eventual relocation via outer symbol.
508 rs, off := FoldSubSymbolOffset(ldr, rs)
509 xadd := r.Add() + off - int64(siz) // relative to address after the relocated chunk
510 rst := ldr.SymType(rs)
511 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && ldr.SymSect(rs) == nil {
512 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
517 if target.IsAMD64() {
520 } else if target.IsDarwin() {
521 if rt == objabi.R_CALL {
522 if target.IsExternal() && rst == sym.SDYNIMPORT {
523 if target.IsAMD64() {
524 // AMD64 dynamic relocations are relative to the end of the relocation.
528 if rst != sym.SHOSTOBJ {
529 o += int64(uint64(ldr.SymValue(rs)) - ldr.SymSect(rs).Vaddr)
531 o -= int64(off) // relative to section offset, not symbol
536 } else if target.IsWindows() && target.IsAMD64() { // only amd64 needs PCREL
537 // PE/COFF's PC32 relocation uses the address after the relocated
538 // bytes as the base. Compensate by skewing the addend.
541 st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
552 o += r.Add() - (ldr.SymValue(s) + int64(off) + int64(siz))
554 o = ldr.SymSize(rs) + r.Add()
556 case objabi.R_XCOFFREF:
558 st.err.Errorf(s, "find XCOFF R_REF on non-XCOFF files")
560 if !target.IsExternal() {
561 st.err.Errorf(s, "find XCOFF R_REF with internal linking")
566 case objabi.R_DWARFFILEREF:
567 // We don't renumber files in dwarf.go:writelines anymore.
573 case objabi.R_GOTOFF:
574 o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(syms.GOT)
577 if target.IsPPC64() || target.IsS390X() {
578 if rv != sym.RV_NONE {
579 o = thearch.Archrelocvariant(target, ldr, r, rv, s, o, P)
585 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
587 P[off] = byte(int8(o))
589 if (rt == objabi.R_PCREL || rt == objabi.R_CALL) && o != int64(int16(o)) {
590 st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
591 } else if o != int64(int16(o)) && o != int64(uint16(o)) {
592 st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
594 target.Arch.ByteOrder.PutUint16(P[off:], uint16(o))
596 if (rt == objabi.R_PCREL || rt == objabi.R_CALL) && o != int64(int32(o)) {
597 st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
598 } else if o != int64(int32(o)) && o != int64(uint32(o)) {
599 st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
601 target.Arch.ByteOrder.PutUint32(P[off:], uint32(o))
603 target.Arch.ByteOrder.PutUint64(P[off:], uint64(o))
606 if target.IsExternal() {
607 // We'll stream out the external relocations in asmb2 (e.g. elfrelocsect)
608 // and we only need the count here.
609 atomic.AddUint32(&ldr.SymSect(s).Relcount, uint32(nExtReloc))
613 // Convert a Go relocation to an external relocation.
614 func extreloc(ctxt *Link, ldr *loader.Loader, s loader.Sym, r loader.Reloc) (loader.ExtReloc, bool) {
615 var rr loader.ExtReloc
616 target := &ctxt.Target
617 siz := int32(r.Siz())
618 if siz == 0 { // informational relocation - no work to do
623 if rt >= objabi.ElfRelocOffset {
629 // TODO(mundaym): remove this special case - see issue 14218.
630 if target.IsS390X() {
632 case objabi.R_PCRELDBL:
639 return thearch.Extreloc(target, ldr, r, s)
641 case objabi.R_TLS_LE, objabi.R_TLS_IE:
653 case objabi.R_ADDR, objabi.R_PEIMAGEOFF:
654 // set up addend for eventual relocation via outer symbol.
656 if r.Weak() && !ldr.AttrReachable(rs) {
657 rs = ctxt.ArchSyms.unreachableMethod
659 rs, off := FoldSubSymbolOffset(ldr, rs)
660 rr.Xadd = r.Add() + off
663 case objabi.R_DWARFSECREF:
664 // On most platforms, the external linker needs to adjust DWARF references
665 // as it combines DWARF sections. However, on Darwin, dsymutil does the
666 // DWARF linking, and it understands how to follow section offsets.
667 // Leaving in the relocation records confuses it (see
668 // https://golang.org/issue/22068) so drop them for Darwin.
669 if target.IsDarwin() {
673 rr.Xsym = loader.Sym(ldr.SymSect(rs).Sym)
674 rr.Xadd = r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
676 // r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
677 case objabi.R_GOTPCREL, objabi.R_CALL, objabi.R_PCREL:
679 if rt == objabi.R_GOTPCREL && target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
681 rr.Xadd -= int64(siz) // relative to address after the relocated chunk
685 if rs != 0 && ldr.SymType(rs) == sym.SUNDEFEXT {
686 // pass through to the external linker.
689 rr.Xadd -= int64(siz)
694 if rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
695 // set up addend for eventual relocation via outer symbol.
697 rs, off := FoldSubSymbolOffset(ldr, rs)
698 rr.Xadd = r.Add() + off
699 rr.Xadd -= int64(siz) // relative to address after the relocated chunk
705 case objabi.R_XCOFFREF:
706 return ExtrelocSimple(ldr, r), true
708 // These reloc types don't need external relocations.
709 case objabi.R_ADDROFF, objabi.R_METHODOFF, objabi.R_ADDRCUOFF,
710 objabi.R_SIZE, objabi.R_CONST, objabi.R_GOTOFF:
716 // ExtrelocSimple creates a simple external relocation from r, with the same
717 // symbol and addend.
718 func ExtrelocSimple(ldr *loader.Loader, r loader.Reloc) loader.ExtReloc {
719 var rr loader.ExtReloc
728 // ExtrelocViaOuterSym creates an external relocation from r targeting the
729 // outer symbol and folding the subsymbol's offset into the addend.
730 func ExtrelocViaOuterSym(ldr *loader.Loader, r loader.Reloc, s loader.Sym) loader.ExtReloc {
731 // set up addend for eventual relocation via outer symbol.
732 var rr loader.ExtReloc
734 rs, off := FoldSubSymbolOffset(ldr, rs)
735 rr.Xadd = r.Add() + off
736 rst := ldr.SymType(rs)
737 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
738 ldr.Errorf(s, "missing section for %s", ldr.SymName(rs))
746 // relocSymState hold state information needed when making a series of
747 // successive calls to relocsym(). The items here are invariant
748 // (meaning that they are set up once initially and then don't change
749 // during the execution of relocsym), with the exception of a slice
750 // used to facilitate batch allocation of external relocations. Calls
751 // to relocsym happen in parallel; the assumption is that each
752 // parallel thread will have its own state object.
753 type relocSymState struct {
760 // makeRelocSymState creates a relocSymState container object to
761 // pass to relocsym(). If relocsym() calls happen in parallel,
762 // each parallel thread should have its own state object.
763 func (ctxt *Link) makeRelocSymState() *relocSymState {
764 return &relocSymState{
765 target: &ctxt.Target,
767 err: &ctxt.ErrorReporter,
768 syms: &ctxt.ArchSyms,
772 // windynrelocsym examines a text symbol 's' and looks for relocations
773 // from it that correspond to references to symbols defined in DLLs,
774 // then fixes up those relocations as needed. A reference to a symbol
775 // XYZ from some DLL will fall into one of two categories: an indirect
776 // ref via "__imp_XYZ", or a direct ref to "XYZ". Here's an example of
777 // an indirect ref (this is an excerpt from objdump -ldr):
779 // 1c1: 48 89 c6 movq %rax, %rsi
780 // 1c4: ff 15 00 00 00 00 callq *(%rip)
781 // 00000000000001c6: IMAGE_REL_AMD64_REL32 __imp__errno
783 // In the assembly above, the code loads up the value of __imp_errno
784 // and then does an indirect call to that value.
786 // Here is what a direct reference might look like:
788 // 137: e9 20 06 00 00 jmp 0x75c <pow+0x75c>
789 // 13c: e8 00 00 00 00 callq 0x141 <pow+0x141>
790 // 000000000000013d: IMAGE_REL_AMD64_REL32 _errno
792 // The assembly below dispenses with the import symbol and just makes
793 // a direct call to _errno.
795 // The code below handles indirect refs by redirecting the target of
796 // the relocation from "__imp_XYZ" to "XYZ" (since the latter symbol
797 // is what the Windows loader is expected to resolve). For direct refs
798 // the call is redirected to a stub, where the stub first loads the
799 // symbol and then direct an indirect call to that value.
801 // Note that for a given symbol (as above) it is perfectly legal to
802 // have both direct and indirect references.
803 func windynrelocsym(ctxt *Link, rel *loader.SymbolBuilder, s loader.Sym) error {
804 var su *loader.SymbolBuilder
805 relocs := ctxt.loader.Relocs(s)
806 for ri := 0; ri < relocs.Count(); ri++ {
809 continue // skip marker relocations
815 if !ctxt.loader.AttrReachable(targ) {
819 return fmt.Errorf("dynamic relocation to unreachable symbol %s",
820 ctxt.loader.SymName(targ))
822 tgot := ctxt.loader.SymGot(targ)
823 if tgot == loadpe.RedirectToDynImportGotToken {
825 // Consistency check: name should be __imp_X
826 sname := ctxt.loader.SymName(targ)
827 if !strings.HasPrefix(sname, "__imp_") {
828 return fmt.Errorf("internal error in windynrelocsym: redirect GOT token applied to non-import symbol %s", sname)
831 // Locate underlying symbol (which originally had type
832 // SDYNIMPORT but has since been retyped to SWINDOWS).
833 ds, err := loadpe.LookupBaseFromImport(targ, ctxt.loader, ctxt.Arch)
837 dstyp := ctxt.loader.SymType(ds)
838 if dstyp != sym.SWINDOWS {
839 return fmt.Errorf("internal error in windynrelocsym: underlying sym for %q has wrong type %s", sname, dstyp.String())
842 // Redirect relocation to the dynimport.
847 tplt := ctxt.loader.SymPlt(targ)
848 if tplt == loadpe.CreateImportStubPltToken {
850 // Consistency check: don't want to see both PLT and GOT tokens.
852 return fmt.Errorf("internal error in windynrelocsym: invalid GOT setting %d for reloc to %s", tgot, ctxt.loader.SymName(targ))
855 // make dynimport JMP table for PE object files.
856 tplt := int32(rel.Size())
857 ctxt.loader.SetPlt(targ, tplt)
860 su = ctxt.loader.MakeSymbolUpdater(s)
863 r.SetAdd(int64(tplt))
866 switch ctxt.Arch.Family {
868 return fmt.Errorf("internal error in windynrelocsym: unsupported arch %v", ctxt.Arch.Family)
872 rel.AddAddrPlus(ctxt.Arch, targ, 0)
879 rel.AddAddrPlus4(ctxt.Arch, targ, 0)
882 } else if tplt >= 0 {
884 su = ctxt.loader.MakeSymbolUpdater(s)
887 r.SetAdd(int64(tplt))
893 // windynrelocsyms generates jump table to C library functions that will be
894 // added later. windynrelocsyms writes the table into .rel symbol.
895 func (ctxt *Link) windynrelocsyms() {
896 if !(ctxt.IsWindows() && iscgo && ctxt.IsInternal()) {
900 rel := ctxt.loader.CreateSymForUpdate(".rel", 0)
901 rel.SetType(sym.STEXT)
903 for _, s := range ctxt.Textp {
904 if err := windynrelocsym(ctxt, rel, s); err != nil {
905 ctxt.Errorf(s, "%v", err)
909 ctxt.Textp = append(ctxt.Textp, rel.Sym())
912 func dynrelocsym(ctxt *Link, s loader.Sym) {
913 target := &ctxt.Target
915 syms := &ctxt.ArchSyms
916 relocs := ldr.Relocs(s)
917 for ri := 0; ri < relocs.Count(); ri++ {
920 continue // skip marker relocations
923 if r.Weak() && !ldr.AttrReachable(rSym) {
926 if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal {
927 // It's expected that some relocations will be done
928 // later by relocsym (R_TLS_LE, R_ADDROFF), so
929 // don't worry if Adddynrel returns false.
930 thearch.Adddynrel(target, ldr, syms, s, r, ri)
934 if rSym != 0 && ldr.SymType(rSym) == sym.SDYNIMPORT || r.Type() >= objabi.ElfRelocOffset {
935 if rSym != 0 && !ldr.AttrReachable(rSym) {
936 ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s", ldr.SymName(rSym))
938 if !thearch.Adddynrel(target, ldr, syms, s, r, ri) {
939 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))
945 func (state *dodataState) dynreloc(ctxt *Link) {
946 if ctxt.HeadType == objabi.Hwindows {
949 // -d suppresses dynamic loader format, so we may as well not
950 // compute these sections or mark their symbols as reachable.
955 for _, s := range ctxt.Textp {
958 for _, syms := range state.data {
959 for _, s := range syms {
968 func CodeblkPad(ctxt *Link, out *OutBuf, addr int64, size int64, pad []byte) {
969 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.Textp, addr, size, pad)
972 const blockSize = 1 << 20 // 1MB chunks written at a time.
974 // writeBlocks writes a specified chunk of symbols to the output buffer. It
975 // breaks the write up into ≥blockSize chunks to write them out, and schedules
976 // as many goroutines as necessary to accomplish this task. This call then
977 // blocks, waiting on the writes to complete. Note that we use the sem parameter
978 // to limit the number of concurrent writes taking place.
979 func writeBlocks(ctxt *Link, out *OutBuf, sem chan int, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
980 for i, s := range syms {
981 if ldr.SymValue(s) >= addr && !ldr.AttrSubSymbol(s) {
987 var wg sync.WaitGroup
988 max, lastAddr, written := int64(blockSize), addr+size, int64(0)
989 for addr < lastAddr {
990 // Find the last symbol we'd write.
992 for i, s := range syms {
993 if ldr.AttrSubSymbol(s) {
997 // If the next symbol's size would put us out of bounds on the total length,
999 end := ldr.SymValue(s) + ldr.SymSize(s)
1004 // We're gonna write this symbol.
1007 // If we cross over the max size, we've got enough symbols.
1013 // If we didn't find any symbols to write, we're done here.
1018 // Compute the length to write, including padding.
1019 // We need to write to the end address (lastAddr), or the next symbol's
1020 // start address, whichever comes first. If there is no more symbols,
1021 // just write to lastAddr. This ensures we don't leave holes between the
1022 // blocks or at the end.
1024 if idx+1 < len(syms) {
1025 // Find the next top-level symbol.
1026 // Skip over sub symbols so we won't split a container symbol
1029 for ldr.AttrSubSymbol(next) {
1033 length = ldr.SymValue(next) - addr
1035 if length == 0 || length > lastAddr-addr {
1036 length = lastAddr - addr
1039 // Start the block output operator.
1040 if o, err := out.View(uint64(out.Offset() + written)); err == nil {
1043 go func(o *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
1044 writeBlock(ctxt, o, ldr, syms, addr, size, pad)
1047 }(o, ldr, syms, addr, length, pad)
1048 } else { // output not mmaped, don't parallelize.
1049 writeBlock(ctxt, out, ldr, syms, addr, length, pad)
1052 // Prepare for the next loop.
1062 func writeBlock(ctxt *Link, out *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
1064 st := ctxt.makeRelocSymState()
1066 // This doesn't distinguish the memory size from the file
1067 // size, and it lays out the file based on Symbol.Value, which
1068 // is the virtual address. DWARF compression changes file sizes,
1069 // so dwarfcompress will fix this up later if necessary.
1070 eaddr := addr + size
1071 for _, s := range syms {
1072 if ldr.AttrSubSymbol(s) {
1075 val := ldr.SymValue(s)
1080 ldr.Errorf(s, "phase error: addr=%#x but val=%#x sym=%s type=%v sect=%v sect.addr=%#x", addr, val, ldr.SymName(s), ldr.SymType(s), ldr.SymSect(s).Name, ldr.SymSect(s).Vaddr)
1084 out.WriteStringPad("", int(val-addr), pad)
1087 P := out.WriteSym(ldr, s)
1089 if ldr.IsGeneratedSym(s) {
1090 f := ctxt.generatorSyms[s]
1093 addr += int64(len(P))
1094 siz := ldr.SymSize(s)
1096 out.WriteStringPad("", int(val+siz-addr), pad)
1099 if addr != val+siz {
1100 ldr.Errorf(s, "phase error: addr=%#x value+size=%#x", addr, val+siz)
1103 if val+siz >= eaddr {
1109 out.WriteStringPad("", int(eaddr-addr), pad)
1113 type writeFn func(*Link, *OutBuf, int64, int64)
1115 // writeParallel handles scheduling parallel execution of data write functions.
1116 func writeParallel(wg *sync.WaitGroup, fn writeFn, ctxt *Link, seek, vaddr, length uint64) {
1117 if out, err := ctxt.Out.View(seek); err != nil {
1118 ctxt.Out.SeekSet(int64(seek))
1119 fn(ctxt, ctxt.Out, int64(vaddr), int64(length))
1124 fn(ctxt, out, int64(vaddr), int64(length))
1129 func datblk(ctxt *Link, out *OutBuf, addr, size int64) {
1130 writeDatblkToOutBuf(ctxt, out, addr, size)
1133 // Used only on Wasm for now.
1134 func DatblkBytes(ctxt *Link, addr int64, size int64) []byte {
1135 buf := make([]byte, size)
1136 out := &OutBuf{heap: buf}
1137 writeDatblkToOutBuf(ctxt, out, addr, size)
1141 func writeDatblkToOutBuf(ctxt *Link, out *OutBuf, addr int64, size int64) {
1142 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.datap, addr, size, zeros[:])
1145 func dwarfblk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1146 // Concatenate the section symbol lists into a single list to pass
1149 // NB: ideally we would do a separate writeBlocks call for each
1150 // section, but this would run the risk of undoing any file offset
1151 // adjustments made during layout.
1153 for i := range dwarfp {
1154 n += len(dwarfp[i].syms)
1156 syms := make([]loader.Sym, 0, n)
1157 for i := range dwarfp {
1158 syms = append(syms, dwarfp[i].syms...)
1160 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, syms, addr, size, zeros[:])
1163 func pdatablk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1164 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, []loader.Sym{sehp.pdata}, addr, size, zeros[:])
1167 func xdatablk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1168 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, []loader.Sym{sehp.xdata}, addr, size, zeros[:])
1171 var covCounterDataStartOff, covCounterDataLen uint64
1176 strdata = make(map[string]string)
1180 func addstrdata1(ctxt *Link, arg string) {
1181 eq := strings.Index(arg, "=")
1182 dot := strings.LastIndex(arg[:eq+1], ".")
1183 if eq < 0 || dot < 0 {
1184 Exitf("-X flag requires argument of the form importpath.name=value")
1187 if ctxt.BuildMode == BuildModePlugin && pkg == "main" {
1188 pkg = *flagPluginPath
1190 pkg = objabi.PathToPrefix(pkg)
1191 name := pkg + arg[dot:eq]
1193 if _, ok := strdata[name]; !ok {
1194 strnames = append(strnames, name)
1196 strdata[name] = value
1199 // addstrdata sets the initial value of the string variable name to value.
1200 func addstrdata(arch *sys.Arch, l *loader.Loader, name, value string) {
1201 s := l.Lookup(name, 0)
1205 if goType := l.SymGoType(s); goType == 0 {
1207 } else if typeName := l.SymName(goType); typeName != "type:string" {
1208 Errorf(nil, "%s: cannot set with -X: not a var of type string (%s)", name, typeName)
1211 if !l.AttrReachable(s) {
1212 return // don't bother setting unreachable variable
1214 bld := l.MakeSymbolUpdater(s)
1215 if bld.Type() == sym.SBSS {
1216 bld.SetType(sym.SDATA)
1219 p := fmt.Sprintf("%s.str", name)
1220 sbld := l.CreateSymForUpdate(p, 0)
1221 sbld.Addstring(value)
1222 sbld.SetType(sym.SRODATA)
1224 // Don't reset the variable's size. String variable usually has size of
1225 // 2*PtrSize, but in ASAN build it can be larger due to red zone.
1226 // (See issue 56175.)
1227 bld.SetData(make([]byte, arch.PtrSize*2))
1228 bld.SetReadOnly(false)
1230 bld.SetAddrPlus(arch, 0, sbld.Sym(), 0)
1231 bld.SetUint(arch, int64(arch.PtrSize), uint64(len(value)))
1234 func (ctxt *Link) dostrdata() {
1235 for _, name := range strnames {
1236 addstrdata(ctxt.Arch, ctxt.loader, name, strdata[name])
1240 // addgostring adds str, as a Go string value, to s. symname is the name of the
1241 // symbol used to define the string data and must be unique per linked object.
1242 func addgostring(ctxt *Link, ldr *loader.Loader, s *loader.SymbolBuilder, symname, str string) {
1243 sdata := ldr.CreateSymForUpdate(symname, 0)
1244 if sdata.Type() != sym.Sxxx {
1245 ctxt.Errorf(s.Sym(), "duplicate symname in addgostring: %s", symname)
1247 sdata.SetLocal(true)
1248 sdata.SetType(sym.SRODATA)
1249 sdata.SetSize(int64(len(str)))
1250 sdata.SetData([]byte(str))
1251 s.AddAddr(ctxt.Arch, sdata.Sym())
1252 s.AddUint(ctxt.Arch, uint64(len(str)))
1255 func addinitarrdata(ctxt *Link, ldr *loader.Loader, s loader.Sym) {
1256 p := ldr.SymName(s) + ".ptr"
1257 sp := ldr.CreateSymForUpdate(p, 0)
1258 sp.SetType(sym.SINITARR)
1260 sp.SetDuplicateOK(true)
1261 sp.AddAddr(ctxt.Arch, s)
1264 // symalign returns the required alignment for the given symbol s.
1265 func symalign(ldr *loader.Loader, s loader.Sym) int32 {
1266 min := int32(thearch.Minalign)
1267 align := ldr.SymAlign(s)
1270 } else if align != 0 {
1273 align = int32(thearch.Maxalign)
1274 ssz := ldr.SymSize(s)
1275 for int64(align) > ssz && align > min {
1278 ldr.SetSymAlign(s, align)
1282 func aligndatsize(state *dodataState, datsize int64, s loader.Sym) int64 {
1283 return Rnd(datsize, int64(symalign(state.ctxt.loader, s)))
1286 const debugGCProg = false
1288 type GCProg struct {
1290 sym *loader.SymbolBuilder
1294 func (p *GCProg) Init(ctxt *Link, name string) {
1296 p.sym = ctxt.loader.CreateSymForUpdate(name, 0)
1297 p.w.Init(p.writeByte())
1299 fmt.Fprintf(os.Stderr, "ld: start GCProg %s\n", name)
1300 p.w.Debug(os.Stderr)
1304 func (p *GCProg) writeByte() func(x byte) {
1305 return func(x byte) {
1310 func (p *GCProg) End(size int64) {
1311 p.w.ZeroUntil(size / int64(p.ctxt.Arch.PtrSize))
1314 fmt.Fprintf(os.Stderr, "ld: end GCProg\n")
1318 func (p *GCProg) AddSym(s loader.Sym) {
1319 ldr := p.ctxt.loader
1320 typ := ldr.SymGoType(s)
1322 // Things without pointers should be in sym.SNOPTRDATA or sym.SNOPTRBSS;
1323 // everything we see should have pointers and should therefore have a type.
1325 switch ldr.SymName(s) {
1326 case "runtime.data", "runtime.edata", "runtime.bss", "runtime.ebss":
1327 // Ignore special symbols that are sometimes laid out
1328 // as real symbols. See comment about dyld on darwin in
1329 // the address function.
1332 p.ctxt.Errorf(p.sym.Sym(), "missing Go type information for global symbol %s: size %d", ldr.SymName(s), ldr.SymSize(s))
1336 ptrsize := int64(p.ctxt.Arch.PtrSize)
1337 typData := ldr.Data(typ)
1338 nptr := decodetypePtrdata(p.ctxt.Arch, typData) / ptrsize
1341 fmt.Fprintf(os.Stderr, "gcprog sym: %s at %d (ptr=%d+%d)\n", ldr.SymName(s), ldr.SymValue(s), ldr.SymValue(s)/ptrsize, nptr)
1344 sval := ldr.SymValue(s)
1345 if decodetypeUsegcprog(p.ctxt.Arch, typData) == 0 {
1346 // Copy pointers from mask into program.
1347 mask := decodetypeGcmask(p.ctxt, typ)
1348 for i := int64(0); i < nptr; i++ {
1349 if (mask[i/8]>>uint(i%8))&1 != 0 {
1350 p.w.Ptr(sval/ptrsize + i)
1357 prog := decodetypeGcprog(p.ctxt, typ)
1358 p.w.ZeroUntil(sval / ptrsize)
1359 p.w.Append(prog[4:], nptr)
1362 // cutoff is the maximum data section size permitted by the linker
1363 // (see issue #9862).
1364 const cutoff = 2e9 // 2 GB (or so; looks better in errors than 2^31)
1366 // check accumulated size of data sections
1367 func (state *dodataState) checkdatsize(symn sym.SymKind) {
1368 if state.datsize > cutoff {
1369 Errorf(nil, "too much data, last section %v (%d, over %v bytes)", symn, state.datsize, cutoff)
1373 func checkSectSize(sect *sym.Section) {
1374 // TODO: consider using 4 GB size limit for DWARF sections, and
1375 // make sure we generate unsigned offset in relocations and check
1377 if sect.Length > cutoff {
1378 Errorf(nil, "too much data in section %s (%d, over %v bytes)", sect.Name, sect.Length, cutoff)
1382 // fixZeroSizedSymbols gives a few special symbols with zero size some space.
1383 func fixZeroSizedSymbols(ctxt *Link) {
1384 // The values in moduledata are filled out by relocations
1385 // pointing to the addresses of these special symbols.
1386 // Typically these symbols have no size and are not laid
1387 // out with their matching section.
1389 // However on darwin, dyld will find the special symbol
1390 // in the first loaded module, even though it is local.
1392 // (An hypothesis, formed without looking in the dyld sources:
1393 // these special symbols have no size, so their address
1394 // matches a real symbol. The dynamic linker assumes we
1395 // want the normal symbol with the same address and finds
1396 // it in the other module.)
1398 // To work around this we lay out the symbls whose
1399 // addresses are vital for multi-module programs to work
1400 // as normal symbols, and give them a little size.
1402 // On AIX, as all DATA sections are merged together, ld might not put
1403 // these symbols at the beginning of their respective section if there
1404 // aren't real symbols, their alignment might not match the
1405 // first symbol alignment. Therefore, there are explicitly put at the
1406 // beginning of their section with the same alignment.
1407 if !(ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) && !(ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
1412 bss := ldr.CreateSymForUpdate("runtime.bss", 0)
1414 ldr.SetAttrSpecial(bss.Sym(), false)
1416 ebss := ldr.CreateSymForUpdate("runtime.ebss", 0)
1417 ldr.SetAttrSpecial(ebss.Sym(), false)
1419 data := ldr.CreateSymForUpdate("runtime.data", 0)
1421 ldr.SetAttrSpecial(data.Sym(), false)
1423 edata := ldr.CreateSymForUpdate("runtime.edata", 0)
1424 ldr.SetAttrSpecial(edata.Sym(), false)
1426 if ctxt.HeadType == objabi.Haix {
1427 // XCOFFTOC symbols are part of .data section.
1428 edata.SetType(sym.SXCOFFTOC)
1431 noptrbss := ldr.CreateSymForUpdate("runtime.noptrbss", 0)
1433 ldr.SetAttrSpecial(noptrbss.Sym(), false)
1435 enoptrbss := ldr.CreateSymForUpdate("runtime.enoptrbss", 0)
1436 ldr.SetAttrSpecial(enoptrbss.Sym(), false)
1438 noptrdata := ldr.CreateSymForUpdate("runtime.noptrdata", 0)
1439 noptrdata.SetSize(8)
1440 ldr.SetAttrSpecial(noptrdata.Sym(), false)
1442 enoptrdata := ldr.CreateSymForUpdate("runtime.enoptrdata", 0)
1443 ldr.SetAttrSpecial(enoptrdata.Sym(), false)
1445 types := ldr.CreateSymForUpdate("runtime.types", 0)
1446 types.SetType(sym.STYPE)
1448 ldr.SetAttrSpecial(types.Sym(), false)
1450 etypes := ldr.CreateSymForUpdate("runtime.etypes", 0)
1451 etypes.SetType(sym.SFUNCTAB)
1452 ldr.SetAttrSpecial(etypes.Sym(), false)
1454 if ctxt.HeadType == objabi.Haix {
1455 rodata := ldr.CreateSymForUpdate("runtime.rodata", 0)
1456 rodata.SetType(sym.SSTRING)
1458 ldr.SetAttrSpecial(rodata.Sym(), false)
1460 erodata := ldr.CreateSymForUpdate("runtime.erodata", 0)
1461 ldr.SetAttrSpecial(erodata.Sym(), false)
1465 // makeRelroForSharedLib creates a section of readonly data if necessary.
1466 func (state *dodataState) makeRelroForSharedLib(target *Link) {
1467 if !target.UseRelro() {
1471 // "read only" data with relocations needs to go in its own section
1472 // when building a shared library. We do this by boosting objects of
1473 // type SXXX with relocations to type SXXXRELRO.
1474 ldr := target.loader
1475 for _, symnro := range sym.ReadOnly {
1476 symnrelro := sym.RelROMap[symnro]
1478 ro := []loader.Sym{}
1479 relro := state.data[symnrelro]
1481 for _, s := range state.data[symnro] {
1482 relocs := ldr.Relocs(s)
1483 isRelro := relocs.Count() > 0
1484 switch state.symType(s) {
1485 case sym.STYPE, sym.STYPERELRO, sym.SGOFUNCRELRO:
1486 // Symbols are not sorted yet, so it is possible
1487 // that an Outer symbol has been changed to a
1488 // relro Type before it reaches here.
1491 if ldr.SymName(s) == "runtime.etypes" {
1492 // runtime.etypes must be at the end of
1497 // The only SGOFUNC symbols that contain relocations are .stkobj,
1498 // and their relocations are of type objabi.R_ADDROFF,
1499 // which always get resolved during linking.
1503 state.setSymType(s, symnrelro)
1504 if outer := ldr.OuterSym(s); outer != 0 {
1505 state.setSymType(outer, symnrelro)
1507 relro = append(relro, s)
1513 // Check that we haven't made two symbols with the same .Outer into
1514 // different types (because references two symbols with non-nil Outer
1515 // become references to the outer symbol + offset it's vital that the
1516 // symbol and the outer end up in the same section).
1517 for _, s := range relro {
1518 if outer := ldr.OuterSym(s); outer != 0 {
1519 st := state.symType(s)
1520 ost := state.symType(outer)
1522 state.ctxt.Errorf(s, "inconsistent types for symbol and its Outer %s (%v != %v)",
1523 ldr.SymName(outer), st, ost)
1528 state.data[symnro] = ro
1529 state.data[symnrelro] = relro
1533 // dodataState holds bits of state information needed by dodata() and the
1534 // various helpers it calls. The lifetime of these items should not extend
1535 // past the end of dodata().
1536 type dodataState struct {
1539 // Data symbols bucketed by type.
1540 data [sym.SXREF][]loader.Sym
1541 // Max alignment for each flavor of data symbol.
1542 dataMaxAlign [sym.SXREF]int32
1543 // Overridden sym type
1544 symGroupType []sym.SymKind
1545 // Current data size so far.
1549 // A note on symType/setSymType below:
1551 // In the legacy linker, the types of symbols (notably data symbols) are
1552 // changed during the symtab() phase so as to insure that similar symbols
1553 // are bucketed together, then their types are changed back again during
1554 // dodata. Symbol to section assignment also plays tricks along these lines
1555 // in the case where a relro segment is needed.
1557 // The value returned from setType() below reflects the effects of
1558 // any overrides made by symtab and/or dodata.
1560 // symType returns the (possibly overridden) type of 's'.
1561 func (state *dodataState) symType(s loader.Sym) sym.SymKind {
1562 if int(s) < len(state.symGroupType) {
1563 if override := state.symGroupType[s]; override != 0 {
1567 return state.ctxt.loader.SymType(s)
1570 // setSymType sets a new override type for 's'.
1571 func (state *dodataState) setSymType(s loader.Sym, kind sym.SymKind) {
1575 if int(s) < len(state.symGroupType) {
1576 state.symGroupType[s] = kind
1578 su := state.ctxt.loader.MakeSymbolUpdater(s)
1583 func (ctxt *Link) dodata(symGroupType []sym.SymKind) {
1585 // Give zeros sized symbols space if necessary.
1586 fixZeroSizedSymbols(ctxt)
1588 // Collect data symbols by type into data.
1589 state := dodataState{ctxt: ctxt, symGroupType: symGroupType}
1591 for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
1592 if !ldr.AttrReachable(s) || ldr.AttrSpecial(s) || ldr.AttrSubSymbol(s) ||
1593 !ldr.TopLevelSym(s) {
1597 st := state.symType(s)
1599 if st <= sym.STEXT || st >= sym.SXREF {
1602 state.data[st] = append(state.data[st], s)
1604 // Similarly with checking the onlist attr.
1605 if ldr.AttrOnList(s) {
1606 log.Fatalf("symbol %s listed multiple times", ldr.SymName(s))
1608 ldr.SetAttrOnList(s, true)
1611 // Now that we have the data symbols, but before we start
1612 // to assign addresses, record all the necessary
1613 // dynamic relocations. These will grow the relocation
1614 // symbol, which is itself data.
1616 // On darwin, we need the symbol table numbers for dynreloc.
1617 if ctxt.HeadType == objabi.Hdarwin {
1620 state.dynreloc(ctxt)
1622 // Move any RO data with relocations to a separate section.
1623 state.makeRelroForSharedLib(ctxt)
1625 // Set alignment for the symbol with the largest known index,
1626 // so as to trigger allocation of the loader's internal
1627 // alignment array. This will avoid data races in the parallel
1629 lastSym := loader.Sym(ldr.NSym() - 1)
1630 ldr.SetSymAlign(lastSym, ldr.SymAlign(lastSym))
1633 var wg sync.WaitGroup
1634 for symn := range state.data {
1635 symn := sym.SymKind(symn)
1638 state.data[symn], state.dataMaxAlign[symn] = state.dodataSect(ctxt, symn, state.data[symn])
1645 // Make .rela and .rela.plt contiguous, the ELF ABI requires this
1646 // and Solaris actually cares.
1647 syms := state.data[sym.SELFROSECT]
1648 reli, plti := -1, -1
1649 for i, s := range syms {
1650 switch ldr.SymName(s) {
1651 case ".rel.plt", ".rela.plt":
1653 case ".rel", ".rela":
1657 if reli >= 0 && plti >= 0 && plti != reli+1 {
1658 var first, second int
1660 first, second = reli, plti
1662 first, second = plti, reli
1664 rel, plt := syms[reli], syms[plti]
1665 copy(syms[first+2:], syms[first+1:second])
1669 // Make sure alignment doesn't introduce a gap.
1670 // Setting the alignment explicitly prevents
1671 // symalign from basing it on the size and
1672 // getting it wrong.
1673 ldr.SetSymAlign(rel, int32(ctxt.Arch.RegSize))
1674 ldr.SetSymAlign(plt, int32(ctxt.Arch.RegSize))
1676 state.data[sym.SELFROSECT] = syms
1679 if ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal {
1680 // These symbols must have the same alignment as their section.
1681 // Otherwise, ld might change the layout of Go sections.
1682 ldr.SetSymAlign(ldr.Lookup("runtime.data", 0), state.dataMaxAlign[sym.SDATA])
1683 ldr.SetSymAlign(ldr.Lookup("runtime.bss", 0), state.dataMaxAlign[sym.SBSS])
1686 // Create *sym.Section objects and assign symbols to sections for
1687 // data/rodata (and related) symbols.
1688 state.allocateDataSections(ctxt)
1690 state.allocateSEHSections(ctxt)
1692 // Create *sym.Section objects and assign symbols to sections for
1694 state.allocateDwarfSections(ctxt)
1696 /* number the sections */
1699 for _, sect := range Segtext.Sections {
1703 for _, sect := range Segrodata.Sections {
1707 for _, sect := range Segrelrodata.Sections {
1711 for _, sect := range Segdata.Sections {
1715 for _, sect := range Segdwarf.Sections {
1719 for _, sect := range Segpdata.Sections {
1723 for _, sect := range Segxdata.Sections {
1729 // allocateDataSectionForSym creates a new sym.Section into which a
1730 // single symbol will be placed. Here "seg" is the segment into which
1731 // the section will go, "s" is the symbol to be placed into the new
1732 // section, and "rwx" contains permissions for the section.
1733 func (state *dodataState) allocateDataSectionForSym(seg *sym.Segment, s loader.Sym, rwx int) *sym.Section {
1734 ldr := state.ctxt.loader
1735 sname := ldr.SymName(s)
1736 if strings.HasPrefix(sname, "go:") {
1737 sname = ".go." + sname[len("go:"):]
1739 sect := addsection(ldr, state.ctxt.Arch, seg, sname, rwx)
1740 sect.Align = symalign(ldr, s)
1741 state.datsize = Rnd(state.datsize, int64(sect.Align))
1742 sect.Vaddr = uint64(state.datsize)
1746 // allocateNamedDataSection creates a new sym.Section for a category
1747 // of data symbols. Here "seg" is the segment into which the section
1748 // will go, "sName" is the name to give to the section, "types" is a
1749 // range of symbol types to be put into the section, and "rwx"
1750 // contains permissions for the section.
1751 func (state *dodataState) allocateNamedDataSection(seg *sym.Segment, sName string, types []sym.SymKind, rwx int) *sym.Section {
1752 sect := addsection(state.ctxt.loader, state.ctxt.Arch, seg, sName, rwx)
1753 if len(types) == 0 {
1755 } else if len(types) == 1 {
1756 sect.Align = state.dataMaxAlign[types[0]]
1758 for _, symn := range types {
1759 align := state.dataMaxAlign[symn]
1760 if sect.Align < align {
1765 state.datsize = Rnd(state.datsize, int64(sect.Align))
1766 sect.Vaddr = uint64(state.datsize)
1770 // assignDsymsToSection assigns a collection of data symbols to a
1771 // newly created section. "sect" is the section into which to place
1772 // the symbols, "syms" holds the list of symbols to assign,
1773 // "forceType" (if non-zero) contains a new sym type to apply to each
1774 // sym during the assignment, and "aligner" is a hook to call to
1775 // handle alignment during the assignment process.
1776 func (state *dodataState) assignDsymsToSection(sect *sym.Section, syms []loader.Sym, forceType sym.SymKind, aligner func(state *dodataState, datsize int64, s loader.Sym) int64) {
1777 ldr := state.ctxt.loader
1778 for _, s := range syms {
1779 state.datsize = aligner(state, state.datsize, s)
1780 ldr.SetSymSect(s, sect)
1781 if forceType != sym.Sxxx {
1782 state.setSymType(s, forceType)
1784 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1785 state.datsize += ldr.SymSize(s)
1787 sect.Length = uint64(state.datsize) - sect.Vaddr
1790 func (state *dodataState) assignToSection(sect *sym.Section, symn sym.SymKind, forceType sym.SymKind) {
1791 state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1792 state.checkdatsize(symn)
1795 // allocateSingleSymSections walks through the bucketed data symbols
1796 // with type 'symn', creates a new section for each sym, and assigns
1797 // the sym to a newly created section. Section name is set from the
1798 // symbol name. "Seg" is the segment into which to place the new
1799 // section, "forceType" is the new sym.SymKind to assign to the symbol
1800 // within the section, and "rwx" holds section permissions.
1801 func (state *dodataState) allocateSingleSymSections(seg *sym.Segment, symn sym.SymKind, forceType sym.SymKind, rwx int) {
1802 ldr := state.ctxt.loader
1803 for _, s := range state.data[symn] {
1804 sect := state.allocateDataSectionForSym(seg, s, rwx)
1805 ldr.SetSymSect(s, sect)
1806 state.setSymType(s, forceType)
1807 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1808 state.datsize += ldr.SymSize(s)
1809 sect.Length = uint64(state.datsize) - sect.Vaddr
1811 state.checkdatsize(symn)
1814 // allocateNamedSectionAndAssignSyms creates a new section with the
1815 // specified name, then walks through the bucketed data symbols with
1816 // type 'symn' and assigns each of them to this new section. "Seg" is
1817 // the segment into which to place the new section, "secName" is the
1818 // name to give to the new section, "forceType" (if non-zero) contains
1819 // a new sym type to apply to each sym during the assignment, and
1820 // "rwx" holds section permissions.
1821 func (state *dodataState) allocateNamedSectionAndAssignSyms(seg *sym.Segment, secName string, symn sym.SymKind, forceType sym.SymKind, rwx int) *sym.Section {
1823 sect := state.allocateNamedDataSection(seg, secName, []sym.SymKind{symn}, rwx)
1824 state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1828 // allocateDataSections allocates sym.Section objects for data/rodata
1829 // (and related) symbols, and then assigns symbols to those sections.
1830 func (state *dodataState) allocateDataSections(ctxt *Link) {
1831 // Allocate sections.
1832 // Data is processed before segtext, because we need
1833 // to see all symbols in the .data and .bss sections in order
1834 // to generate garbage collection information.
1836 // Writable data sections that do not need any specialized handling.
1837 writable := []sym.SymKind{
1844 for _, symn := range writable {
1845 state.allocateSingleSymSections(&Segdata, symn, sym.SDATA, 06)
1850 if len(state.data[sym.SELFGOT]) > 0 {
1851 state.allocateNamedSectionAndAssignSyms(&Segdata, ".got", sym.SELFGOT, sym.SDATA, 06)
1854 /* pointer-free data */
1855 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrdata", sym.SNOPTRDATA, sym.SDATA, 06)
1856 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrdata", 0), sect)
1857 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrdata", 0), sect)
1859 hasinitarr := ctxt.linkShared
1861 /* shared library initializer */
1862 switch ctxt.BuildMode {
1863 case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePlugin:
1867 if ctxt.HeadType == objabi.Haix {
1868 if len(state.data[sym.SINITARR]) > 0 {
1869 Errorf(nil, "XCOFF format doesn't allow .init_array section")
1873 if hasinitarr && len(state.data[sym.SINITARR]) > 0 {
1874 state.allocateNamedSectionAndAssignSyms(&Segdata, ".init_array", sym.SINITARR, sym.Sxxx, 06)
1878 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".data", sym.SDATA, sym.SDATA, 06)
1879 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.data", 0), sect)
1880 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.edata", 0), sect)
1881 dataGcEnd := state.datsize - int64(sect.Vaddr)
1883 // On AIX, TOC entries must be the last of .data
1884 // These aren't part of gc as they won't change during the runtime.
1885 state.assignToSection(sect, sym.SXCOFFTOC, sym.SDATA)
1886 state.checkdatsize(sym.SDATA)
1887 sect.Length = uint64(state.datsize) - sect.Vaddr
1890 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".bss", sym.SBSS, sym.Sxxx, 06)
1891 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.bss", 0), sect)
1892 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ebss", 0), sect)
1893 bssGcEnd := state.datsize - int64(sect.Vaddr)
1895 // Emit gcdata for bss symbols now that symbol values have been assigned.
1896 gcsToEmit := []struct {
1901 {"runtime.gcdata", sym.SDATA, dataGcEnd},
1902 {"runtime.gcbss", sym.SBSS, bssGcEnd},
1904 for _, g := range gcsToEmit {
1906 gc.Init(ctxt, g.symName)
1907 for _, s := range state.data[g.symKind] {
1913 /* pointer-free bss */
1914 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrbss", sym.SNOPTRBSS, sym.Sxxx, 06)
1915 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrbss", 0), sect)
1916 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrbss", 0), sect)
1917 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.end", 0), sect)
1919 // Code coverage counters are assigned to the .noptrbss section.
1920 // We assign them in a separate pass so that they stay aggregated
1921 // together in a single blob (coverage runtime depends on this).
1922 covCounterDataStartOff = sect.Length
1923 state.assignToSection(sect, sym.SCOVERAGE_COUNTER, sym.SNOPTRBSS)
1924 covCounterDataLen = sect.Length - covCounterDataStartOff
1925 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.covctrs", 0), sect)
1926 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ecovctrs", 0), sect)
1928 // Coverage instrumentation counters for libfuzzer.
1929 if len(state.data[sym.SLIBFUZZER_8BIT_COUNTER]) > 0 {
1930 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".go.fuzzcntrs", sym.SLIBFUZZER_8BIT_COUNTER, sym.Sxxx, 06)
1931 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.__start___sancov_cntrs", 0), sect)
1932 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.__stop___sancov_cntrs", 0), sect)
1933 ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._counters", 0), sect)
1934 ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._ecounters", 0), sect)
1937 if len(state.data[sym.STLSBSS]) > 0 {
1938 var sect *sym.Section
1939 // FIXME: not clear why it is sometimes necessary to suppress .tbss section creation.
1940 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && (ctxt.LinkMode == LinkExternal || !*FlagD) {
1941 sect = addsection(ldr, ctxt.Arch, &Segdata, ".tbss", 06)
1942 sect.Align = int32(ctxt.Arch.PtrSize)
1943 // FIXME: why does this need to be set to zero?
1948 for _, s := range state.data[sym.STLSBSS] {
1949 state.datsize = aligndatsize(state, state.datsize, s)
1951 ldr.SetSymSect(s, sect)
1953 ldr.SetSymValue(s, state.datsize)
1954 state.datsize += ldr.SymSize(s)
1956 state.checkdatsize(sym.STLSBSS)
1959 sect.Length = uint64(state.datsize)
1964 * We finished data, begin read-only data.
1965 * Not all systems support a separate read-only non-executable data section.
1966 * ELF and Windows PE systems do.
1967 * OS X and Plan 9 do not.
1968 * And if we're using external linking mode, the point is moot,
1969 * since it's not our decision; that code expects the sections in
1972 var segro *sym.Segment
1973 if ctxt.IsELF && ctxt.LinkMode == LinkInternal {
1975 } else if ctxt.HeadType == objabi.Hwindows {
1983 /* read-only executable ELF, Mach-O sections */
1984 if len(state.data[sym.STEXT]) != 0 {
1985 culprit := ldr.SymName(state.data[sym.STEXT][0])
1986 Errorf(nil, "dodata found an sym.STEXT symbol: %s", culprit)
1988 state.allocateSingleSymSections(&Segtext, sym.SELFRXSECT, sym.SRODATA, 05)
1989 state.allocateSingleSymSections(&Segtext, sym.SMACHOPLT, sym.SRODATA, 05)
1991 /* read-only data */
1992 sect = state.allocateNamedDataSection(segro, ".rodata", sym.ReadOnly, 04)
1993 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.rodata", 0), sect)
1994 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.erodata", 0), sect)
1995 if !ctxt.UseRelro() {
1996 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
1997 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
1999 for _, symn := range sym.ReadOnly {
2000 symnStartValue := state.datsize
2001 if len(state.data[symn]) != 0 {
2002 symnStartValue = aligndatsize(state, symnStartValue, state.data[symn][0])
2004 state.assignToSection(sect, symn, sym.SRODATA)
2005 setCarrierSize(symn, state.datsize-symnStartValue)
2006 if ctxt.HeadType == objabi.Haix {
2007 // Read-only symbols might be wrapped inside their outer
2009 // XCOFF symbol table needs to know the size of
2010 // these outer symbols.
2011 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
2015 /* read-only ELF, Mach-O sections */
2016 state.allocateSingleSymSections(segro, sym.SELFROSECT, sym.SRODATA, 04)
2018 // There is some data that are conceptually read-only but are written to by
2019 // relocations. On GNU systems, we can arrange for the dynamic linker to
2020 // mprotect sections after relocations are applied by giving them write
2021 // permissions in the object file and calling them ".data.rel.ro.FOO". We
2022 // divide the .rodata section between actual .rodata and .data.rel.ro.rodata,
2023 // but for the other sections that this applies to, we just write a read-only
2024 // .FOO section or a read-write .data.rel.ro.FOO section depending on the
2026 // TODO(mwhudson): It would make sense to do this more widely, but it makes
2027 // the system linker segfault on darwin.
2028 const relroPerm = 06
2029 const fallbackPerm = 04
2030 relroSecPerm := fallbackPerm
2031 genrelrosecname := func(suffix string) string {
2039 if ctxt.UseRelro() {
2040 segrelro := &Segrelrodata
2041 if ctxt.LinkMode == LinkExternal && !ctxt.IsAIX() && !ctxt.IsDarwin() {
2042 // Using a separate segment with an external
2043 // linker results in some programs moving
2044 // their data sections unexpectedly, which
2045 // corrupts the moduledata. So we use the
2046 // rodata segment and let the external linker
2047 // sort out a rel.ro segment.
2050 // Reset datsize for new segment.
2054 if !ctxt.IsDarwin() { // We don't need the special names on darwin.
2055 genrelrosecname = func(suffix string) string {
2056 return ".data.rel.ro" + suffix
2060 relroReadOnly := []sym.SymKind{}
2061 for _, symnro := range sym.ReadOnly {
2062 symn := sym.RelROMap[symnro]
2063 relroReadOnly = append(relroReadOnly, symn)
2066 relroSecPerm = relroPerm
2068 /* data only written by relocations */
2069 sect = state.allocateNamedDataSection(segrelro, genrelrosecname(""), relroReadOnly, relroSecPerm)
2071 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
2072 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
2074 for i, symnro := range sym.ReadOnly {
2075 if i == 0 && symnro == sym.STYPE && ctxt.HeadType != objabi.Haix {
2076 // Skip forward so that no type
2077 // reference uses a zero offset.
2078 // This is unlikely but possible in small
2079 // programs with no other read-only data.
2083 symn := sym.RelROMap[symnro]
2084 symnStartValue := state.datsize
2085 if len(state.data[symn]) != 0 {
2086 symnStartValue = aligndatsize(state, symnStartValue, state.data[symn][0])
2089 for _, s := range state.data[symn] {
2090 outer := ldr.OuterSym(s)
2091 if s != 0 && ldr.SymSect(outer) != nil && ldr.SymSect(outer) != sect {
2092 ctxt.Errorf(s, "s.Outer (%s) in different section from s, %s != %s", ldr.SymName(outer), ldr.SymSect(outer).Name, sect.Name)
2095 state.assignToSection(sect, symn, sym.SRODATA)
2096 setCarrierSize(symn, state.datsize-symnStartValue)
2097 if ctxt.HeadType == objabi.Haix {
2098 // Read-only symbols might be wrapped inside their outer
2100 // XCOFF symbol table needs to know the size of
2101 // these outer symbols.
2102 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
2106 sect.Length = uint64(state.datsize) - sect.Vaddr
2110 sect = state.allocateNamedDataSection(seg, genrelrosecname(".typelink"), []sym.SymKind{sym.STYPELINK}, relroSecPerm)
2112 typelink := ldr.CreateSymForUpdate("runtime.typelink", 0)
2113 ldr.SetSymSect(typelink.Sym(), sect)
2114 typelink.SetType(sym.SRODATA)
2115 state.datsize += typelink.Size()
2116 state.checkdatsize(sym.STYPELINK)
2117 sect.Length = uint64(state.datsize) - sect.Vaddr
2120 sect = state.allocateNamedDataSection(seg, genrelrosecname(".itablink"), []sym.SymKind{sym.SITABLINK}, relroSecPerm)
2122 itablink := ldr.CreateSymForUpdate("runtime.itablink", 0)
2123 ldr.SetSymSect(itablink.Sym(), sect)
2124 itablink.SetType(sym.SRODATA)
2125 state.datsize += itablink.Size()
2126 state.checkdatsize(sym.SITABLINK)
2127 sect.Length = uint64(state.datsize) - sect.Vaddr
2130 sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gosymtab"), sym.SSYMTAB, sym.SRODATA, relroSecPerm)
2131 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.symtab", 0), sect)
2132 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.esymtab", 0), sect)
2135 sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gopclntab"), sym.SPCLNTAB, sym.SRODATA, relroSecPerm)
2136 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0), sect)
2137 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pcheader", 0), sect)
2138 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.funcnametab", 0), sect)
2139 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.cutab", 0), sect)
2140 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.filetab", 0), sect)
2141 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pctab", 0), sect)
2142 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.functab", 0), sect)
2143 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.epclntab", 0), sect)
2144 setCarrierSize(sym.SPCLNTAB, int64(sect.Length))
2145 if ctxt.HeadType == objabi.Haix {
2146 xcoffUpdateOuterSize(ctxt, int64(sect.Length), sym.SPCLNTAB)
2149 // 6g uses 4-byte relocation offsets, so the entire segment must fit in 32 bits.
2150 if state.datsize != int64(uint32(state.datsize)) {
2151 Errorf(nil, "read-only data segment too large: %d", state.datsize)
2155 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
2156 siz += len(state.data[symn])
2158 ctxt.datap = make([]loader.Sym, 0, siz)
2159 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
2160 ctxt.datap = append(ctxt.datap, state.data[symn]...)
2164 // allocateDwarfSections allocates sym.Section objects for DWARF
2165 // symbols, and assigns symbols to sections.
2166 func (state *dodataState) allocateDwarfSections(ctxt *Link) {
2168 alignOne := func(state *dodataState, datsize int64, s loader.Sym) int64 { return datsize }
2171 for i := 0; i < len(dwarfp); i++ {
2172 // First the section symbol.
2173 s := dwarfp[i].secSym()
2174 sect := state.allocateNamedDataSection(&Segdwarf, ldr.SymName(s), []sym.SymKind{}, 04)
2175 ldr.SetSymSect(s, sect)
2176 sect.Sym = sym.LoaderSym(s)
2177 curType := ldr.SymType(s)
2178 state.setSymType(s, sym.SRODATA)
2179 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
2180 state.datsize += ldr.SymSize(s)
2182 // Then any sub-symbols for the section symbol.
2183 subSyms := dwarfp[i].subSyms()
2184 state.assignDsymsToSection(sect, subSyms, sym.SRODATA, alignOne)
2186 for j := 0; j < len(subSyms); j++ {
2188 if ctxt.HeadType == objabi.Haix && curType == sym.SDWARFLOC {
2189 // Update the size of .debug_loc for this symbol's
2191 addDwsectCUSize(".debug_loc", ldr.SymPkg(s), uint64(ldr.SymSize(s)))
2194 sect.Length = uint64(state.datsize) - sect.Vaddr
2199 // allocateSEHSections allocate a sym.Section object for SEH
2200 // symbols, and assigns symbols to sections.
2201 func (state *dodataState) allocateSEHSections(ctxt *Link) {
2203 sect := state.allocateDataSectionForSym(&Segpdata, sehp.pdata, 04)
2204 state.assignDsymsToSection(sect, []loader.Sym{sehp.pdata}, sym.SRODATA, aligndatsize)
2205 state.checkdatsize(sym.SSEHSECT)
2208 sect := state.allocateNamedDataSection(&Segxdata, ".xdata", []sym.SymKind{}, 04)
2209 state.assignDsymsToSection(sect, []loader.Sym{sehp.xdata}, sym.SRODATA, aligndatsize)
2210 state.checkdatsize(sym.SSEHSECT)
2214 type symNameSize struct {
2221 func (state *dodataState) dodataSect(ctxt *Link, symn sym.SymKind, syms []loader.Sym) (result []loader.Sym, maxAlign int32) {
2222 var head, tail, zerobase loader.Sym
2224 sl := make([]symNameSize, len(syms))
2226 // For ppc64, we want to interleave the .got and .toc sections
2227 // from input files. Both are type sym.SELFGOT, so in that case
2228 // we skip size comparison and do the name comparison instead
2229 // (conveniently, .got sorts before .toc).
2230 checkSize := symn != sym.SELFGOT
2232 for k, s := range syms {
2233 ss := ldr.SymSize(s)
2234 sl[k] = symNameSize{sz: ss, sym: s}
2236 sl[k].name = ldr.SymName(s)
2238 ds := int64(len(ldr.Data(s)))
2241 ctxt.Errorf(s, "initialize bounds (%d < %d)", ss, ds)
2243 ctxt.Errorf(s, "negative size (%d bytes)", ss)
2245 ctxt.Errorf(s, "symbol too large (%d bytes)", ss)
2248 // If the usually-special section-marker symbols are being laid
2249 // out as regular symbols, put them either at the beginning or
2250 // end of their section.
2251 if (ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) || (ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
2252 switch ldr.SymName(s) {
2253 case "runtime.text", "runtime.bss", "runtime.data", "runtime.types", "runtime.rodata",
2254 "runtime.noptrdata", "runtime.noptrbss":
2257 case "runtime.etext", "runtime.ebss", "runtime.edata", "runtime.etypes", "runtime.erodata",
2258 "runtime.enoptrdata", "runtime.enoptrbss":
2264 zerobase = ldr.Lookup("runtime.zerobase", 0)
2266 // Perform the sort.
2267 if symn != sym.SPCLNTAB {
2268 sort.Slice(sl, func(i, j int) bool {
2269 si, sj := sl[i].sym, sl[j].sym
2270 isz, jsz := sl[i].sz, sl[j].sz
2272 case si == head, sj == tail:
2274 case sj == head, si == tail:
2276 // put zerobase right after all the zero-sized symbols,
2277 // so zero-sized symbols have the same address as zerobase.
2278 case si == zerobase:
2279 return jsz != 0 // zerobase < nonzero-sized
2280 case sj == zerobase:
2281 return isz == 0 // 0-sized < zerobase
2291 return iname < jname
2297 // PCLNTAB was built internally, and already has the proper order.
2300 // Set alignment, construct result
2304 if s != head && s != tail {
2305 align := symalign(ldr, s)
2306 if maxAlign < align {
2310 syms = append(syms, s)
2313 return syms, maxAlign
2316 // Add buildid to beginning of text segment, on non-ELF systems.
2317 // Non-ELF binary formats are not always flexible enough to
2318 // give us a place to put the Go build ID. On those systems, we put it
2319 // at the very beginning of the text segment.
2320 // This “header” is read by cmd/go.
2321 func (ctxt *Link) textbuildid() {
2322 if ctxt.IsELF || *flagBuildid == "" {
2327 s := ldr.CreateSymForUpdate("go:buildid", 0)
2328 // The \xff is invalid UTF-8, meant to make it less likely
2329 // to find one of these accidentally.
2330 data := "\xff Go build ID: " + strconv.Quote(*flagBuildid) + "\n \xff"
2331 s.SetType(sym.STEXT)
2332 s.SetData([]byte(data))
2333 s.SetSize(int64(len(data)))
2335 ctxt.Textp = append(ctxt.Textp, 0)
2336 copy(ctxt.Textp[1:], ctxt.Textp)
2337 ctxt.Textp[0] = s.Sym()
2340 func (ctxt *Link) buildinfo() {
2341 // Write the buildinfo symbol, which go version looks for.
2342 // The code reading this data is in package debug/buildinfo.
2344 s := ldr.CreateSymForUpdate("go:buildinfo", 0)
2345 s.SetType(sym.SBUILDINFO)
2347 // The \xff is invalid UTF-8, meant to make it less likely
2348 // to find one of these accidentally.
2349 const prefix = "\xff Go buildinf:" // 14 bytes, plus 2 data bytes filled in below
2350 data := make([]byte, 32)
2352 data[len(prefix)] = byte(ctxt.Arch.PtrSize)
2353 data[len(prefix)+1] = 0
2354 if ctxt.Arch.ByteOrder == binary.BigEndian {
2355 data[len(prefix)+1] = 1
2357 data[len(prefix)+1] |= 2 // signals new pointer-free format
2358 data = appendString(data, strdata["runtime.buildVersion"])
2359 data = appendString(data, strdata["runtime.modinfo"])
2360 // MacOS linker gets very upset if the size os not a multiple of alignment.
2361 for len(data)%16 != 0 {
2362 data = append(data, 0)
2365 s.SetSize(int64(len(data)))
2367 // Add reference to go:buildinfo from the rodata section,
2368 // so that external linking with -Wl,--gc-sections does not
2369 // delete the build info.
2370 sr := ldr.CreateSymForUpdate("go:buildinfo.ref", 0)
2371 sr.SetType(sym.SRODATA)
2372 sr.SetAlign(int32(ctxt.Arch.PtrSize))
2373 sr.AddAddr(ctxt.Arch, s.Sym())
2376 // appendString appends s to data, prefixed by its varint-encoded length.
2377 func appendString(data []byte, s string) []byte {
2378 var v [binary.MaxVarintLen64]byte
2379 n := binary.PutUvarint(v[:], uint64(len(s)))
2380 data = append(data, v[:n]...)
2381 data = append(data, s...)
2385 // assign addresses to text
2386 func (ctxt *Link) textaddress() {
2387 addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2389 // Assign PCs in text segment.
2390 // Could parallelize, by assigning to text
2391 // and then letting threads copy down, but probably not worth it.
2392 sect := Segtext.Sections[0]
2394 sect.Align = int32(Funcalign)
2398 text := ctxt.xdefine("runtime.text", sym.STEXT, 0)
2399 etext := ctxt.xdefine("runtime.etext", sym.STEXT, 0)
2400 ldr.SetSymSect(text, sect)
2401 if ctxt.IsAIX() && ctxt.IsExternal() {
2402 // Setting runtime.text has a real symbol prevents ld to
2403 // change its base address resulting in wrong offsets for
2405 u := ldr.MakeSymbolUpdater(text)
2406 u.SetAlign(sect.Align)
2410 if (ctxt.DynlinkingGo() && ctxt.IsDarwin()) || (ctxt.IsAIX() && ctxt.IsExternal()) {
2411 ldr.SetSymSect(etext, sect)
2412 ctxt.Textp = append(ctxt.Textp, etext, 0)
2413 copy(ctxt.Textp[1:], ctxt.Textp)
2414 ctxt.Textp[0] = text
2417 start := uint64(Rnd(*FlagTextAddr, int64(Funcalign)))
2422 limit := thearch.TrampLimit
2424 limit = 1 << 63 // unlimited
2426 if *FlagDebugTextSize != 0 {
2427 limit = uint64(*FlagDebugTextSize)
2429 if *FlagDebugTramp > 1 {
2430 limit = 1 // debug mode, force generating trampolines for everything
2433 if ctxt.IsAIX() && ctxt.IsExternal() {
2434 // On AIX, normally we won't generate direct calls to external symbols,
2435 // except in one test, cmd/go/testdata/script/link_syso_issue33139.txt.
2436 // That test doesn't make much sense, and I'm not sure it ever works.
2437 // Just generate trampoline for now (which will turn a direct call to
2438 // an indirect call, which at least builds).
2442 // First pass: assign addresses assuming the program is small and will
2443 // not require trampoline generation.
2445 for _, s := range ctxt.Textp {
2446 sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
2447 if va-start >= limit {
2453 // Second pass: only if it is too big, insert trampolines for too-far
2454 // jumps and targets with unknown addresses.
2457 for _, s := range ctxt.Textp {
2459 resetAddress(ctxt, s)
2466 for i, s := range ctxt.Textp {
2467 // When we find the first symbol in a package, perform a
2468 // single iteration that assigns temporary addresses to all
2469 // of the text in the same package, using the maximum possible
2470 // number of trampolines. This allows for better decisions to
2471 // be made regarding reachability and the need for trampolines.
2472 if symPkg := ldr.SymPkg(s); symPkg != "" && curPkg != symPkg {
2475 for j := i; j < len(ctxt.Textp); j++ {
2476 curSym := ctxt.Textp[j]
2477 if symPkg := ldr.SymPkg(curSym); symPkg == "" || curPkg != symPkg {
2480 // We do not pass big to assignAddress here, as this
2481 // can result in side effects such as section splitting.
2482 sect, n, vaTmp = assignAddress(ctxt, sect, n, curSym, vaTmp, false, false)
2483 vaTmp += maxSizeTrampolines(ctxt, ldr, curSym, false)
2487 // Reset address for current symbol.
2489 resetAddress(ctxt, s)
2492 // Assign actual address for current symbol.
2493 sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
2495 // Resolve jumps, adding trampolines if they are needed.
2498 // lay down trampolines after each function
2499 for ; ntramps < len(ctxt.tramps); ntramps++ {
2500 tramp := ctxt.tramps[ntramps]
2501 if ctxt.IsAIX() && strings.HasPrefix(ldr.SymName(tramp), "runtime.text.") {
2502 // Already set in assignAddress
2505 sect, n, va = assignAddress(ctxt, sect, n, tramp, va, true, big)
2509 // merge tramps into Textp, keeping Textp in address order
2511 newtextp := make([]loader.Sym, 0, len(ctxt.Textp)+ntramps)
2513 for _, s := range ctxt.Textp {
2514 for ; i < ntramps && ldr.SymValue(ctxt.tramps[i]) < ldr.SymValue(s); i++ {
2515 newtextp = append(newtextp, ctxt.tramps[i])
2517 newtextp = append(newtextp, s)
2519 newtextp = append(newtextp, ctxt.tramps[i:ntramps]...)
2521 ctxt.Textp = newtextp
2525 // Add MinLC size after etext, so it won't collide with the next symbol
2526 // (which may confuse some symbolizer).
2527 sect.Length = va - sect.Vaddr + uint64(ctxt.Arch.MinLC)
2528 ldr.SetSymSect(etext, sect)
2529 if ldr.SymValue(etext) == 0 {
2530 // Set the address of the start/end symbols, if not already
2531 // (i.e. not darwin+dynlink or AIX+external, see above).
2532 ldr.SetSymValue(etext, int64(va))
2533 ldr.SetSymValue(text, int64(Segtext.Sections[0].Vaddr))
2537 // assigns address for a text symbol, returns (possibly new) section, its number, and the address.
2538 func assignAddress(ctxt *Link, sect *sym.Section, n int, s loader.Sym, va uint64, isTramp, big bool) (*sym.Section, int, uint64) {
2540 if thearch.AssignAddress != nil {
2541 return thearch.AssignAddress(ldr, sect, n, s, va, isTramp)
2544 ldr.SetSymSect(s, sect)
2545 if ldr.AttrSubSymbol(s) {
2549 align := ldr.SymAlign(s)
2551 align = int32(Funcalign)
2553 va = uint64(Rnd(int64(va), int64(align)))
2554 if sect.Align < align {
2558 funcsize := uint64(MINFUNC) // spacing required for findfunctab
2559 if ldr.SymSize(s) > MINFUNC {
2560 funcsize = uint64(ldr.SymSize(s))
2563 // If we need to split text sections, and this function doesn't fit in the current
2564 // section, then create a new one.
2566 // Only break at outermost syms.
2567 if big && splitTextSections(ctxt) && ldr.OuterSym(s) == 0 {
2568 // For debugging purposes, allow text size limit to be cranked down,
2569 // so as to stress test the code that handles multiple text sections.
2570 var textSizelimit uint64 = thearch.TrampLimit
2571 if *FlagDebugTextSize != 0 {
2572 textSizelimit = uint64(*FlagDebugTextSize)
2575 // Sanity check: make sure the limit is larger than any
2576 // individual text symbol.
2577 if funcsize > textSizelimit {
2578 panic(fmt.Sprintf("error: text size limit %d less than text symbol %s size of %d", textSizelimit, ldr.SymName(s), funcsize))
2581 if va-sect.Vaddr+funcsize+maxSizeTrampolines(ctxt, ldr, s, isTramp) > textSizelimit {
2582 sectAlign := int32(thearch.Funcalign)
2584 // Align the next text section to the worst case function alignment likely
2585 // to be encountered when processing function symbols. The start address
2586 // is rounded against the final alignment of the text section later on in
2587 // (*Link).address. This may happen due to usage of PCALIGN directives
2588 // larger than Funcalign, or usage of ISA 3.1 prefixed instructions
2589 // (see ISA 3.1 Book I 1.9).
2590 const ppc64maxFuncalign = 64
2591 sectAlign = ppc64maxFuncalign
2592 va = uint64(Rnd(int64(va), ppc64maxFuncalign))
2595 // Set the length for the previous text section
2596 sect.Length = va - sect.Vaddr
2598 // Create new section, set the starting Vaddr
2599 sect = addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2602 sect.Align = sectAlign
2603 ldr.SetSymSect(s, sect)
2605 // Create a symbol for the start of the secondary text sections
2606 ntext := ldr.CreateSymForUpdate(fmt.Sprintf("runtime.text.%d", n), 0)
2609 // runtime.text.X must be a real symbol on AIX.
2610 // Assign its address directly in order to be the
2611 // first symbol of this new section.
2612 ntext.SetType(sym.STEXT)
2613 ntext.SetSize(int64(MINFUNC))
2614 ntext.SetOnList(true)
2615 ntext.SetAlign(sectAlign)
2616 ctxt.tramps = append(ctxt.tramps, ntext.Sym())
2618 ntext.SetValue(int64(va))
2619 va += uint64(ntext.Size())
2621 if align := ldr.SymAlign(s); align != 0 {
2622 va = uint64(Rnd(int64(va), int64(align)))
2624 va = uint64(Rnd(int64(va), int64(Funcalign)))
2631 ldr.SetSymValue(s, 0)
2632 for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2633 ldr.SetSymValue(sub, ldr.SymValue(sub)+int64(va))
2634 if ctxt.Debugvlog > 2 {
2635 fmt.Println("assign text address:", ldr.SymName(sub), ldr.SymValue(sub))
2644 func resetAddress(ctxt *Link, s loader.Sym) {
2646 if ldr.OuterSym(s) != 0 {
2649 oldv := ldr.SymValue(s)
2650 for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2651 ldr.SetSymValue(sub, ldr.SymValue(sub)-oldv)
2655 // Return whether we may need to split text sections.
2657 // On PPC64x, when external linking, a text section should not be
2658 // larger than 2^25 bytes due to the size of call target offset field
2659 // in the 'bl' instruction. Splitting into smaller text sections
2660 // smaller than this limit allows the system linker to modify the long
2661 // calls appropriately. The limit allows for the space needed for
2662 // tables inserted by the linker.
2664 // The same applies to Darwin/ARM64, with 2^27 byte threshold.
2666 // Similarly for ARM, we split sections (at 2^25 bytes) to avoid
2667 // inconsistencies between the Go linker's reachability calculations
2668 // (e.g. will direct call from X to Y need a trampoline) and similar
2669 // machinery in the external linker; see #58425 for more on the
2671 func splitTextSections(ctxt *Link) bool {
2672 return (ctxt.IsARM() || ctxt.IsPPC64() || (ctxt.IsARM64() && ctxt.IsDarwin())) && ctxt.IsExternal()
2675 // On Wasm, we reserve 4096 bytes for zero page, then 8192 bytes for wasm_exec.js
2676 // to store command line args and environment variables.
2677 // Data sections starts from at least address 12288.
2678 // Keep in sync with wasm_exec.js.
2679 const wasmMinDataAddr = 4096 + 8192
2681 // address assigns virtual addresses to all segments and sections and
2682 // returns all segments in file order.
2683 func (ctxt *Link) address() []*sym.Segment {
2684 var order []*sym.Segment // Layout order
2686 va := uint64(*FlagTextAddr)
2687 order = append(order, &Segtext)
2690 for i, s := range Segtext.Sections {
2691 va = uint64(Rnd(int64(va), int64(s.Align)))
2695 if ctxt.IsWasm() && i == 0 && va < wasmMinDataAddr {
2696 va = wasmMinDataAddr
2700 Segtext.Length = va - uint64(*FlagTextAddr)
2702 if len(Segrodata.Sections) > 0 {
2703 // align to page boundary so as not to mix
2704 // rodata and executable text.
2706 // Note: gold or GNU ld will reduce the size of the executable
2707 // file by arranging for the relro segment to end at a page
2708 // boundary, and overlap the end of the text segment with the
2709 // start of the relro segment in the file. The PT_LOAD segments
2710 // will be such that the last page of the text segment will be
2711 // mapped twice, once r-x and once starting out rw- and, after
2712 // relocation processing, changed to r--.
2714 // Ideally the last page of the text segment would not be
2715 // writable even for this short period.
2716 va = uint64(Rnd(int64(va), *FlagRound))
2718 order = append(order, &Segrodata)
2720 Segrodata.Vaddr = va
2721 for _, s := range Segrodata.Sections {
2722 va = uint64(Rnd(int64(va), int64(s.Align)))
2727 Segrodata.Length = va - Segrodata.Vaddr
2729 if len(Segrelrodata.Sections) > 0 {
2730 // align to page boundary so as not to mix
2731 // rodata, rel-ro data, and executable text.
2732 va = uint64(Rnd(int64(va), *FlagRound))
2733 if ctxt.HeadType == objabi.Haix {
2734 // Relro data are inside data segment on AIX.
2735 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2738 order = append(order, &Segrelrodata)
2739 Segrelrodata.Rwx = 06
2740 Segrelrodata.Vaddr = va
2741 for _, s := range Segrelrodata.Sections {
2742 va = uint64(Rnd(int64(va), int64(s.Align)))
2747 Segrelrodata.Length = va - Segrelrodata.Vaddr
2750 va = uint64(Rnd(int64(va), *FlagRound))
2751 if ctxt.HeadType == objabi.Haix && len(Segrelrodata.Sections) == 0 {
2752 // Data sections are moved to an unreachable segment
2753 // to ensure that they are position-independent.
2754 // Already done if relro sections exist.
2755 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2757 order = append(order, &Segdata)
2760 var data *sym.Section
2761 var noptr *sym.Section
2762 var bss *sym.Section
2763 var noptrbss *sym.Section
2764 var fuzzCounters *sym.Section
2765 for i, s := range Segdata.Sections {
2766 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && s.Name == ".tbss" {
2769 vlen := int64(s.Length)
2770 if i+1 < len(Segdata.Sections) && !((ctxt.IsELF || ctxt.HeadType == objabi.Haix) && Segdata.Sections[i+1].Name == ".tbss") {
2771 vlen = int64(Segdata.Sections[i+1].Vaddr - s.Vaddr)
2775 Segdata.Length = va - Segdata.Vaddr
2785 case ".go.fuzzcntrs":
2790 // Assign Segdata's Filelen omitting the BSS. We do this here
2791 // simply because right now we know where the BSS starts.
2792 Segdata.Filelen = bss.Vaddr - Segdata.Vaddr
2794 if len(Segpdata.Sections) > 0 {
2795 va = uint64(Rnd(int64(va), *FlagRound))
2796 order = append(order, &Segpdata)
2799 // Segpdata.Sections is intended to contain just one section.
2800 // Loop through the slice anyway for consistency.
2801 for _, s := range Segpdata.Sections {
2802 va = uint64(Rnd(int64(va), int64(s.Align)))
2806 Segpdata.Length = va - Segpdata.Vaddr
2809 if len(Segxdata.Sections) > 0 {
2810 va = uint64(Rnd(int64(va), *FlagRound))
2811 order = append(order, &Segxdata)
2814 // Segxdata.Sections is intended to contain just one section.
2815 // Loop through the slice anyway for consistency.
2816 for _, s := range Segxdata.Sections {
2817 va = uint64(Rnd(int64(va), int64(s.Align)))
2821 Segxdata.Length = va - Segxdata.Vaddr
2824 va = uint64(Rnd(int64(va), *FlagRound))
2825 order = append(order, &Segdwarf)
2828 for i, s := range Segdwarf.Sections {
2829 vlen := int64(s.Length)
2830 if i+1 < len(Segdwarf.Sections) {
2831 vlen = int64(Segdwarf.Sections[i+1].Vaddr - s.Vaddr)
2835 if ctxt.HeadType == objabi.Hwindows {
2836 va = uint64(Rnd(int64(va), PEFILEALIGN))
2838 Segdwarf.Length = va - Segdwarf.Vaddr
2843 rodata = ldr.SymSect(ldr.LookupOrCreateSym("runtime.rodata", 0))
2844 symtab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.symtab", 0))
2845 pclntab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0))
2846 types = ldr.SymSect(ldr.LookupOrCreateSym("runtime.types", 0))
2849 for _, s := range ctxt.datap {
2850 if sect := ldr.SymSect(s); sect != nil {
2851 ldr.AddToSymValue(s, int64(sect.Vaddr))
2853 v := ldr.SymValue(s)
2854 for sub := ldr.SubSym(s); sub != 0; sub = ldr.SubSym(sub) {
2855 ldr.AddToSymValue(sub, v)
2859 for _, si := range dwarfp {
2860 for _, s := range si.syms {
2861 if sect := ldr.SymSect(s); sect != nil {
2862 ldr.AddToSymValue(s, int64(sect.Vaddr))
2864 sub := ldr.SubSym(s)
2866 panic(fmt.Sprintf("unexpected sub-sym for %s %s", ldr.SymName(s), ldr.SymType(s).String()))
2868 v := ldr.SymValue(s)
2869 for ; sub != 0; sub = ldr.SubSym(sub) {
2870 ldr.AddToSymValue(s, v)
2875 for _, s := range []loader.Sym{sehp.pdata, sehp.xdata} {
2876 if sect := ldr.SymSect(s); sect != nil {
2877 ldr.AddToSymValue(s, int64(sect.Vaddr))
2881 if ctxt.BuildMode == BuildModeShared {
2882 s := ldr.LookupOrCreateSym("go:link.abihashbytes", 0)
2883 sect := ldr.SymSect(ldr.LookupOrCreateSym(".note.go.abihash", 0))
2884 ldr.SetSymSect(s, sect)
2885 ldr.SetSymValue(s, int64(sect.Vaddr+16))
2888 // If there are multiple text sections, create runtime.text.n for
2889 // their section Vaddr, using n for index
2891 for _, sect := range Segtext.Sections[1:] {
2892 if sect.Name != ".text" {
2895 symname := fmt.Sprintf("runtime.text.%d", n)
2896 if ctxt.HeadType != objabi.Haix || ctxt.LinkMode != LinkExternal {
2897 // Addresses are already set on AIX with external linker
2898 // because these symbols are part of their sections.
2899 ctxt.xdefine(symname, sym.STEXT, int64(sect.Vaddr))
2904 ctxt.xdefine("runtime.rodata", sym.SRODATA, int64(rodata.Vaddr))
2905 ctxt.xdefine("runtime.erodata", sym.SRODATA, int64(rodata.Vaddr+rodata.Length))
2906 ctxt.xdefine("runtime.types", sym.SRODATA, int64(types.Vaddr))
2907 ctxt.xdefine("runtime.etypes", sym.SRODATA, int64(types.Vaddr+types.Length))
2909 s := ldr.Lookup("runtime.gcdata", 0)
2910 ldr.SetAttrLocal(s, true)
2911 ctxt.xdefine("runtime.egcdata", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2912 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcdata", 0), ldr.SymSect(s))
2914 s = ldr.LookupOrCreateSym("runtime.gcbss", 0)
2915 ldr.SetAttrLocal(s, true)
2916 ctxt.xdefine("runtime.egcbss", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2917 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcbss", 0), ldr.SymSect(s))
2919 ctxt.xdefine("runtime.symtab", sym.SRODATA, int64(symtab.Vaddr))
2920 ctxt.xdefine("runtime.esymtab", sym.SRODATA, int64(symtab.Vaddr+symtab.Length))
2921 ctxt.xdefine("runtime.pclntab", sym.SRODATA, int64(pclntab.Vaddr))
2922 ctxt.defineInternal("runtime.pcheader", sym.SRODATA)
2923 ctxt.defineInternal("runtime.funcnametab", sym.SRODATA)
2924 ctxt.defineInternal("runtime.cutab", sym.SRODATA)
2925 ctxt.defineInternal("runtime.filetab", sym.SRODATA)
2926 ctxt.defineInternal("runtime.pctab", sym.SRODATA)
2927 ctxt.defineInternal("runtime.functab", sym.SRODATA)
2928 ctxt.xdefine("runtime.epclntab", sym.SRODATA, int64(pclntab.Vaddr+pclntab.Length))
2929 ctxt.xdefine("runtime.noptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr))
2930 ctxt.xdefine("runtime.enoptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr+noptr.Length))
2931 ctxt.xdefine("runtime.bss", sym.SBSS, int64(bss.Vaddr))
2932 ctxt.xdefine("runtime.ebss", sym.SBSS, int64(bss.Vaddr+bss.Length))
2933 ctxt.xdefine("runtime.data", sym.SDATA, int64(data.Vaddr))
2934 ctxt.xdefine("runtime.edata", sym.SDATA, int64(data.Vaddr+data.Length))
2935 ctxt.xdefine("runtime.noptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr))
2936 ctxt.xdefine("runtime.enoptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr+noptrbss.Length))
2937 ctxt.xdefine("runtime.covctrs", sym.SCOVERAGE_COUNTER, int64(noptrbss.Vaddr+covCounterDataStartOff))
2938 ctxt.xdefine("runtime.ecovctrs", sym.SCOVERAGE_COUNTER, int64(noptrbss.Vaddr+covCounterDataStartOff+covCounterDataLen))
2939 ctxt.xdefine("runtime.end", sym.SBSS, int64(Segdata.Vaddr+Segdata.Length))
2941 if fuzzCounters != nil {
2942 ctxt.xdefine("runtime.__start___sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr))
2943 ctxt.xdefine("runtime.__stop___sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
2944 ctxt.xdefine("internal/fuzz._counters", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr))
2945 ctxt.xdefine("internal/fuzz._ecounters", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
2948 if ctxt.IsSolaris() {
2949 // On Solaris, in the runtime it sets the external names of the
2950 // end symbols. Unset them and define separate symbols, so we
2952 etext := ldr.Lookup("runtime.etext", 0)
2953 edata := ldr.Lookup("runtime.edata", 0)
2954 end := ldr.Lookup("runtime.end", 0)
2955 ldr.SetSymExtname(etext, "runtime.etext")
2956 ldr.SetSymExtname(edata, "runtime.edata")
2957 ldr.SetSymExtname(end, "runtime.end")
2958 ctxt.xdefine("_etext", ldr.SymType(etext), ldr.SymValue(etext))
2959 ctxt.xdefine("_edata", ldr.SymType(edata), ldr.SymValue(edata))
2960 ctxt.xdefine("_end", ldr.SymType(end), ldr.SymValue(end))
2961 ldr.SetSymSect(ldr.Lookup("_etext", 0), ldr.SymSect(etext))
2962 ldr.SetSymSect(ldr.Lookup("_edata", 0), ldr.SymSect(edata))
2963 ldr.SetSymSect(ldr.Lookup("_end", 0), ldr.SymSect(end))
2966 if ctxt.IsPPC64() && ctxt.IsElf() {
2967 // Resolve .TOC. symbols for all objects. Only one TOC region is supported. If a
2968 // GOT section is present, compute it as suggested by the ELFv2 ABI. Otherwise,
2969 // choose a similar offset from the start of the data segment.
2970 tocAddr := int64(Segdata.Vaddr) + 0x8000
2971 if gotAddr := ldr.SymValue(ctxt.GOT); gotAddr != 0 {
2972 tocAddr = gotAddr + 0x8000
2974 for i := range ctxt.DotTOC {
2975 if i >= sym.SymVerABICount && i < sym.SymVerStatic { // these versions are not used currently
2978 if toc := ldr.Lookup(".TOC.", i); toc != 0 {
2979 ldr.SetSymValue(toc, tocAddr)
2987 // layout assigns file offsets and lengths to the segments in order.
2988 // Returns the file size containing all the segments.
2989 func (ctxt *Link) layout(order []*sym.Segment) uint64 {
2990 var prev *sym.Segment
2991 for _, seg := range order {
2993 seg.Fileoff = uint64(HEADR)
2995 switch ctxt.HeadType {
2997 // Assuming the previous segment was
2998 // aligned, the following rounding
2999 // should ensure that this segment's
3000 // VA ≡ Fileoff mod FlagRound.
3001 seg.Fileoff = uint64(Rnd(int64(prev.Fileoff+prev.Filelen), *FlagRound))
3002 if seg.Vaddr%uint64(*FlagRound) != seg.Fileoff%uint64(*FlagRound) {
3003 Exitf("bad segment rounding (Vaddr=%#x Fileoff=%#x FlagRound=%#x)", seg.Vaddr, seg.Fileoff, *FlagRound)
3005 case objabi.Hwindows:
3006 seg.Fileoff = prev.Fileoff + uint64(Rnd(int64(prev.Filelen), PEFILEALIGN))
3008 seg.Fileoff = prev.Fileoff + prev.Filelen
3011 if seg != &Segdata {
3012 // Link.address already set Segdata.Filelen to
3014 seg.Filelen = seg.Length
3018 return prev.Fileoff + prev.Filelen
3021 // add a trampoline with symbol s (to be laid down after the current function)
3022 func (ctxt *Link) AddTramp(s *loader.SymbolBuilder) {
3023 s.SetType(sym.STEXT)
3024 s.SetReachable(true)
3026 ctxt.tramps = append(ctxt.tramps, s.Sym())
3027 if *FlagDebugTramp > 0 && ctxt.Debugvlog > 0 {
3028 ctxt.Logf("trampoline %s inserted\n", s.Name())
3032 // compressSyms compresses syms and returns the contents of the
3033 // compressed section. If the section would get larger, it returns nil.
3034 func compressSyms(ctxt *Link, syms []loader.Sym) []byte {
3037 for _, sym := range syms {
3038 total += ldr.SymSize(sym)
3041 var buf bytes.Buffer
3043 switch ctxt.Arch.PtrSize {
3045 binary.Write(&buf, ctxt.Arch.ByteOrder, elf.Chdr64{
3046 Type: uint32(elf.COMPRESS_ZLIB),
3047 Size: uint64(total),
3048 Addralign: uint64(ctxt.Arch.Alignment),
3051 binary.Write(&buf, ctxt.Arch.ByteOrder, elf.Chdr32{
3052 Type: uint32(elf.COMPRESS_ZLIB),
3053 Size: uint32(total),
3054 Addralign: uint32(ctxt.Arch.Alignment),
3057 log.Fatalf("can't compress header size:%d", ctxt.Arch.PtrSize)
3060 buf.Write([]byte("ZLIB"))
3061 var sizeBytes [8]byte
3062 binary.BigEndian.PutUint64(sizeBytes[:], uint64(total))
3063 buf.Write(sizeBytes[:])
3066 var relocbuf []byte // temporary buffer for applying relocations
3068 // Using zlib.BestSpeed achieves very nearly the same
3069 // compression levels of zlib.DefaultCompression, but takes
3070 // substantially less time. This is important because DWARF
3071 // compression can be a significant fraction of link time.
3072 z, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
3074 log.Fatalf("NewWriterLevel failed: %s", err)
3076 st := ctxt.makeRelocSymState()
3077 for _, s := range syms {
3078 // Symbol data may be read-only. Apply relocations in a
3079 // temporary buffer, and immediately write it out.
3081 relocs := ldr.Relocs(s)
3082 if relocs.Count() != 0 {
3083 relocbuf = append(relocbuf[:0], P...)
3087 if _, err := z.Write(P); err != nil {
3088 log.Fatalf("compression failed: %s", err)
3090 for i := ldr.SymSize(s) - int64(len(P)); i > 0; {
3092 if i < int64(len(b)) {
3095 n, err := z.Write(b)
3097 log.Fatalf("compression failed: %s", err)
3102 if err := z.Close(); err != nil {
3103 log.Fatalf("compression failed: %s", err)
3105 if int64(buf.Len()) >= total {
3106 // Compression didn't save any space.