1 // Derived from Inferno utils/6l/obj.c and utils/6l/span.c
2 // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/obj.c
3 // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/span.c
5 // Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
6 // Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
7 // Portions Copyright © 1997-1999 Vita Nuova Limited
8 // Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
9 // Portions Copyright © 2004,2006 Bruce Ellis
10 // Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
11 // Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
12 // Portions Copyright © 2009 The Go Authors. All rights reserved.
14 // Permission is hereby granted, free of charge, to any person obtaining a copy
15 // of this software and associated documentation files (the "Software"), to deal
16 // in the Software without restriction, including without limitation the rights
17 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 // copies of the Software, and to permit persons to whom the Software is
19 // furnished to do so, subject to the following conditions:
21 // The above copyright notice and this permission notice shall be included in
22 // all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
39 "cmd/link/internal/loader"
40 "cmd/link/internal/sym"
54 // isRuntimeDepPkg reports whether pkg is the runtime package or its dependency
55 func isRuntimeDepPkg(pkg string) bool {
58 "sync/atomic", // runtime may call to sync/atomic, due to go:linkname
59 "internal/abi", // used by reflectcall (and maybe more)
60 "internal/bytealg", // for IndexByte
61 "internal/cpu": // for cpu features
64 return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test")
67 // Estimate the max size needed to hold any new trampolines created for this function. This
68 // is used to determine when the section can be split if it becomes too large, to ensure that
69 // the trampolines are in the same section as the function that uses them.
70 func maxSizeTrampolines(ctxt *Link, ldr *loader.Loader, s loader.Sym, isTramp bool) uint64 {
71 // If thearch.Trampoline is nil, then trampoline support is not available on this arch.
72 // A trampoline does not need any dependent trampolines.
73 if thearch.Trampoline == nil || isTramp {
78 relocs := ldr.Relocs(s)
79 for ri := 0; ri < relocs.Count(); ri++ {
81 if r.Type().IsDirectCallOrJump() {
87 return n * 16 // Trampolines in PPC64 are 4 instructions.
90 return n * 12 // Trampolines in ARM64 are 3 instructions.
95 // Detect too-far jumps in function s, and add trampolines if necessary.
96 // ARM, PPC64, PPC64LE and RISCV64 support trampoline insertion for internal
97 // and external linking. On PPC64 and PPC64LE the text sections might be split
98 // but will still insert trampolines where necessary.
99 func trampoline(ctxt *Link, s loader.Sym) {
100 if thearch.Trampoline == nil {
101 return // no need or no support of trampolines on this arch
105 relocs := ldr.Relocs(s)
106 for ri := 0; ri < relocs.Count(); ri++ {
109 if !rt.IsDirectCallOrJump() && !isPLTCall(rt) {
113 if !ldr.AttrReachable(rs) || ldr.SymType(rs) == sym.Sxxx {
114 continue // something is wrong. skip it here and we'll emit a better error later
117 // RISC-V is only able to reach +/-1MiB via a JAL instruction,
118 // which we can readily exceed in the same package. As such, we
119 // need to generate trampolines when the address is unknown.
120 if ldr.SymValue(rs) == 0 && !ctxt.Target.IsRISCV64() && ldr.SymType(rs) != sym.SDYNIMPORT && ldr.SymType(rs) != sym.SUNDEFEXT {
121 if ldr.SymPkg(s) != "" && ldr.SymPkg(rs) == ldr.SymPkg(s) {
122 // Symbols in the same package are laid out together.
123 // Except that if SymPkg(s) == "", it is a host object symbol
124 // which may call an external symbol via PLT.
127 if isRuntimeDepPkg(ldr.SymPkg(s)) && isRuntimeDepPkg(ldr.SymPkg(rs)) {
128 continue // runtime packages are laid out together
131 thearch.Trampoline(ctxt, ldr, ri, rs, s)
135 // whether rt is a (host object) relocation that will be turned into
137 func isPLTCall(rt objabi.RelocType) bool {
141 case objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_CALL26),
142 objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_JUMP26),
143 objabi.MachoRelocOffset + MACHO_ARM64_RELOC_BRANCH26*2 + pcrel:
147 case objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_CALL),
148 objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_PC24),
149 objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_JUMP24):
152 // TODO: other architectures.
156 // FoldSubSymbolOffset computes the offset of symbol s to its top-level outer
157 // symbol. Returns the top-level symbol and the offset.
158 // This is used in generating external relocations.
159 func FoldSubSymbolOffset(ldr *loader.Loader, s loader.Sym) (loader.Sym, int64) {
160 outer := ldr.OuterSym(s)
163 off += ldr.SymValue(s) - ldr.SymValue(outer)
169 // relocsym resolve relocations in "s", updating the symbol's content
171 // The main loop walks through the list of relocations attached to "s"
172 // and resolves them where applicable. Relocations are often
173 // architecture-specific, requiring calls into the 'archreloc' and/or
174 // 'archrelocvariant' functions for the architecture. When external
175 // linking is in effect, it may not be possible to completely resolve
176 // the address/offset for a symbol, in which case the goal is to lay
177 // the groundwork for turning a given relocation into an external reloc
178 // (to be applied by the external linker). For more on how relocations
179 // work in general, see
181 // "Linkers and Loaders", by John R. Levine (Morgan Kaufmann, 1999), ch. 7
183 // This is a performance-critical function for the linker; be careful
184 // to avoid introducing unnecessary allocations in the main loop.
185 func (st *relocSymState) relocsym(s loader.Sym, P []byte) {
187 relocs := ldr.Relocs(s)
188 if relocs.Count() == 0 {
193 nExtReloc := 0 // number of external relocations
194 for ri := 0; ri < relocs.Count(); ri++ {
197 siz := int32(r.Siz())
201 if off < 0 || off+siz > int32(len(P)) {
204 rname = ldr.SymName(rs)
206 st.err.Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(P))
209 if siz == 0 { // informational relocation - no work to do
215 rst = ldr.SymType(rs)
218 if rs != 0 && (rst == sym.Sxxx || rst == sym.SXREF) {
219 // When putting the runtime but not main into a shared library
220 // these symbols are undefined and that's OK.
221 if target.IsShared() || target.IsPlugin() {
222 if ldr.SymName(rs) == "main.main" || (!target.IsPlugin() && ldr.SymName(rs) == "main..inittask") {
223 sb := ldr.MakeSymbolUpdater(rs)
224 sb.SetType(sym.SDYNIMPORT)
225 } else if strings.HasPrefix(ldr.SymName(rs), "go:info.") {
226 // Skip go.info symbols. They are only needed to communicate
227 // DWARF info between the compiler and linker.
230 } else if target.IsPPC64() && ldr.SymName(rs) == ".TOC." {
231 // TOC symbol doesn't have a type but we do assign a value
232 // (see the address pass) and we can resolve it.
233 // TODO: give it a type.
235 st.err.errorUnresolved(ldr, s, rs)
240 if rt >= objabi.ElfRelocOffset {
244 // We need to be able to reference dynimport symbols when linking against
245 // shared libraries, and AIX, Darwin, OpenBSD and Solaris always need it.
246 if !target.IsAIX() && !target.IsDarwin() && !target.IsSolaris() && !target.IsOpenbsd() && rs != 0 && rst == sym.SDYNIMPORT && !target.IsDynlinkingGo() && !ldr.AttrSubSymbol(rs) {
247 if !(target.IsPPC64() && target.IsExternal() && ldr.SymName(rs) == ".TOC.") {
248 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))
251 if rs != 0 && rst != sym.STLSBSS && !weak && rt != objabi.R_METHODOFF && !ldr.AttrReachable(rs) {
252 st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
255 var rv sym.RelocVariant
256 if target.IsPPC64() || target.IsS390X() {
257 rv = ldr.RelocVariant(s, ri)
260 // TODO(mundaym): remove this special case - see issue 14218.
261 if target.IsS390X() {
263 case objabi.R_PCRELDBL:
276 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
280 o = int64(target.Arch.ByteOrder.Uint16(P[off:]))
282 o = int64(target.Arch.ByteOrder.Uint32(P[off:]))
284 o = int64(target.Arch.ByteOrder.Uint64(P[off:]))
286 out, n, ok := thearch.Archreloc(target, ldr, syms, r, s, o)
287 if target.IsExternal() {
293 st.err.Errorf(s, "unknown reloc to %v: %d (%s)", ldr.SymName(rs), rt, sym.RelocName(target.Arch, rt))
295 case objabi.R_TLS_LE:
296 if target.IsExternal() && target.IsElf() {
299 if !target.IsAMD64() {
305 if target.IsElf() && target.IsARM() {
306 // On ELF ARM, the thread pointer is 8 bytes before
307 // the start of the thread-local data block, so add 8
308 // to the actual TLS offset (r->sym->value).
309 // This 8 seems to be a fundamental constant of
310 // ELF on ARM (or maybe Glibc on ARM); it is not
311 // related to the fact that our own TLS storage happens
312 // to take up 8 bytes.
313 o = 8 + ldr.SymValue(rs)
314 } else if target.IsElf() || target.IsPlan9() || target.IsDarwin() {
315 o = int64(syms.Tlsoffset) + r.Add()
316 } else if target.IsWindows() {
319 log.Fatalf("unexpected R_TLS_LE relocation for %v", target.HeadType)
321 case objabi.R_TLS_IE:
322 if target.IsExternal() && target.IsElf() {
325 if !target.IsAMD64() {
329 nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
333 if target.IsPIE() && target.IsElf() {
334 // We are linking the final executable, so we
335 // can optimize any TLS IE relocation to LE.
336 if thearch.TLSIEtoLE == nil {
337 log.Fatalf("internal linking of TLS IE not supported on %v", target.Arch.Family)
339 thearch.TLSIEtoLE(P, int(off), int(siz))
340 o = int64(syms.Tlsoffset)
342 log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", ldr.SymName(s))
345 if weak && !ldr.AttrReachable(rs) {
346 // Redirect it to runtime.unreachableMethod, which will throw if called.
347 rs = syms.unreachableMethod
349 if target.IsExternal() {
352 // set up addend for eventual relocation via outer symbol.
354 rs, off := FoldSubSymbolOffset(ldr, rs)
355 xadd := r.Add() + off
356 rst := ldr.SymType(rs)
357 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
358 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
363 if target.IsAMD64() {
366 } else if target.IsDarwin() {
367 if ldr.SymType(rs) != sym.SHOSTOBJ {
368 o += ldr.SymValue(rs)
370 } else if target.IsWindows() {
372 } else if target.IsAIX() {
373 o = ldr.SymValue(rs) + xadd
375 st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
381 // On AIX, a second relocation must be done by the loader,
382 // as section addresses can change once loaded.
383 // The "default" symbol address is still needed by the loader so
384 // the current relocation can't be skipped.
385 if target.IsAIX() && rst != sym.SDYNIMPORT {
386 // It's not possible to make a loader relocation in a
387 // symbol which is not inside .data section.
388 // FIXME: It should be forbidden to have R_ADDR from a
389 // symbol which isn't in .data. However, as .text has the
390 // same address once loaded, this is possible.
391 if ldr.SymSect(s).Seg == &Segdata {
392 Xcoffadddynrel(target, ldr, syms, s, r, ri)
396 o = ldr.SymValue(rs) + r.Add()
398 // On amd64, 4-byte offsets will be sign-extended, so it is impossible to
399 // access more than 2GB of static data; fail at link time is better than
400 // fail at runtime. See https://golang.org/issue/7980.
401 // Instead of special casing only amd64, we treat this as an error on all
402 // 64-bit architectures so as to be future-proof.
403 if int32(o) < 0 && target.Arch.PtrSize > 4 && siz == 4 {
404 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())
407 case objabi.R_DWARFSECREF:
408 if ldr.SymSect(rs) == nil {
409 st.err.Errorf(s, "missing DWARF section for relocation target %s", ldr.SymName(rs))
412 if target.IsExternal() {
413 // On most platforms, the external linker needs to adjust DWARF references
414 // as it combines DWARF sections. However, on Darwin, dsymutil does the
415 // DWARF linking, and it understands how to follow section offsets.
416 // Leaving in the relocation records confuses it (see
417 // https://golang.org/issue/22068) so drop them for Darwin.
418 if !target.IsDarwin() {
422 xadd := r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
425 if target.IsElf() && target.IsAMD64() {
430 o = ldr.SymValue(rs) + r.Add() - int64(ldr.SymSect(rs).Vaddr)
431 case objabi.R_METHODOFF:
432 if !ldr.AttrReachable(rs) {
433 // Set it to a sentinel value. The runtime knows this is not pointing to
439 case objabi.R_ADDROFF:
440 if weak && !ldr.AttrReachable(rs) {
443 if ldr.SymSect(rs) == nil {
444 st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
448 // The method offset tables using this relocation expect the offset to be relative
449 // to the start of the first text section, even if there are multiple.
450 if ldr.SymSect(rs).Name == ".text" {
451 o = ldr.SymValue(rs) - int64(Segtext.Sections[0].Vaddr) + r.Add()
453 o = ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr) + r.Add()
456 case objabi.R_ADDRCUOFF:
457 // debug_range and debug_loc elements use this relocation type to get an
458 // offset from the start of the compile unit.
459 o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(loader.Sym(ldr.SymUnit(rs).Textp[0]))
461 // r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
462 case objabi.R_GOTPCREL:
463 if target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
468 if target.Is386() && target.IsExternal() && target.IsELF {
469 nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
472 case objabi.R_CALL, objabi.R_PCREL:
473 if target.IsExternal() && rs != 0 && rst == sym.SUNDEFEXT {
474 // pass through to the external linker.
479 if target.IsExternal() && rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
482 // set up addend for eventual relocation via outer symbol.
484 rs, off := FoldSubSymbolOffset(ldr, rs)
485 xadd := r.Add() + off - int64(siz) // relative to address after the relocated chunk
486 rst := ldr.SymType(rs)
487 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && ldr.SymSect(rs) == nil {
488 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
493 if target.IsAMD64() {
496 } else if target.IsDarwin() {
497 if rt == objabi.R_CALL {
498 if target.IsExternal() && rst == sym.SDYNIMPORT {
499 if target.IsAMD64() {
500 // AMD64 dynamic relocations are relative to the end of the relocation.
504 if rst != sym.SHOSTOBJ {
505 o += int64(uint64(ldr.SymValue(rs)) - ldr.SymSect(rs).Vaddr)
507 o -= int64(off) // relative to section offset, not symbol
512 } else if target.IsWindows() && target.IsAMD64() { // only amd64 needs PCREL
513 // PE/COFF's PC32 relocation uses the address after the relocated
514 // bytes as the base. Compensate by skewing the addend.
517 st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
528 o += r.Add() - (ldr.SymValue(s) + int64(off) + int64(siz))
530 o = ldr.SymSize(rs) + r.Add()
532 case objabi.R_XCOFFREF:
534 st.err.Errorf(s, "find XCOFF R_REF on non-XCOFF files")
536 if !target.IsExternal() {
537 st.err.Errorf(s, "find XCOFF R_REF with internal linking")
542 case objabi.R_DWARFFILEREF:
543 // We don't renumber files in dwarf.go:writelines anymore.
549 case objabi.R_GOTOFF:
550 o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(syms.GOT)
553 if target.IsPPC64() || target.IsS390X() {
554 if rv != sym.RV_NONE {
555 o = thearch.Archrelocvariant(target, ldr, r, rv, s, o, P)
561 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
563 P[off] = byte(int8(o))
565 if o != int64(int16(o)) {
566 st.err.Errorf(s, "relocation address for %s is too big: %#x", ldr.SymName(rs), o)
568 target.Arch.ByteOrder.PutUint16(P[off:], uint16(o))
570 if rt == objabi.R_PCREL || rt == objabi.R_CALL {
571 if o != int64(int32(o)) {
572 st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
575 if o != int64(int32(o)) && o != int64(uint32(o)) {
576 st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
579 target.Arch.ByteOrder.PutUint32(P[off:], uint32(o))
581 target.Arch.ByteOrder.PutUint64(P[off:], uint64(o))
584 if target.IsExternal() {
585 // We'll stream out the external relocations in asmb2 (e.g. elfrelocsect)
586 // and we only need the count here.
587 atomic.AddUint32(&ldr.SymSect(s).Relcount, uint32(nExtReloc))
591 // Convert a Go relocation to an external relocation.
592 func extreloc(ctxt *Link, ldr *loader.Loader, s loader.Sym, r loader.Reloc) (loader.ExtReloc, bool) {
593 var rr loader.ExtReloc
594 target := &ctxt.Target
595 siz := int32(r.Siz())
596 if siz == 0 { // informational relocation - no work to do
601 if rt >= objabi.ElfRelocOffset {
607 // TODO(mundaym): remove this special case - see issue 14218.
608 if target.IsS390X() {
610 case objabi.R_PCRELDBL:
617 return thearch.Extreloc(target, ldr, r, s)
619 case objabi.R_TLS_LE, objabi.R_TLS_IE:
632 // set up addend for eventual relocation via outer symbol.
634 if r.Weak() && !ldr.AttrReachable(rs) {
635 rs = ctxt.ArchSyms.unreachableMethod
637 rs, off := FoldSubSymbolOffset(ldr, rs)
638 rr.Xadd = r.Add() + off
641 case objabi.R_DWARFSECREF:
642 // On most platforms, the external linker needs to adjust DWARF references
643 // as it combines DWARF sections. However, on Darwin, dsymutil does the
644 // DWARF linking, and it understands how to follow section offsets.
645 // Leaving in the relocation records confuses it (see
646 // https://golang.org/issue/22068) so drop them for Darwin.
647 if target.IsDarwin() {
651 rr.Xsym = loader.Sym(ldr.SymSect(rs).Sym)
652 rr.Xadd = r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
654 // r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
655 case objabi.R_GOTPCREL, objabi.R_CALL, objabi.R_PCREL:
657 if rt == objabi.R_GOTPCREL && target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
659 rr.Xadd -= int64(siz) // relative to address after the relocated chunk
663 if rs != 0 && ldr.SymType(rs) == sym.SUNDEFEXT {
664 // pass through to the external linker.
667 rr.Xadd -= int64(siz)
672 if rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
673 // set up addend for eventual relocation via outer symbol.
675 rs, off := FoldSubSymbolOffset(ldr, rs)
676 rr.Xadd = r.Add() + off
677 rr.Xadd -= int64(siz) // relative to address after the relocated chunk
683 case objabi.R_XCOFFREF:
684 return ExtrelocSimple(ldr, r), true
686 // These reloc types don't need external relocations.
687 case objabi.R_ADDROFF, objabi.R_METHODOFF, objabi.R_ADDRCUOFF,
688 objabi.R_SIZE, objabi.R_CONST, objabi.R_GOTOFF:
694 // ExtrelocSimple creates a simple external relocation from r, with the same
695 // symbol and addend.
696 func ExtrelocSimple(ldr *loader.Loader, r loader.Reloc) loader.ExtReloc {
697 var rr loader.ExtReloc
706 // ExtrelocViaOuterSym creates an external relocation from r targeting the
707 // outer symbol and folding the subsymbol's offset into the addend.
708 func ExtrelocViaOuterSym(ldr *loader.Loader, r loader.Reloc, s loader.Sym) loader.ExtReloc {
709 // set up addend for eventual relocation via outer symbol.
710 var rr loader.ExtReloc
712 rs, off := FoldSubSymbolOffset(ldr, rs)
713 rr.Xadd = r.Add() + off
714 rst := ldr.SymType(rs)
715 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
716 ldr.Errorf(s, "missing section for %s", ldr.SymName(rs))
724 // relocSymState hold state information needed when making a series of
725 // successive calls to relocsym(). The items here are invariant
726 // (meaning that they are set up once initially and then don't change
727 // during the execution of relocsym), with the exception of a slice
728 // used to facilitate batch allocation of external relocations. Calls
729 // to relocsym happen in parallel; the assumption is that each
730 // parallel thread will have its own state object.
731 type relocSymState struct {
738 // makeRelocSymState creates a relocSymState container object to
739 // pass to relocsym(). If relocsym() calls happen in parallel,
740 // each parallel thread should have its own state object.
741 func (ctxt *Link) makeRelocSymState() *relocSymState {
742 return &relocSymState{
743 target: &ctxt.Target,
745 err: &ctxt.ErrorReporter,
746 syms: &ctxt.ArchSyms,
750 func windynrelocsym(ctxt *Link, rel *loader.SymbolBuilder, s loader.Sym) {
751 var su *loader.SymbolBuilder
752 relocs := ctxt.loader.Relocs(s)
753 for ri := 0; ri < relocs.Count(); ri++ {
756 continue // skip marker relocations
762 if !ctxt.loader.AttrReachable(targ) {
766 ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s",
767 ctxt.loader.SymName(targ))
770 tplt := ctxt.loader.SymPlt(targ)
771 tgot := ctxt.loader.SymGot(targ)
772 if tplt == -2 && tgot != -2 { // make dynimport JMP table for PE object files.
773 tplt := int32(rel.Size())
774 ctxt.loader.SetPlt(targ, tplt)
777 su = ctxt.loader.MakeSymbolUpdater(s)
780 r.SetAdd(int64(tplt))
783 switch ctxt.Arch.Family {
785 ctxt.Errorf(s, "unsupported arch %v", ctxt.Arch.Family)
790 rel.AddAddrPlus(ctxt.Arch, targ, 0)
797 rel.AddAddrPlus4(ctxt.Arch, targ, 0)
800 } else if tplt >= 0 {
802 su = ctxt.loader.MakeSymbolUpdater(s)
805 r.SetAdd(int64(tplt))
810 // windynrelocsyms generates jump table to C library functions that will be
811 // added later. windynrelocsyms writes the table into .rel symbol.
812 func (ctxt *Link) windynrelocsyms() {
813 if !(ctxt.IsWindows() && iscgo && ctxt.IsInternal()) {
817 rel := ctxt.loader.CreateSymForUpdate(".rel", 0)
818 rel.SetType(sym.STEXT)
820 for _, s := range ctxt.Textp {
821 windynrelocsym(ctxt, rel, s)
824 ctxt.Textp = append(ctxt.Textp, rel.Sym())
827 func dynrelocsym(ctxt *Link, s loader.Sym) {
828 target := &ctxt.Target
830 syms := &ctxt.ArchSyms
831 relocs := ldr.Relocs(s)
832 for ri := 0; ri < relocs.Count(); ri++ {
835 continue // skip marker relocations
838 if r.Weak() && !ldr.AttrReachable(rSym) {
841 if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal {
842 // It's expected that some relocations will be done
843 // later by relocsym (R_TLS_LE, R_ADDROFF), so
844 // don't worry if Adddynrel returns false.
845 thearch.Adddynrel(target, ldr, syms, s, r, ri)
849 if rSym != 0 && ldr.SymType(rSym) == sym.SDYNIMPORT || r.Type() >= objabi.ElfRelocOffset {
850 if rSym != 0 && !ldr.AttrReachable(rSym) {
851 ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s", ldr.SymName(rSym))
853 if !thearch.Adddynrel(target, ldr, syms, s, r, ri) {
854 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))
860 func (state *dodataState) dynreloc(ctxt *Link) {
861 if ctxt.HeadType == objabi.Hwindows {
864 // -d suppresses dynamic loader format, so we may as well not
865 // compute these sections or mark their symbols as reachable.
870 for _, s := range ctxt.Textp {
873 for _, syms := range state.data {
874 for _, s := range syms {
883 func CodeblkPad(ctxt *Link, out *OutBuf, addr int64, size int64, pad []byte) {
884 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.Textp, addr, size, pad)
887 const blockSize = 1 << 20 // 1MB chunks written at a time.
889 // writeBlocks writes a specified chunk of symbols to the output buffer. It
890 // breaks the write up into ≥blockSize chunks to write them out, and schedules
891 // as many goroutines as necessary to accomplish this task. This call then
892 // blocks, waiting on the writes to complete. Note that we use the sem parameter
893 // to limit the number of concurrent writes taking place.
894 func writeBlocks(ctxt *Link, out *OutBuf, sem chan int, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
895 for i, s := range syms {
896 if ldr.SymValue(s) >= addr && !ldr.AttrSubSymbol(s) {
902 var wg sync.WaitGroup
903 max, lastAddr, written := int64(blockSize), addr+size, int64(0)
904 for addr < lastAddr {
905 // Find the last symbol we'd write.
907 for i, s := range syms {
908 if ldr.AttrSubSymbol(s) {
912 // If the next symbol's size would put us out of bounds on the total length,
914 end := ldr.SymValue(s) + ldr.SymSize(s)
919 // We're gonna write this symbol.
922 // If we cross over the max size, we've got enough symbols.
928 // If we didn't find any symbols to write, we're done here.
933 // Compute the length to write, including padding.
934 // We need to write to the end address (lastAddr), or the next symbol's
935 // start address, whichever comes first. If there is no more symbols,
936 // just write to lastAddr. This ensures we don't leave holes between the
937 // blocks or at the end.
939 if idx+1 < len(syms) {
940 // Find the next top-level symbol.
941 // Skip over sub symbols so we won't split a container symbol
944 for ldr.AttrSubSymbol(next) {
948 length = ldr.SymValue(next) - addr
950 if length == 0 || length > lastAddr-addr {
951 length = lastAddr - addr
954 // Start the block output operator.
955 if o, err := out.View(uint64(out.Offset() + written)); err == nil {
958 go func(o *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
959 writeBlock(ctxt, o, ldr, syms, addr, size, pad)
962 }(o, ldr, syms, addr, length, pad)
963 } else { // output not mmaped, don't parallelize.
964 writeBlock(ctxt, out, ldr, syms, addr, length, pad)
967 // Prepare for the next loop.
977 func writeBlock(ctxt *Link, out *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
979 st := ctxt.makeRelocSymState()
981 // This doesn't distinguish the memory size from the file
982 // size, and it lays out the file based on Symbol.Value, which
983 // is the virtual address. DWARF compression changes file sizes,
984 // so dwarfcompress will fix this up later if necessary.
986 for _, s := range syms {
987 if ldr.AttrSubSymbol(s) {
990 val := ldr.SymValue(s)
995 ldr.Errorf(s, "phase error: addr=%#x but sym=%#x type=%v sect=%v", addr, val, ldr.SymType(s), ldr.SymSect(s).Name)
999 out.WriteStringPad("", int(val-addr), pad)
1002 P := out.WriteSym(ldr, s)
1004 if f, ok := ctxt.generatorSyms[s]; ok {
1007 addr += int64(len(P))
1008 siz := ldr.SymSize(s)
1010 out.WriteStringPad("", int(val+siz-addr), pad)
1013 if addr != val+siz {
1014 ldr.Errorf(s, "phase error: addr=%#x value+size=%#x", addr, val+siz)
1017 if val+siz >= eaddr {
1023 out.WriteStringPad("", int(eaddr-addr), pad)
1027 type writeFn func(*Link, *OutBuf, int64, int64)
1029 // writeParallel handles scheduling parallel execution of data write functions.
1030 func writeParallel(wg *sync.WaitGroup, fn writeFn, ctxt *Link, seek, vaddr, length uint64) {
1031 if out, err := ctxt.Out.View(seek); err != nil {
1032 ctxt.Out.SeekSet(int64(seek))
1033 fn(ctxt, ctxt.Out, int64(vaddr), int64(length))
1038 fn(ctxt, out, int64(vaddr), int64(length))
1043 func datblk(ctxt *Link, out *OutBuf, addr, size int64) {
1044 writeDatblkToOutBuf(ctxt, out, addr, size)
1047 // Used only on Wasm for now.
1048 func DatblkBytes(ctxt *Link, addr int64, size int64) []byte {
1049 buf := make([]byte, size)
1050 out := &OutBuf{heap: buf}
1051 writeDatblkToOutBuf(ctxt, out, addr, size)
1055 func writeDatblkToOutBuf(ctxt *Link, out *OutBuf, addr int64, size int64) {
1056 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.datap, addr, size, zeros[:])
1059 func dwarfblk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1060 // Concatenate the section symbol lists into a single list to pass
1063 // NB: ideally we would do a separate writeBlocks call for each
1064 // section, but this would run the risk of undoing any file offset
1065 // adjustments made during layout.
1067 for i := range dwarfp {
1068 n += len(dwarfp[i].syms)
1070 syms := make([]loader.Sym, 0, n)
1071 for i := range dwarfp {
1072 syms = append(syms, dwarfp[i].syms...)
1074 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, syms, addr, size, zeros[:])
1080 strdata = make(map[string]string)
1084 func addstrdata1(ctxt *Link, arg string) {
1085 eq := strings.Index(arg, "=")
1086 dot := strings.LastIndex(arg[:eq+1], ".")
1087 if eq < 0 || dot < 0 {
1088 Exitf("-X flag requires argument of the form importpath.name=value")
1091 if ctxt.BuildMode == BuildModePlugin && pkg == "main" {
1092 pkg = *flagPluginPath
1094 pkg = objabi.PathToPrefix(pkg)
1095 name := pkg + arg[dot:eq]
1097 if _, ok := strdata[name]; !ok {
1098 strnames = append(strnames, name)
1100 strdata[name] = value
1103 // addstrdata sets the initial value of the string variable name to value.
1104 func addstrdata(arch *sys.Arch, l *loader.Loader, name, value string) {
1105 s := l.Lookup(name, 0)
1109 if goType := l.SymGoType(s); goType == 0 {
1111 } else if typeName := l.SymName(goType); typeName != "type:string" {
1112 Errorf(nil, "%s: cannot set with -X: not a var of type string (%s)", name, typeName)
1115 if !l.AttrReachable(s) {
1116 return // don't bother setting unreachable variable
1118 bld := l.MakeSymbolUpdater(s)
1119 if bld.Type() == sym.SBSS {
1120 bld.SetType(sym.SDATA)
1123 p := fmt.Sprintf("%s.str", name)
1124 sbld := l.CreateSymForUpdate(p, 0)
1125 sbld.Addstring(value)
1126 sbld.SetType(sym.SRODATA)
1129 bld.SetData(make([]byte, 0, arch.PtrSize*2))
1130 bld.SetReadOnly(false)
1132 bld.AddAddrPlus(arch, sbld.Sym(), 0)
1133 bld.AddUint(arch, uint64(len(value)))
1136 func (ctxt *Link) dostrdata() {
1137 for _, name := range strnames {
1138 addstrdata(ctxt.Arch, ctxt.loader, name, strdata[name])
1142 // addgostring adds str, as a Go string value, to s. symname is the name of the
1143 // symbol used to define the string data and must be unique per linked object.
1144 func addgostring(ctxt *Link, ldr *loader.Loader, s *loader.SymbolBuilder, symname, str string) {
1145 sdata := ldr.CreateSymForUpdate(symname, 0)
1146 if sdata.Type() != sym.Sxxx {
1147 ctxt.Errorf(s.Sym(), "duplicate symname in addgostring: %s", symname)
1149 sdata.SetLocal(true)
1150 sdata.SetType(sym.SRODATA)
1151 sdata.SetSize(int64(len(str)))
1152 sdata.SetData([]byte(str))
1153 s.AddAddr(ctxt.Arch, sdata.Sym())
1154 s.AddUint(ctxt.Arch, uint64(len(str)))
1157 func addinitarrdata(ctxt *Link, ldr *loader.Loader, s loader.Sym) {
1158 p := ldr.SymName(s) + ".ptr"
1159 sp := ldr.CreateSymForUpdate(p, 0)
1160 sp.SetType(sym.SINITARR)
1162 sp.SetDuplicateOK(true)
1163 sp.AddAddr(ctxt.Arch, s)
1166 // symalign returns the required alignment for the given symbol s.
1167 func symalign(ldr *loader.Loader, s loader.Sym) int32 {
1168 min := int32(thearch.Minalign)
1169 align := ldr.SymAlign(s)
1172 } else if align != 0 {
1175 align = int32(thearch.Maxalign)
1176 ssz := ldr.SymSize(s)
1177 for int64(align) > ssz && align > min {
1180 ldr.SetSymAlign(s, align)
1184 func aligndatsize(state *dodataState, datsize int64, s loader.Sym) int64 {
1185 return Rnd(datsize, int64(symalign(state.ctxt.loader, s)))
1188 const debugGCProg = false
1190 type GCProg struct {
1192 sym *loader.SymbolBuilder
1196 func (p *GCProg) Init(ctxt *Link, name string) {
1198 p.sym = ctxt.loader.CreateSymForUpdate(name, 0)
1199 p.w.Init(p.writeByte())
1201 fmt.Fprintf(os.Stderr, "ld: start GCProg %s\n", name)
1202 p.w.Debug(os.Stderr)
1206 func (p *GCProg) writeByte() func(x byte) {
1207 return func(x byte) {
1212 func (p *GCProg) End(size int64) {
1213 p.w.ZeroUntil(size / int64(p.ctxt.Arch.PtrSize))
1216 fmt.Fprintf(os.Stderr, "ld: end GCProg\n")
1220 func (p *GCProg) AddSym(s loader.Sym) {
1221 ldr := p.ctxt.loader
1222 typ := ldr.SymGoType(s)
1224 // Things without pointers should be in sym.SNOPTRDATA or sym.SNOPTRBSS;
1225 // everything we see should have pointers and should therefore have a type.
1227 switch ldr.SymName(s) {
1228 case "runtime.data", "runtime.edata", "runtime.bss", "runtime.ebss":
1229 // Ignore special symbols that are sometimes laid out
1230 // as real symbols. See comment about dyld on darwin in
1231 // the address function.
1234 p.ctxt.Errorf(p.sym.Sym(), "missing Go type information for global symbol %s: size %d", ldr.SymName(s), ldr.SymSize(s))
1238 ptrsize := int64(p.ctxt.Arch.PtrSize)
1239 typData := ldr.Data(typ)
1240 nptr := decodetypePtrdata(p.ctxt.Arch, typData) / ptrsize
1243 fmt.Fprintf(os.Stderr, "gcprog sym: %s at %d (ptr=%d+%d)\n", ldr.SymName(s), ldr.SymValue(s), ldr.SymValue(s)/ptrsize, nptr)
1246 sval := ldr.SymValue(s)
1247 if decodetypeUsegcprog(p.ctxt.Arch, typData) == 0 {
1248 // Copy pointers from mask into program.
1249 mask := decodetypeGcmask(p.ctxt, typ)
1250 for i := int64(0); i < nptr; i++ {
1251 if (mask[i/8]>>uint(i%8))&1 != 0 {
1252 p.w.Ptr(sval/ptrsize + i)
1259 prog := decodetypeGcprog(p.ctxt, typ)
1260 p.w.ZeroUntil(sval / ptrsize)
1261 p.w.Append(prog[4:], nptr)
1264 // cutoff is the maximum data section size permitted by the linker
1265 // (see issue #9862).
1266 const cutoff = 2e9 // 2 GB (or so; looks better in errors than 2^31)
1268 func (state *dodataState) checkdatsize(symn sym.SymKind) {
1269 if state.datsize > cutoff {
1270 Errorf(nil, "too much data in section %v (over %v bytes)", symn, cutoff)
1274 // fixZeroSizedSymbols gives a few special symbols with zero size some space.
1275 func fixZeroSizedSymbols(ctxt *Link) {
1276 // The values in moduledata are filled out by relocations
1277 // pointing to the addresses of these special symbols.
1278 // Typically these symbols have no size and are not laid
1279 // out with their matching section.
1281 // However on darwin, dyld will find the special symbol
1282 // in the first loaded module, even though it is local.
1284 // (An hypothesis, formed without looking in the dyld sources:
1285 // these special symbols have no size, so their address
1286 // matches a real symbol. The dynamic linker assumes we
1287 // want the normal symbol with the same address and finds
1288 // it in the other module.)
1290 // To work around this we lay out the symbls whose
1291 // addresses are vital for multi-module programs to work
1292 // as normal symbols, and give them a little size.
1294 // On AIX, as all DATA sections are merged together, ld might not put
1295 // these symbols at the beginning of their respective section if there
1296 // aren't real symbols, their alignment might not match the
1297 // first symbol alignment. Therefore, there are explicitly put at the
1298 // beginning of their section with the same alignment.
1299 if !(ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) && !(ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
1304 bss := ldr.CreateSymForUpdate("runtime.bss", 0)
1306 ldr.SetAttrSpecial(bss.Sym(), false)
1308 ebss := ldr.CreateSymForUpdate("runtime.ebss", 0)
1309 ldr.SetAttrSpecial(ebss.Sym(), false)
1311 data := ldr.CreateSymForUpdate("runtime.data", 0)
1313 ldr.SetAttrSpecial(data.Sym(), false)
1315 edata := ldr.CreateSymForUpdate("runtime.edata", 0)
1316 ldr.SetAttrSpecial(edata.Sym(), false)
1318 if ctxt.HeadType == objabi.Haix {
1319 // XCOFFTOC symbols are part of .data section.
1320 edata.SetType(sym.SXCOFFTOC)
1323 types := ldr.CreateSymForUpdate("runtime.types", 0)
1324 types.SetType(sym.STYPE)
1326 ldr.SetAttrSpecial(types.Sym(), false)
1328 etypes := ldr.CreateSymForUpdate("runtime.etypes", 0)
1329 etypes.SetType(sym.SFUNCTAB)
1330 ldr.SetAttrSpecial(etypes.Sym(), false)
1332 if ctxt.HeadType == objabi.Haix {
1333 rodata := ldr.CreateSymForUpdate("runtime.rodata", 0)
1334 rodata.SetType(sym.SSTRING)
1336 ldr.SetAttrSpecial(rodata.Sym(), false)
1338 erodata := ldr.CreateSymForUpdate("runtime.erodata", 0)
1339 ldr.SetAttrSpecial(erodata.Sym(), false)
1343 // makeRelroForSharedLib creates a section of readonly data if necessary.
1344 func (state *dodataState) makeRelroForSharedLib(target *Link) {
1345 if !target.UseRelro() {
1349 // "read only" data with relocations needs to go in its own section
1350 // when building a shared library. We do this by boosting objects of
1351 // type SXXX with relocations to type SXXXRELRO.
1352 ldr := target.loader
1353 for _, symnro := range sym.ReadOnly {
1354 symnrelro := sym.RelROMap[symnro]
1356 ro := []loader.Sym{}
1357 relro := state.data[symnrelro]
1359 for _, s := range state.data[symnro] {
1360 relocs := ldr.Relocs(s)
1361 isRelro := relocs.Count() > 0
1362 switch state.symType(s) {
1363 case sym.STYPE, sym.STYPERELRO, sym.SGOFUNCRELRO:
1364 // Symbols are not sorted yet, so it is possible
1365 // that an Outer symbol has been changed to a
1366 // relro Type before it reaches here.
1369 if ldr.SymName(s) == "runtime.etypes" {
1370 // runtime.etypes must be at the end of
1375 // The only SGOFUNC symbols that contain relocations are .stkobj,
1376 // and their relocations are of type objabi.R_ADDROFF,
1377 // which always get resolved during linking.
1381 state.setSymType(s, symnrelro)
1382 if outer := ldr.OuterSym(s); outer != 0 {
1383 state.setSymType(outer, symnrelro)
1385 relro = append(relro, s)
1391 // Check that we haven't made two symbols with the same .Outer into
1392 // different types (because references two symbols with non-nil Outer
1393 // become references to the outer symbol + offset it's vital that the
1394 // symbol and the outer end up in the same section).
1395 for _, s := range relro {
1396 if outer := ldr.OuterSym(s); outer != 0 {
1397 st := state.symType(s)
1398 ost := state.symType(outer)
1400 state.ctxt.Errorf(s, "inconsistent types for symbol and its Outer %s (%v != %v)",
1401 ldr.SymName(outer), st, ost)
1406 state.data[symnro] = ro
1407 state.data[symnrelro] = relro
1411 // dodataState holds bits of state information needed by dodata() and the
1412 // various helpers it calls. The lifetime of these items should not extend
1413 // past the end of dodata().
1414 type dodataState struct {
1417 // Data symbols bucketed by type.
1418 data [sym.SXREF][]loader.Sym
1419 // Max alignment for each flavor of data symbol.
1420 dataMaxAlign [sym.SXREF]int32
1421 // Overridden sym type
1422 symGroupType []sym.SymKind
1423 // Current data size so far.
1427 // A note on symType/setSymType below:
1429 // In the legacy linker, the types of symbols (notably data symbols) are
1430 // changed during the symtab() phase so as to insure that similar symbols
1431 // are bucketed together, then their types are changed back again during
1432 // dodata. Symbol to section assignment also plays tricks along these lines
1433 // in the case where a relro segment is needed.
1435 // The value returned from setType() below reflects the effects of
1436 // any overrides made by symtab and/or dodata.
1438 // symType returns the (possibly overridden) type of 's'.
1439 func (state *dodataState) symType(s loader.Sym) sym.SymKind {
1440 if int(s) < len(state.symGroupType) {
1441 if override := state.symGroupType[s]; override != 0 {
1445 return state.ctxt.loader.SymType(s)
1448 // setSymType sets a new override type for 's'.
1449 func (state *dodataState) setSymType(s loader.Sym, kind sym.SymKind) {
1453 if int(s) < len(state.symGroupType) {
1454 state.symGroupType[s] = kind
1456 su := state.ctxt.loader.MakeSymbolUpdater(s)
1461 func (ctxt *Link) dodata(symGroupType []sym.SymKind) {
1463 // Give zeros sized symbols space if necessary.
1464 fixZeroSizedSymbols(ctxt)
1466 // Collect data symbols by type into data.
1467 state := dodataState{ctxt: ctxt, symGroupType: symGroupType}
1469 for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
1470 if !ldr.AttrReachable(s) || ldr.AttrSpecial(s) || ldr.AttrSubSymbol(s) ||
1471 !ldr.TopLevelSym(s) {
1475 st := state.symType(s)
1477 if st <= sym.STEXT || st >= sym.SXREF {
1480 state.data[st] = append(state.data[st], s)
1482 // Similarly with checking the onlist attr.
1483 if ldr.AttrOnList(s) {
1484 log.Fatalf("symbol %s listed multiple times", ldr.SymName(s))
1486 ldr.SetAttrOnList(s, true)
1489 // Now that we have the data symbols, but before we start
1490 // to assign addresses, record all the necessary
1491 // dynamic relocations. These will grow the relocation
1492 // symbol, which is itself data.
1494 // On darwin, we need the symbol table numbers for dynreloc.
1495 if ctxt.HeadType == objabi.Hdarwin {
1498 state.dynreloc(ctxt)
1500 // Move any RO data with relocations to a separate section.
1501 state.makeRelroForSharedLib(ctxt)
1503 // Set alignment for the symbol with the largest known index,
1504 // so as to trigger allocation of the loader's internal
1505 // alignment array. This will avoid data races in the parallel
1507 lastSym := loader.Sym(ldr.NSym() - 1)
1508 ldr.SetSymAlign(lastSym, ldr.SymAlign(lastSym))
1511 var wg sync.WaitGroup
1512 for symn := range state.data {
1513 symn := sym.SymKind(symn)
1516 state.data[symn], state.dataMaxAlign[symn] = state.dodataSect(ctxt, symn, state.data[symn])
1523 // Make .rela and .rela.plt contiguous, the ELF ABI requires this
1524 // and Solaris actually cares.
1525 syms := state.data[sym.SELFROSECT]
1526 reli, plti := -1, -1
1527 for i, s := range syms {
1528 switch ldr.SymName(s) {
1529 case ".rel.plt", ".rela.plt":
1531 case ".rel", ".rela":
1535 if reli >= 0 && plti >= 0 && plti != reli+1 {
1536 var first, second int
1538 first, second = reli, plti
1540 first, second = plti, reli
1542 rel, plt := syms[reli], syms[plti]
1543 copy(syms[first+2:], syms[first+1:second])
1547 // Make sure alignment doesn't introduce a gap.
1548 // Setting the alignment explicitly prevents
1549 // symalign from basing it on the size and
1550 // getting it wrong.
1551 ldr.SetSymAlign(rel, int32(ctxt.Arch.RegSize))
1552 ldr.SetSymAlign(plt, int32(ctxt.Arch.RegSize))
1554 state.data[sym.SELFROSECT] = syms
1557 if ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal {
1558 // These symbols must have the same alignment as their section.
1559 // Otherwise, ld might change the layout of Go sections.
1560 ldr.SetSymAlign(ldr.Lookup("runtime.data", 0), state.dataMaxAlign[sym.SDATA])
1561 ldr.SetSymAlign(ldr.Lookup("runtime.bss", 0), state.dataMaxAlign[sym.SBSS])
1564 // Create *sym.Section objects and assign symbols to sections for
1565 // data/rodata (and related) symbols.
1566 state.allocateDataSections(ctxt)
1568 // Create *sym.Section objects and assign symbols to sections for
1570 state.allocateDwarfSections(ctxt)
1572 /* number the sections */
1575 for _, sect := range Segtext.Sections {
1579 for _, sect := range Segrodata.Sections {
1583 for _, sect := range Segrelrodata.Sections {
1587 for _, sect := range Segdata.Sections {
1591 for _, sect := range Segdwarf.Sections {
1597 // allocateDataSectionForSym creates a new sym.Section into which a a
1598 // single symbol will be placed. Here "seg" is the segment into which
1599 // the section will go, "s" is the symbol to be placed into the new
1600 // section, and "rwx" contains permissions for the section.
1601 func (state *dodataState) allocateDataSectionForSym(seg *sym.Segment, s loader.Sym, rwx int) *sym.Section {
1602 ldr := state.ctxt.loader
1603 sname := ldr.SymName(s)
1604 sect := addsection(ldr, state.ctxt.Arch, seg, sname, rwx)
1605 sect.Align = symalign(ldr, s)
1606 state.datsize = Rnd(state.datsize, int64(sect.Align))
1607 sect.Vaddr = uint64(state.datsize)
1611 // allocateNamedDataSection creates a new sym.Section for a category
1612 // of data symbols. Here "seg" is the segment into which the section
1613 // will go, "sName" is the name to give to the section, "types" is a
1614 // range of symbol types to be put into the section, and "rwx"
1615 // contains permissions for the section.
1616 func (state *dodataState) allocateNamedDataSection(seg *sym.Segment, sName string, types []sym.SymKind, rwx int) *sym.Section {
1617 sect := addsection(state.ctxt.loader, state.ctxt.Arch, seg, sName, rwx)
1618 if len(types) == 0 {
1620 } else if len(types) == 1 {
1621 sect.Align = state.dataMaxAlign[types[0]]
1623 for _, symn := range types {
1624 align := state.dataMaxAlign[symn]
1625 if sect.Align < align {
1630 state.datsize = Rnd(state.datsize, int64(sect.Align))
1631 sect.Vaddr = uint64(state.datsize)
1635 // assignDsymsToSection assigns a collection of data symbols to a
1636 // newly created section. "sect" is the section into which to place
1637 // the symbols, "syms" holds the list of symbols to assign,
1638 // "forceType" (if non-zero) contains a new sym type to apply to each
1639 // sym during the assignment, and "aligner" is a hook to call to
1640 // handle alignment during the assignment process.
1641 func (state *dodataState) assignDsymsToSection(sect *sym.Section, syms []loader.Sym, forceType sym.SymKind, aligner func(state *dodataState, datsize int64, s loader.Sym) int64) {
1642 ldr := state.ctxt.loader
1643 for _, s := range syms {
1644 state.datsize = aligner(state, state.datsize, s)
1645 ldr.SetSymSect(s, sect)
1646 if forceType != sym.Sxxx {
1647 state.setSymType(s, forceType)
1649 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1650 state.datsize += ldr.SymSize(s)
1652 sect.Length = uint64(state.datsize) - sect.Vaddr
1655 func (state *dodataState) assignToSection(sect *sym.Section, symn sym.SymKind, forceType sym.SymKind) {
1656 state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1657 state.checkdatsize(symn)
1660 // allocateSingleSymSections walks through the bucketed data symbols
1661 // with type 'symn', creates a new section for each sym, and assigns
1662 // the sym to a newly created section. Section name is set from the
1663 // symbol name. "Seg" is the segment into which to place the new
1664 // section, "forceType" is the new sym.SymKind to assign to the symbol
1665 // within the section, and "rwx" holds section permissions.
1666 func (state *dodataState) allocateSingleSymSections(seg *sym.Segment, symn sym.SymKind, forceType sym.SymKind, rwx int) {
1667 ldr := state.ctxt.loader
1668 for _, s := range state.data[symn] {
1669 sect := state.allocateDataSectionForSym(seg, s, rwx)
1670 ldr.SetSymSect(s, sect)
1671 state.setSymType(s, forceType)
1672 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1673 state.datsize += ldr.SymSize(s)
1674 sect.Length = uint64(state.datsize) - sect.Vaddr
1676 state.checkdatsize(symn)
1679 // allocateNamedSectionAndAssignSyms creates a new section with the
1680 // specified name, then walks through the bucketed data symbols with
1681 // type 'symn' and assigns each of them to this new section. "Seg" is
1682 // the segment into which to place the new section, "secName" is the
1683 // name to give to the new section, "forceType" (if non-zero) contains
1684 // a new sym type to apply to each sym during the assignment, and
1685 // "rwx" holds section permissions.
1686 func (state *dodataState) allocateNamedSectionAndAssignSyms(seg *sym.Segment, secName string, symn sym.SymKind, forceType sym.SymKind, rwx int) *sym.Section {
1688 sect := state.allocateNamedDataSection(seg, secName, []sym.SymKind{symn}, rwx)
1689 state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1693 // allocateDataSections allocates sym.Section objects for data/rodata
1694 // (and related) symbols, and then assigns symbols to those sections.
1695 func (state *dodataState) allocateDataSections(ctxt *Link) {
1696 // Allocate sections.
1697 // Data is processed before segtext, because we need
1698 // to see all symbols in the .data and .bss sections in order
1699 // to generate garbage collection information.
1701 // Writable data sections that do not need any specialized handling.
1702 writable := []sym.SymKind{
1709 for _, symn := range writable {
1710 state.allocateSingleSymSections(&Segdata, symn, sym.SDATA, 06)
1715 if len(state.data[sym.SELFGOT]) > 0 {
1716 state.allocateNamedSectionAndAssignSyms(&Segdata, ".got", sym.SELFGOT, sym.SDATA, 06)
1719 /* pointer-free data */
1720 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrdata", sym.SNOPTRDATA, sym.SDATA, 06)
1721 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrdata", 0), sect)
1722 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrdata", 0), sect)
1724 hasinitarr := ctxt.linkShared
1726 /* shared library initializer */
1727 switch ctxt.BuildMode {
1728 case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePlugin:
1732 if ctxt.HeadType == objabi.Haix {
1733 if len(state.data[sym.SINITARR]) > 0 {
1734 Errorf(nil, "XCOFF format doesn't allow .init_array section")
1738 if hasinitarr && len(state.data[sym.SINITARR]) > 0 {
1739 state.allocateNamedSectionAndAssignSyms(&Segdata, ".init_array", sym.SINITARR, sym.Sxxx, 06)
1743 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".data", sym.SDATA, sym.SDATA, 06)
1744 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.data", 0), sect)
1745 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.edata", 0), sect)
1746 dataGcEnd := state.datsize - int64(sect.Vaddr)
1748 // On AIX, TOC entries must be the last of .data
1749 // These aren't part of gc as they won't change during the runtime.
1750 state.assignToSection(sect, sym.SXCOFFTOC, sym.SDATA)
1751 state.checkdatsize(sym.SDATA)
1752 sect.Length = uint64(state.datsize) - sect.Vaddr
1755 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".bss", sym.SBSS, sym.Sxxx, 06)
1756 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.bss", 0), sect)
1757 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ebss", 0), sect)
1758 bssGcEnd := state.datsize - int64(sect.Vaddr)
1760 // Emit gcdata for bss symbols now that symbol values have been assigned.
1761 gcsToEmit := []struct {
1766 {"runtime.gcdata", sym.SDATA, dataGcEnd},
1767 {"runtime.gcbss", sym.SBSS, bssGcEnd},
1769 for _, g := range gcsToEmit {
1771 gc.Init(ctxt, g.symName)
1772 for _, s := range state.data[g.symKind] {
1778 /* pointer-free bss */
1779 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrbss", sym.SNOPTRBSS, sym.Sxxx, 06)
1780 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrbss", 0), sect)
1781 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrbss", 0), sect)
1782 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.end", 0), sect)
1784 // Coverage instrumentation counters for libfuzzer.
1785 if len(state.data[sym.SLIBFUZZER_8BIT_COUNTER]) > 0 {
1786 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, "__sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, sym.Sxxx, 06)
1787 ldr.SetSymSect(ldr.LookupOrCreateSym("__start___sancov_cntrs", 0), sect)
1788 ldr.SetSymSect(ldr.LookupOrCreateSym("__stop___sancov_cntrs", 0), sect)
1789 ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._counters", 0), sect)
1790 ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._ecounters", 0), sect)
1793 if len(state.data[sym.STLSBSS]) > 0 {
1794 var sect *sym.Section
1795 // FIXME: not clear why it is sometimes necessary to suppress .tbss section creation.
1796 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && (ctxt.LinkMode == LinkExternal || !*FlagD) {
1797 sect = addsection(ldr, ctxt.Arch, &Segdata, ".tbss", 06)
1798 sect.Align = int32(ctxt.Arch.PtrSize)
1799 // FIXME: why does this need to be set to zero?
1804 for _, s := range state.data[sym.STLSBSS] {
1805 state.datsize = aligndatsize(state, state.datsize, s)
1807 ldr.SetSymSect(s, sect)
1809 ldr.SetSymValue(s, state.datsize)
1810 state.datsize += ldr.SymSize(s)
1812 state.checkdatsize(sym.STLSBSS)
1815 sect.Length = uint64(state.datsize)
1820 * We finished data, begin read-only data.
1821 * Not all systems support a separate read-only non-executable data section.
1822 * ELF and Windows PE systems do.
1823 * OS X and Plan 9 do not.
1824 * And if we're using external linking mode, the point is moot,
1825 * since it's not our decision; that code expects the sections in
1828 var segro *sym.Segment
1829 if ctxt.IsELF && ctxt.LinkMode == LinkInternal {
1831 } else if ctxt.HeadType == objabi.Hwindows {
1839 /* read-only executable ELF, Mach-O sections */
1840 if len(state.data[sym.STEXT]) != 0 {
1841 culprit := ldr.SymName(state.data[sym.STEXT][0])
1842 Errorf(nil, "dodata found an sym.STEXT symbol: %s", culprit)
1844 state.allocateSingleSymSections(&Segtext, sym.SELFRXSECT, sym.SRODATA, 05)
1845 state.allocateSingleSymSections(&Segtext, sym.SMACHOPLT, sym.SRODATA, 05)
1847 /* read-only data */
1848 sect = state.allocateNamedDataSection(segro, ".rodata", sym.ReadOnly, 04)
1849 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.rodata", 0), sect)
1850 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.erodata", 0), sect)
1851 if !ctxt.UseRelro() {
1852 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
1853 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
1855 for _, symn := range sym.ReadOnly {
1856 symnStartValue := state.datsize
1857 if len(state.data[symn]) != 0 {
1858 symnStartValue = aligndatsize(state, symnStartValue, state.data[symn][0])
1860 state.assignToSection(sect, symn, sym.SRODATA)
1861 setCarrierSize(symn, state.datsize-symnStartValue)
1862 if ctxt.HeadType == objabi.Haix {
1863 // Read-only symbols might be wrapped inside their outer
1865 // XCOFF symbol table needs to know the size of
1866 // these outer symbols.
1867 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
1871 /* read-only ELF, Mach-O sections */
1872 state.allocateSingleSymSections(segro, sym.SELFROSECT, sym.SRODATA, 04)
1874 // There is some data that are conceptually read-only but are written to by
1875 // relocations. On GNU systems, we can arrange for the dynamic linker to
1876 // mprotect sections after relocations are applied by giving them write
1877 // permissions in the object file and calling them ".data.rel.ro.FOO". We
1878 // divide the .rodata section between actual .rodata and .data.rel.ro.rodata,
1879 // but for the other sections that this applies to, we just write a read-only
1880 // .FOO section or a read-write .data.rel.ro.FOO section depending on the
1882 // TODO(mwhudson): It would make sense to do this more widely, but it makes
1883 // the system linker segfault on darwin.
1884 const relroPerm = 06
1885 const fallbackPerm = 04
1886 relroSecPerm := fallbackPerm
1887 genrelrosecname := func(suffix string) string {
1895 if ctxt.UseRelro() {
1896 segrelro := &Segrelrodata
1897 if ctxt.LinkMode == LinkExternal && !ctxt.IsAIX() && !ctxt.IsDarwin() {
1898 // Using a separate segment with an external
1899 // linker results in some programs moving
1900 // their data sections unexpectedly, which
1901 // corrupts the moduledata. So we use the
1902 // rodata segment and let the external linker
1903 // sort out a rel.ro segment.
1906 // Reset datsize for new segment.
1910 if !ctxt.IsDarwin() { // We don't need the special names on darwin.
1911 genrelrosecname = func(suffix string) string {
1912 return ".data.rel.ro" + suffix
1916 relroReadOnly := []sym.SymKind{}
1917 for _, symnro := range sym.ReadOnly {
1918 symn := sym.RelROMap[symnro]
1919 relroReadOnly = append(relroReadOnly, symn)
1922 relroSecPerm = relroPerm
1924 /* data only written by relocations */
1925 sect = state.allocateNamedDataSection(segrelro, genrelrosecname(""), relroReadOnly, relroSecPerm)
1927 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
1928 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
1930 for i, symnro := range sym.ReadOnly {
1931 if i == 0 && symnro == sym.STYPE && ctxt.HeadType != objabi.Haix {
1932 // Skip forward so that no type
1933 // reference uses a zero offset.
1934 // This is unlikely but possible in small
1935 // programs with no other read-only data.
1939 symn := sym.RelROMap[symnro]
1940 symnStartValue := state.datsize
1941 if len(state.data[symn]) != 0 {
1942 symnStartValue = aligndatsize(state, symnStartValue, state.data[symn][0])
1945 for _, s := range state.data[symn] {
1946 outer := ldr.OuterSym(s)
1947 if s != 0 && ldr.SymSect(outer) != nil && ldr.SymSect(outer) != sect {
1948 ctxt.Errorf(s, "s.Outer (%s) in different section from s, %s != %s", ldr.SymName(outer), ldr.SymSect(outer).Name, sect.Name)
1951 state.assignToSection(sect, symn, sym.SRODATA)
1952 setCarrierSize(symn, state.datsize-symnStartValue)
1953 if ctxt.HeadType == objabi.Haix {
1954 // Read-only symbols might be wrapped inside their outer
1956 // XCOFF symbol table needs to know the size of
1957 // these outer symbols.
1958 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
1962 sect.Length = uint64(state.datsize) - sect.Vaddr
1966 sect = state.allocateNamedDataSection(seg, genrelrosecname(".typelink"), []sym.SymKind{sym.STYPELINK}, relroSecPerm)
1968 typelink := ldr.CreateSymForUpdate("runtime.typelink", 0)
1969 ldr.SetSymSect(typelink.Sym(), sect)
1970 typelink.SetType(sym.SRODATA)
1971 state.datsize += typelink.Size()
1972 state.checkdatsize(sym.STYPELINK)
1973 sect.Length = uint64(state.datsize) - sect.Vaddr
1976 sect = state.allocateNamedDataSection(seg, genrelrosecname(".itablink"), []sym.SymKind{sym.SITABLINK}, relroSecPerm)
1978 itablink := ldr.CreateSymForUpdate("runtime.itablink", 0)
1979 ldr.SetSymSect(itablink.Sym(), sect)
1980 itablink.SetType(sym.SRODATA)
1981 state.datsize += itablink.Size()
1982 state.checkdatsize(sym.SITABLINK)
1983 sect.Length = uint64(state.datsize) - sect.Vaddr
1986 sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gosymtab"), sym.SSYMTAB, sym.SRODATA, relroSecPerm)
1987 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.symtab", 0), sect)
1988 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.esymtab", 0), sect)
1991 sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gopclntab"), sym.SPCLNTAB, sym.SRODATA, relroSecPerm)
1992 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0), sect)
1993 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pcheader", 0), sect)
1994 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.funcnametab", 0), sect)
1995 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.cutab", 0), sect)
1996 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.filetab", 0), sect)
1997 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pctab", 0), sect)
1998 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.functab", 0), sect)
1999 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.epclntab", 0), sect)
2000 setCarrierSize(sym.SPCLNTAB, int64(sect.Length))
2001 if ctxt.HeadType == objabi.Haix {
2002 xcoffUpdateOuterSize(ctxt, int64(sect.Length), sym.SPCLNTAB)
2005 // 6g uses 4-byte relocation offsets, so the entire segment must fit in 32 bits.
2006 if state.datsize != int64(uint32(state.datsize)) {
2007 Errorf(nil, "read-only data segment too large: %d", state.datsize)
2011 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
2012 siz += len(state.data[symn])
2014 ctxt.datap = make([]loader.Sym, 0, siz)
2015 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
2016 ctxt.datap = append(ctxt.datap, state.data[symn]...)
2020 // allocateDwarfSections allocates sym.Section objects for DWARF
2021 // symbols, and assigns symbols to sections.
2022 func (state *dodataState) allocateDwarfSections(ctxt *Link) {
2024 alignOne := func(state *dodataState, datsize int64, s loader.Sym) int64 { return datsize }
2027 for i := 0; i < len(dwarfp); i++ {
2028 // First the section symbol.
2029 s := dwarfp[i].secSym()
2030 sect := state.allocateNamedDataSection(&Segdwarf, ldr.SymName(s), []sym.SymKind{}, 04)
2031 ldr.SetSymSect(s, sect)
2032 sect.Sym = sym.LoaderSym(s)
2033 curType := ldr.SymType(s)
2034 state.setSymType(s, sym.SRODATA)
2035 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
2036 state.datsize += ldr.SymSize(s)
2038 // Then any sub-symbols for the section symbol.
2039 subSyms := dwarfp[i].subSyms()
2040 state.assignDsymsToSection(sect, subSyms, sym.SRODATA, alignOne)
2042 for j := 0; j < len(subSyms); j++ {
2044 if ctxt.HeadType == objabi.Haix && curType == sym.SDWARFLOC {
2045 // Update the size of .debug_loc for this symbol's
2047 addDwsectCUSize(".debug_loc", ldr.SymPkg(s), uint64(ldr.SymSize(s)))
2050 sect.Length = uint64(state.datsize) - sect.Vaddr
2051 state.checkdatsize(curType)
2055 type symNameSize struct {
2062 func (state *dodataState) dodataSect(ctxt *Link, symn sym.SymKind, syms []loader.Sym) (result []loader.Sym, maxAlign int32) {
2063 var head, tail loader.Sym
2065 sl := make([]symNameSize, len(syms))
2066 for k, s := range syms {
2067 ss := ldr.SymSize(s)
2068 sl[k] = symNameSize{name: ldr.SymName(s), sz: ss, sym: s}
2069 ds := int64(len(ldr.Data(s)))
2072 ctxt.Errorf(s, "initialize bounds (%d < %d)", ss, ds)
2074 ctxt.Errorf(s, "negative size (%d bytes)", ss)
2076 ctxt.Errorf(s, "symbol too large (%d bytes)", ss)
2079 // If the usually-special section-marker symbols are being laid
2080 // out as regular symbols, put them either at the beginning or
2081 // end of their section.
2082 if (ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) || (ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
2083 switch ldr.SymName(s) {
2084 case "runtime.text", "runtime.bss", "runtime.data", "runtime.types", "runtime.rodata":
2087 case "runtime.etext", "runtime.ebss", "runtime.edata", "runtime.etypes", "runtime.erodata":
2094 // For ppc64, we want to interleave the .got and .toc sections
2095 // from input files. Both are type sym.SELFGOT, so in that case
2096 // we skip size comparison and fall through to the name
2097 // comparison (conveniently, .got sorts before .toc).
2098 checkSize := symn != sym.SELFGOT
2100 // Perform the sort.
2101 if symn != sym.SPCLNTAB {
2102 sort.Slice(sl, func(i, j int) bool {
2103 si, sj := sl[i].sym, sl[j].sym
2105 case si == head, sj == tail:
2107 case sj == head, si == tail:
2120 return iname < jname
2125 // PCLNTAB was built internally, and already has the proper order.
2128 // Set alignment, construct result
2132 if s != head && s != tail {
2133 align := symalign(ldr, s)
2134 if maxAlign < align {
2138 syms = append(syms, s)
2141 return syms, maxAlign
2144 // Add buildid to beginning of text segment, on non-ELF systems.
2145 // Non-ELF binary formats are not always flexible enough to
2146 // give us a place to put the Go build ID. On those systems, we put it
2147 // at the very beginning of the text segment.
2148 // This “header” is read by cmd/go.
2149 func (ctxt *Link) textbuildid() {
2150 if ctxt.IsELF || ctxt.BuildMode == BuildModePlugin || *flagBuildid == "" {
2155 s := ldr.CreateSymForUpdate("go:buildid", 0)
2156 // The \xff is invalid UTF-8, meant to make it less likely
2157 // to find one of these accidentally.
2158 data := "\xff Go build ID: " + strconv.Quote(*flagBuildid) + "\n \xff"
2159 s.SetType(sym.STEXT)
2160 s.SetData([]byte(data))
2161 s.SetSize(int64(len(data)))
2163 ctxt.Textp = append(ctxt.Textp, 0)
2164 copy(ctxt.Textp[1:], ctxt.Textp)
2165 ctxt.Textp[0] = s.Sym()
2168 func (ctxt *Link) buildinfo() {
2169 if ctxt.linkShared || ctxt.BuildMode == BuildModePlugin {
2170 // -linkshared and -buildmode=plugin get confused
2171 // about the relocations in go.buildinfo
2172 // pointing at the other data sections.
2173 // The version information is only available in executables.
2177 // Write the buildinfo symbol, which go version looks for.
2178 // The code reading this data is in package debug/buildinfo.
2180 s := ldr.CreateSymForUpdate(".go.buildinfo", 0)
2181 s.SetType(sym.SBUILDINFO)
2183 // The \xff is invalid UTF-8, meant to make it less likely
2184 // to find one of these accidentally.
2185 const prefix = "\xff Go buildinf:" // 14 bytes, plus 2 data bytes filled in below
2186 data := make([]byte, 32)
2188 data[len(prefix)] = byte(ctxt.Arch.PtrSize)
2189 data[len(prefix)+1] = 0
2190 if ctxt.Arch.ByteOrder == binary.BigEndian {
2191 data[len(prefix)+1] = 1
2193 data[len(prefix)+1] |= 2 // signals new pointer-free format
2194 data = appendString(data, strdata["runtime.buildVersion"])
2195 data = appendString(data, strdata["runtime.modinfo"])
2196 // MacOS linker gets very upset if the size os not a multiple of alignment.
2197 for len(data)%16 != 0 {
2198 data = append(data, 0)
2201 s.SetSize(int64(len(data)))
2204 // appendString appends s to data, prefixed by its varint-encoded length.
2205 func appendString(data []byte, s string) []byte {
2206 var v [binary.MaxVarintLen64]byte
2207 n := binary.PutUvarint(v[:], uint64(len(s)))
2208 data = append(data, v[:n]...)
2209 data = append(data, s...)
2213 // assign addresses to text
2214 func (ctxt *Link) textaddress() {
2215 addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2217 // Assign PCs in text segment.
2218 // Could parallelize, by assigning to text
2219 // and then letting threads copy down, but probably not worth it.
2220 sect := Segtext.Sections[0]
2222 sect.Align = int32(Funcalign)
2226 text := ctxt.xdefine("runtime.text", sym.STEXT, 0)
2227 etext := ctxt.xdefine("runtime.etext", sym.STEXT, 0)
2228 ldr.SetSymSect(text, sect)
2229 if ctxt.IsAIX() && ctxt.IsExternal() {
2230 // Setting runtime.text has a real symbol prevents ld to
2231 // change its base address resulting in wrong offsets for
2233 u := ldr.MakeSymbolUpdater(text)
2234 u.SetAlign(sect.Align)
2238 if (ctxt.DynlinkingGo() && ctxt.IsDarwin()) || (ctxt.IsAIX() && ctxt.IsExternal()) {
2239 ldr.SetSymSect(etext, sect)
2240 ctxt.Textp = append(ctxt.Textp, etext, 0)
2241 copy(ctxt.Textp[1:], ctxt.Textp)
2242 ctxt.Textp[0] = text
2245 start := uint64(Rnd(*FlagTextAddr, int64(Funcalign)))
2250 limit := thearch.TrampLimit
2252 limit = 1 << 63 // unlimited
2254 if *FlagDebugTextSize != 0 {
2255 limit = uint64(*FlagDebugTextSize)
2257 if *FlagDebugTramp > 1 {
2258 limit = 1 // debug mode, force generating trampolines for everything
2261 if ctxt.IsAIX() && ctxt.IsExternal() {
2262 // On AIX, normally we won't generate direct calls to external symbols,
2263 // except in one test, cmd/go/testdata/script/link_syso_issue33139.txt.
2264 // That test doesn't make much sense, and I'm not sure it ever works.
2265 // Just generate trampoline for now (which will turn a direct call to
2266 // an indirect call, which at least builds).
2270 // First pass: assign addresses assuming the program is small and
2271 // don't generate trampolines.
2273 for _, s := range ctxt.Textp {
2274 sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
2275 if va-start >= limit {
2281 // Second pass: only if it is too big, insert trampolines for too-far
2282 // jumps and targets with unknown addresses.
2285 for _, s := range ctxt.Textp {
2286 if ldr.OuterSym(s) != 0 || s == text {
2289 oldv := ldr.SymValue(s)
2290 for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2291 ldr.SetSymValue(sub, ldr.SymValue(sub)-oldv)
2297 for _, s := range ctxt.Textp {
2298 sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
2300 trampoline(ctxt, s) // resolve jumps, may add trampolines if jump too far
2302 // lay down trampolines after each function
2303 for ; ntramps < len(ctxt.tramps); ntramps++ {
2304 tramp := ctxt.tramps[ntramps]
2305 if ctxt.IsAIX() && strings.HasPrefix(ldr.SymName(tramp), "runtime.text.") {
2306 // Already set in assignAddress
2309 sect, n, va = assignAddress(ctxt, sect, n, tramp, va, true, big)
2313 // merge tramps into Textp, keeping Textp in address order
2315 newtextp := make([]loader.Sym, 0, len(ctxt.Textp)+ntramps)
2317 for _, s := range ctxt.Textp {
2318 for ; i < ntramps && ldr.SymValue(ctxt.tramps[i]) < ldr.SymValue(s); i++ {
2319 newtextp = append(newtextp, ctxt.tramps[i])
2321 newtextp = append(newtextp, s)
2323 newtextp = append(newtextp, ctxt.tramps[i:ntramps]...)
2325 ctxt.Textp = newtextp
2329 sect.Length = va - sect.Vaddr
2330 ldr.SetSymSect(etext, sect)
2331 if ldr.SymValue(etext) == 0 {
2332 // Set the address of the start/end symbols, if not already
2333 // (i.e. not darwin+dynlink or AIX+external, see above).
2334 ldr.SetSymValue(etext, int64(va))
2335 ldr.SetSymValue(text, int64(Segtext.Sections[0].Vaddr))
2339 // assigns address for a text symbol, returns (possibly new) section, its number, and the address
2340 func assignAddress(ctxt *Link, sect *sym.Section, n int, s loader.Sym, va uint64, isTramp, big bool) (*sym.Section, int, uint64) {
2342 if thearch.AssignAddress != nil {
2343 return thearch.AssignAddress(ldr, sect, n, s, va, isTramp)
2346 ldr.SetSymSect(s, sect)
2347 if ldr.AttrSubSymbol(s) {
2351 align := ldr.SymAlign(s)
2353 align = int32(Funcalign)
2355 va = uint64(Rnd(int64(va), int64(align)))
2356 if sect.Align < align {
2360 funcsize := uint64(MINFUNC) // spacing required for findfunctab
2361 if ldr.SymSize(s) > MINFUNC {
2362 funcsize = uint64(ldr.SymSize(s))
2365 // If we need to split text sections, and this function doesn't fit in the current
2366 // section, then create a new one.
2368 // Only break at outermost syms.
2369 if big && splitTextSections(ctxt) && ldr.OuterSym(s) == 0 {
2370 // For debugging purposes, allow text size limit to be cranked down,
2371 // so as to stress test the code that handles multiple text sections.
2372 var textSizelimit uint64 = thearch.TrampLimit
2373 if *FlagDebugTextSize != 0 {
2374 textSizelimit = uint64(*FlagDebugTextSize)
2377 // Sanity check: make sure the limit is larger than any
2378 // individual text symbol.
2379 if funcsize > textSizelimit {
2380 panic(fmt.Sprintf("error: text size limit %d less than text symbol %s size of %d", textSizelimit, ldr.SymName(s), funcsize))
2383 if va-sect.Vaddr+funcsize+maxSizeTrampolines(ctxt, ldr, s, isTramp) > textSizelimit {
2384 sectAlign := int32(thearch.Funcalign)
2386 // Align the next text section to the worst case function alignment likely
2387 // to be encountered when processing function symbols. The start address
2388 // is rounded against the final alignment of the text section later on in
2389 // (*Link).address. This may happen due to usage of PCALIGN directives
2390 // larger than Funcalign, or usage of ISA 3.1 prefixed instructions
2391 // (see ISA 3.1 Book I 1.9).
2392 const ppc64maxFuncalign = 64
2393 sectAlign = ppc64maxFuncalign
2394 va = uint64(Rnd(int64(va), ppc64maxFuncalign))
2397 // Set the length for the previous text section
2398 sect.Length = va - sect.Vaddr
2400 // Create new section, set the starting Vaddr
2401 sect = addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2404 sect.Align = sectAlign
2405 ldr.SetSymSect(s, sect)
2407 // Create a symbol for the start of the secondary text sections
2408 ntext := ldr.CreateSymForUpdate(fmt.Sprintf("runtime.text.%d", n), 0)
2411 // runtime.text.X must be a real symbol on AIX.
2412 // Assign its address directly in order to be the
2413 // first symbol of this new section.
2414 ntext.SetType(sym.STEXT)
2415 ntext.SetSize(int64(MINFUNC))
2416 ntext.SetOnList(true)
2417 ntext.SetAlign(sectAlign)
2418 ctxt.tramps = append(ctxt.tramps, ntext.Sym())
2420 ntext.SetValue(int64(va))
2421 va += uint64(ntext.Size())
2423 if align := ldr.SymAlign(s); align != 0 {
2424 va = uint64(Rnd(int64(va), int64(align)))
2426 va = uint64(Rnd(int64(va), int64(Funcalign)))
2433 ldr.SetSymValue(s, 0)
2434 for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2435 ldr.SetSymValue(sub, ldr.SymValue(sub)+int64(va))
2436 if ctxt.Debugvlog > 2 {
2437 fmt.Println("assign text address:", ldr.SymName(sub), ldr.SymValue(sub))
2446 // Return whether we may need to split text sections.
2448 // On PPC64x whem external linking a text section should not be larger than 2^25 bytes
2449 // due to the size of call target offset field in the bl instruction. Splitting into
2450 // smaller text sections smaller than this limit allows the system linker to modify the long
2451 // calls appropriately. The limit allows for the space needed for tables inserted by the
2454 // The same applies to Darwin/ARM64, with 2^27 byte threshold.
2455 func splitTextSections(ctxt *Link) bool {
2456 return (ctxt.IsPPC64() || (ctxt.IsARM64() && ctxt.IsDarwin())) && ctxt.IsExternal()
2459 // On Wasm, we reserve 4096 bytes for zero page, then 8192 bytes for wasm_exec.js
2460 // to store command line args and environment variables.
2461 // Data sections starts from at least address 12288.
2462 // Keep in sync with wasm_exec.js.
2463 const wasmMinDataAddr = 4096 + 8192
2465 // address assigns virtual addresses to all segments and sections and
2466 // returns all segments in file order.
2467 func (ctxt *Link) address() []*sym.Segment {
2468 var order []*sym.Segment // Layout order
2470 va := uint64(*FlagTextAddr)
2471 order = append(order, &Segtext)
2474 for i, s := range Segtext.Sections {
2475 va = uint64(Rnd(int64(va), int64(s.Align)))
2479 if ctxt.IsWasm() && i == 0 && va < wasmMinDataAddr {
2480 va = wasmMinDataAddr
2484 Segtext.Length = va - uint64(*FlagTextAddr)
2486 if len(Segrodata.Sections) > 0 {
2487 // align to page boundary so as not to mix
2488 // rodata and executable text.
2490 // Note: gold or GNU ld will reduce the size of the executable
2491 // file by arranging for the relro segment to end at a page
2492 // boundary, and overlap the end of the text segment with the
2493 // start of the relro segment in the file. The PT_LOAD segments
2494 // will be such that the last page of the text segment will be
2495 // mapped twice, once r-x and once starting out rw- and, after
2496 // relocation processing, changed to r--.
2498 // Ideally the last page of the text segment would not be
2499 // writable even for this short period.
2500 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2502 order = append(order, &Segrodata)
2504 Segrodata.Vaddr = va
2505 for _, s := range Segrodata.Sections {
2506 va = uint64(Rnd(int64(va), int64(s.Align)))
2511 Segrodata.Length = va - Segrodata.Vaddr
2513 if len(Segrelrodata.Sections) > 0 {
2514 // align to page boundary so as not to mix
2515 // rodata, rel-ro data, and executable text.
2516 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2517 if ctxt.HeadType == objabi.Haix {
2518 // Relro data are inside data segment on AIX.
2519 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2522 order = append(order, &Segrelrodata)
2523 Segrelrodata.Rwx = 06
2524 Segrelrodata.Vaddr = va
2525 for _, s := range Segrelrodata.Sections {
2526 va = uint64(Rnd(int64(va), int64(s.Align)))
2531 Segrelrodata.Length = va - Segrelrodata.Vaddr
2534 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2535 if ctxt.HeadType == objabi.Haix && len(Segrelrodata.Sections) == 0 {
2536 // Data sections are moved to an unreachable segment
2537 // to ensure that they are position-independent.
2538 // Already done if relro sections exist.
2539 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2541 order = append(order, &Segdata)
2544 var data *sym.Section
2545 var noptr *sym.Section
2546 var bss *sym.Section
2547 var noptrbss *sym.Section
2548 var fuzzCounters *sym.Section
2549 for i, s := range Segdata.Sections {
2550 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && s.Name == ".tbss" {
2553 vlen := int64(s.Length)
2554 if i+1 < len(Segdata.Sections) && !((ctxt.IsELF || ctxt.HeadType == objabi.Haix) && Segdata.Sections[i+1].Name == ".tbss") {
2555 vlen = int64(Segdata.Sections[i+1].Vaddr - s.Vaddr)
2559 Segdata.Length = va - Segdata.Vaddr
2569 case "__sancov_cntrs":
2574 // Assign Segdata's Filelen omitting the BSS. We do this here
2575 // simply because right now we know where the BSS starts.
2576 Segdata.Filelen = bss.Vaddr - Segdata.Vaddr
2578 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2579 order = append(order, &Segdwarf)
2582 for i, s := range Segdwarf.Sections {
2583 vlen := int64(s.Length)
2584 if i+1 < len(Segdwarf.Sections) {
2585 vlen = int64(Segdwarf.Sections[i+1].Vaddr - s.Vaddr)
2589 if ctxt.HeadType == objabi.Hwindows {
2590 va = uint64(Rnd(int64(va), PEFILEALIGN))
2592 Segdwarf.Length = va - Segdwarf.Vaddr
2597 rodata = ldr.SymSect(ldr.LookupOrCreateSym("runtime.rodata", 0))
2598 symtab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.symtab", 0))
2599 pclntab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0))
2600 types = ldr.SymSect(ldr.LookupOrCreateSym("runtime.types", 0))
2603 for _, s := range ctxt.datap {
2604 if sect := ldr.SymSect(s); sect != nil {
2605 ldr.AddToSymValue(s, int64(sect.Vaddr))
2607 v := ldr.SymValue(s)
2608 for sub := ldr.SubSym(s); sub != 0; sub = ldr.SubSym(sub) {
2609 ldr.AddToSymValue(sub, v)
2613 for _, si := range dwarfp {
2614 for _, s := range si.syms {
2615 if sect := ldr.SymSect(s); sect != nil {
2616 ldr.AddToSymValue(s, int64(sect.Vaddr))
2618 sub := ldr.SubSym(s)
2620 panic(fmt.Sprintf("unexpected sub-sym for %s %s", ldr.SymName(s), ldr.SymType(s).String()))
2622 v := ldr.SymValue(s)
2623 for ; sub != 0; sub = ldr.SubSym(sub) {
2624 ldr.AddToSymValue(s, v)
2629 if ctxt.BuildMode == BuildModeShared {
2630 s := ldr.LookupOrCreateSym("go:link.abihashbytes", 0)
2631 sect := ldr.SymSect(ldr.LookupOrCreateSym(".note.go.abihash", 0))
2632 ldr.SetSymSect(s, sect)
2633 ldr.SetSymValue(s, int64(sect.Vaddr+16))
2636 // If there are multiple text sections, create runtime.text.n for
2637 // their section Vaddr, using n for index
2639 for _, sect := range Segtext.Sections[1:] {
2640 if sect.Name != ".text" {
2643 symname := fmt.Sprintf("runtime.text.%d", n)
2644 if ctxt.HeadType != objabi.Haix || ctxt.LinkMode != LinkExternal {
2645 // Addresses are already set on AIX with external linker
2646 // because these symbols are part of their sections.
2647 ctxt.xdefine(symname, sym.STEXT, int64(sect.Vaddr))
2652 ctxt.xdefine("runtime.rodata", sym.SRODATA, int64(rodata.Vaddr))
2653 ctxt.xdefine("runtime.erodata", sym.SRODATA, int64(rodata.Vaddr+rodata.Length))
2654 ctxt.xdefine("runtime.types", sym.SRODATA, int64(types.Vaddr))
2655 ctxt.xdefine("runtime.etypes", sym.SRODATA, int64(types.Vaddr+types.Length))
2657 s := ldr.Lookup("runtime.gcdata", 0)
2658 ldr.SetAttrLocal(s, true)
2659 ctxt.xdefine("runtime.egcdata", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2660 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcdata", 0), ldr.SymSect(s))
2662 s = ldr.LookupOrCreateSym("runtime.gcbss", 0)
2663 ldr.SetAttrLocal(s, true)
2664 ctxt.xdefine("runtime.egcbss", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2665 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcbss", 0), ldr.SymSect(s))
2667 ctxt.xdefine("runtime.symtab", sym.SRODATA, int64(symtab.Vaddr))
2668 ctxt.xdefine("runtime.esymtab", sym.SRODATA, int64(symtab.Vaddr+symtab.Length))
2669 ctxt.xdefine("runtime.pclntab", sym.SRODATA, int64(pclntab.Vaddr))
2670 ctxt.defineInternal("runtime.pcheader", sym.SRODATA)
2671 ctxt.defineInternal("runtime.funcnametab", sym.SRODATA)
2672 ctxt.defineInternal("runtime.cutab", sym.SRODATA)
2673 ctxt.defineInternal("runtime.filetab", sym.SRODATA)
2674 ctxt.defineInternal("runtime.pctab", sym.SRODATA)
2675 ctxt.defineInternal("runtime.functab", sym.SRODATA)
2676 ctxt.xdefine("runtime.epclntab", sym.SRODATA, int64(pclntab.Vaddr+pclntab.Length))
2677 ctxt.xdefine("runtime.noptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr))
2678 ctxt.xdefine("runtime.enoptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr+noptr.Length))
2679 ctxt.xdefine("runtime.bss", sym.SBSS, int64(bss.Vaddr))
2680 ctxt.xdefine("runtime.ebss", sym.SBSS, int64(bss.Vaddr+bss.Length))
2681 ctxt.xdefine("runtime.data", sym.SDATA, int64(data.Vaddr))
2682 ctxt.xdefine("runtime.edata", sym.SDATA, int64(data.Vaddr+data.Length))
2683 ctxt.xdefine("runtime.noptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr))
2684 ctxt.xdefine("runtime.enoptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr+noptrbss.Length))
2685 ctxt.xdefine("runtime.end", sym.SBSS, int64(Segdata.Vaddr+Segdata.Length))
2687 if fuzzCounters != nil {
2688 ctxt.xdefine("__start___sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr))
2689 ctxt.xdefine("__stop___sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
2690 ctxt.xdefine("internal/fuzz._counters", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr))
2691 ctxt.xdefine("internal/fuzz._ecounters", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
2694 if ctxt.IsSolaris() {
2695 // On Solaris, in the runtime it sets the external names of the
2696 // end symbols. Unset them and define separate symbols, so we
2698 etext := ldr.Lookup("runtime.etext", 0)
2699 edata := ldr.Lookup("runtime.edata", 0)
2700 end := ldr.Lookup("runtime.end", 0)
2701 ldr.SetSymExtname(etext, "runtime.etext")
2702 ldr.SetSymExtname(edata, "runtime.edata")
2703 ldr.SetSymExtname(end, "runtime.end")
2704 ctxt.xdefine("_etext", ldr.SymType(etext), ldr.SymValue(etext))
2705 ctxt.xdefine("_edata", ldr.SymType(edata), ldr.SymValue(edata))
2706 ctxt.xdefine("_end", ldr.SymType(end), ldr.SymValue(end))
2707 ldr.SetSymSect(ldr.Lookup("_etext", 0), ldr.SymSect(etext))
2708 ldr.SetSymSect(ldr.Lookup("_edata", 0), ldr.SymSect(edata))
2709 ldr.SetSymSect(ldr.Lookup("_end", 0), ldr.SymSect(end))
2712 if ctxt.IsPPC64() && ctxt.IsElf() {
2713 // Resolve .TOC. symbols for all objects. Only one TOC region is supported. If a
2714 // GOT section is present, compute it as suggested by the ELFv2 ABI. Otherwise,
2715 // choose a similar offset from the start of the data segment.
2716 tocAddr := int64(Segdata.Vaddr) + 0x8000
2717 if gotAddr := ldr.SymValue(ctxt.GOT); gotAddr != 0 {
2718 tocAddr = gotAddr + 0x8000
2720 for i, _ := range ctxt.DotTOC {
2721 if i >= sym.SymVerABICount && i < sym.SymVerStatic { // these versions are not used currently
2724 if toc := ldr.Lookup(".TOC.", i); toc != 0 {
2725 ldr.SetSymValue(toc, tocAddr)
2733 // layout assigns file offsets and lengths to the segments in order.
2734 // Returns the file size containing all the segments.
2735 func (ctxt *Link) layout(order []*sym.Segment) uint64 {
2736 var prev *sym.Segment
2737 for _, seg := range order {
2739 seg.Fileoff = uint64(HEADR)
2741 switch ctxt.HeadType {
2743 // Assuming the previous segment was
2744 // aligned, the following rounding
2745 // should ensure that this segment's
2746 // VA ≡ Fileoff mod FlagRound.
2747 seg.Fileoff = uint64(Rnd(int64(prev.Fileoff+prev.Filelen), int64(*FlagRound)))
2748 if seg.Vaddr%uint64(*FlagRound) != seg.Fileoff%uint64(*FlagRound) {
2749 Exitf("bad segment rounding (Vaddr=%#x Fileoff=%#x FlagRound=%#x)", seg.Vaddr, seg.Fileoff, *FlagRound)
2751 case objabi.Hwindows:
2752 seg.Fileoff = prev.Fileoff + uint64(Rnd(int64(prev.Filelen), PEFILEALIGN))
2754 seg.Fileoff = prev.Fileoff + prev.Filelen
2757 if seg != &Segdata {
2758 // Link.address already set Segdata.Filelen to
2760 seg.Filelen = seg.Length
2764 return prev.Fileoff + prev.Filelen
2767 // add a trampoline with symbol s (to be laid down after the current function)
2768 func (ctxt *Link) AddTramp(s *loader.SymbolBuilder) {
2769 s.SetType(sym.STEXT)
2770 s.SetReachable(true)
2772 ctxt.tramps = append(ctxt.tramps, s.Sym())
2773 if *FlagDebugTramp > 0 && ctxt.Debugvlog > 0 {
2774 ctxt.Logf("trampoline %s inserted\n", s.Name())
2778 // compressSyms compresses syms and returns the contents of the
2779 // compressed section. If the section would get larger, it returns nil.
2780 func compressSyms(ctxt *Link, syms []loader.Sym) []byte {
2783 for _, sym := range syms {
2784 total += ldr.SymSize(sym)
2787 var buf bytes.Buffer
2789 switch ctxt.Arch.PtrSize {
2791 binary.Write(&buf, ctxt.Arch.ByteOrder, elf.Chdr64{
2792 Type: uint32(elf.COMPRESS_ZLIB),
2793 Size: uint64(total),
2794 Addralign: uint64(ctxt.Arch.Alignment),
2797 binary.Write(&buf, ctxt.Arch.ByteOrder, elf.Chdr32{
2798 Type: uint32(elf.COMPRESS_ZLIB),
2799 Size: uint32(total),
2800 Addralign: uint32(ctxt.Arch.Alignment),
2803 log.Fatalf("can't compress header size:%d", ctxt.Arch.PtrSize)
2806 buf.Write([]byte("ZLIB"))
2807 var sizeBytes [8]byte
2808 binary.BigEndian.PutUint64(sizeBytes[:], uint64(total))
2809 buf.Write(sizeBytes[:])
2812 var relocbuf []byte // temporary buffer for applying relocations
2814 // Using zlib.BestSpeed achieves very nearly the same
2815 // compression levels of zlib.DefaultCompression, but takes
2816 // substantially less time. This is important because DWARF
2817 // compression can be a significant fraction of link time.
2818 z, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
2820 log.Fatalf("NewWriterLevel failed: %s", err)
2822 st := ctxt.makeRelocSymState()
2823 for _, s := range syms {
2824 // Symbol data may be read-only. Apply relocations in a
2825 // temporary buffer, and immediately write it out.
2827 relocs := ldr.Relocs(s)
2828 if relocs.Count() != 0 {
2829 relocbuf = append(relocbuf[:0], P...)
2833 if _, err := z.Write(P); err != nil {
2834 log.Fatalf("compression failed: %s", err)
2836 for i := ldr.SymSize(s) - int64(len(P)); i > 0; {
2838 if i < int64(len(b)) {
2841 n, err := z.Write(b)
2843 log.Fatalf("compression failed: %s", err)
2848 if err := z.Close(); err != nil {
2849 log.Fatalf("compression failed: %s", err)
2851 if int64(buf.Len()) >= total {
2852 // Compression didn't save any space.