Source file src/cmd/link/internal/ld/data.go

     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
     4  //
     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.
    13  //
    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:
    20  //
    21  // The above copyright notice and this permission notice shall be included in
    22  // all copies or substantial portions of the Software.
    23  //
    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
    30  // THE SOFTWARE.
    31  
    32  package ld
    33  
    34  import (
    35  	"bytes"
    36  	"cmd/internal/gcprog"
    37  	"cmd/internal/objabi"
    38  	"cmd/internal/sys"
    39  	"cmd/link/internal/loader"
    40  	"cmd/link/internal/loadpe"
    41  	"cmd/link/internal/sym"
    42  	"compress/zlib"
    43  	"debug/elf"
    44  	"encoding/binary"
    45  	"fmt"
    46  	"internal/abi"
    47  	"log"
    48  	"math/rand"
    49  	"os"
    50  	"sort"
    51  	"strconv"
    52  	"strings"
    53  	"sync"
    54  	"sync/atomic"
    55  )
    56  
    57  // isRuntimeDepPkg reports whether pkg is the runtime package or its dependency.
    58  func isRuntimeDepPkg(pkg string) bool {
    59  	switch pkg {
    60  	case "runtime",
    61  		"sync/atomic",          // runtime may call to sync/atomic, due to go:linkname
    62  		"internal/abi",         // used by reflectcall (and maybe more)
    63  		"internal/bytealg",     // for IndexByte
    64  		"internal/chacha8rand", // for rand
    65  		"internal/cpu":         // for cpu features
    66  		return true
    67  	}
    68  	return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test")
    69  }
    70  
    71  // Estimate the max size needed to hold any new trampolines created for this function. This
    72  // is used to determine when the section can be split if it becomes too large, to ensure that
    73  // the trampolines are in the same section as the function that uses them.
    74  func maxSizeTrampolines(ctxt *Link, ldr *loader.Loader, s loader.Sym, isTramp bool) uint64 {
    75  	// If thearch.Trampoline is nil, then trampoline support is not available on this arch.
    76  	// A trampoline does not need any dependent trampolines.
    77  	if thearch.Trampoline == nil || isTramp {
    78  		return 0
    79  	}
    80  
    81  	n := uint64(0)
    82  	relocs := ldr.Relocs(s)
    83  	for ri := 0; ri < relocs.Count(); ri++ {
    84  		r := relocs.At(ri)
    85  		if r.Type().IsDirectCallOrJump() {
    86  			n++
    87  		}
    88  	}
    89  
    90  	switch {
    91  	case ctxt.IsARM():
    92  		return n * 20 // Trampolines in ARM range from 3 to 5 instructions.
    93  	case ctxt.IsARM64():
    94  		return n * 12 // Trampolines in ARM64 are 3 instructions.
    95  	case ctxt.IsLOONG64():
    96  		return n * 12 // Trampolines in LOONG64 are 3 instructions.
    97  	case ctxt.IsPPC64():
    98  		return n * 16 // Trampolines in PPC64 are 4 instructions.
    99  	case ctxt.IsRISCV64():
   100  		return n * 8 // Trampolines in RISCV64 are 2 instructions.
   101  	}
   102  	panic("unreachable")
   103  }
   104  
   105  // Detect too-far jumps in function s, and add trampolines if necessary.
   106  // ARM, LOONG64, PPC64, PPC64LE and RISCV64 support trampoline insertion for internal
   107  // and external linking. On PPC64 and PPC64LE the text sections might be split
   108  // but will still insert trampolines where necessary.
   109  func trampoline(ctxt *Link, s loader.Sym) {
   110  	if thearch.Trampoline == nil {
   111  		return // no need or no support of trampolines on this arch
   112  	}
   113  
   114  	ldr := ctxt.loader
   115  	relocs := ldr.Relocs(s)
   116  	for ri := 0; ri < relocs.Count(); ri++ {
   117  		r := relocs.At(ri)
   118  		rt := r.Type()
   119  		if !rt.IsDirectCallOrJump() && !isPLTCall(ctxt.Arch, rt) {
   120  			continue
   121  		}
   122  		rs := r.Sym()
   123  		if !ldr.AttrReachable(rs) || ldr.SymType(rs) == sym.Sxxx {
   124  			continue // something is wrong. skip it here and we'll emit a better error later
   125  		}
   126  
   127  		if ldr.SymValue(rs) == 0 && ldr.SymType(rs) != sym.SDYNIMPORT && ldr.SymType(rs) != sym.SUNDEFEXT {
   128  			// Symbols in the same package are laid out together (if we
   129  			// don't randomize the function order).
   130  			// Except that if SymPkg(s) == "", it is a host object symbol
   131  			// which may call an external symbol via PLT.
   132  			if ldr.SymPkg(s) != "" && ldr.SymPkg(rs) == ldr.SymPkg(s) && *flagRandLayout == 0 {
   133  				// RISC-V is only able to reach +/-1MiB via a JAL instruction.
   134  				// We need to generate a trampoline when an address is
   135  				// currently unknown.
   136  				if !ctxt.Target.IsRISCV64() {
   137  					continue
   138  				}
   139  			}
   140  			// Runtime packages are laid out together.
   141  			if isRuntimeDepPkg(ldr.SymPkg(s)) && isRuntimeDepPkg(ldr.SymPkg(rs)) && *flagRandLayout == 0 {
   142  				continue
   143  			}
   144  		}
   145  		thearch.Trampoline(ctxt, ldr, ri, rs, s)
   146  	}
   147  }
   148  
   149  // whether rt is a (host object) relocation that will be turned into
   150  // a call to PLT.
   151  func isPLTCall(arch *sys.Arch, rt objabi.RelocType) bool {
   152  	const pcrel = 1
   153  	switch uint32(arch.Family) | uint32(rt)<<8 {
   154  	// ARM64
   155  	case uint32(sys.ARM64) | uint32(objabi.ElfRelocOffset+objabi.RelocType(elf.R_AARCH64_CALL26))<<8,
   156  		uint32(sys.ARM64) | uint32(objabi.ElfRelocOffset+objabi.RelocType(elf.R_AARCH64_JUMP26))<<8,
   157  		uint32(sys.ARM64) | uint32(objabi.MachoRelocOffset+MACHO_ARM64_RELOC_BRANCH26*2+pcrel)<<8:
   158  		return true
   159  
   160  	// ARM
   161  	case uint32(sys.ARM) | uint32(objabi.ElfRelocOffset+objabi.RelocType(elf.R_ARM_CALL))<<8,
   162  		uint32(sys.ARM) | uint32(objabi.ElfRelocOffset+objabi.RelocType(elf.R_ARM_PC24))<<8,
   163  		uint32(sys.ARM) | uint32(objabi.ElfRelocOffset+objabi.RelocType(elf.R_ARM_JUMP24))<<8:
   164  		return true
   165  
   166  	// Loong64
   167  	case uint32(sys.Loong64) | uint32(objabi.ElfRelocOffset+objabi.RelocType(elf.R_LARCH_B26))<<8:
   168  		return true
   169  	}
   170  	// TODO: other architectures.
   171  	return false
   172  }
   173  
   174  // FoldSubSymbolOffset computes the offset of symbol s to its top-level outer
   175  // symbol. Returns the top-level symbol and the offset.
   176  // This is used in generating external relocations.
   177  func FoldSubSymbolOffset(ldr *loader.Loader, s loader.Sym) (loader.Sym, int64) {
   178  	outer := ldr.OuterSym(s)
   179  	off := int64(0)
   180  	if outer != 0 {
   181  		off += ldr.SymValue(s) - ldr.SymValue(outer)
   182  		s = outer
   183  	}
   184  	return s, off
   185  }
   186  
   187  // relocsym resolve relocations in "s", updating the symbol's content
   188  // in "P".
   189  // The main loop walks through the list of relocations attached to "s"
   190  // and resolves them where applicable. Relocations are often
   191  // architecture-specific, requiring calls into the 'archreloc' and/or
   192  // 'archrelocvariant' functions for the architecture. When external
   193  // linking is in effect, it may not be  possible to completely resolve
   194  // the address/offset for a symbol, in which case the goal is to lay
   195  // the groundwork for turning a given relocation into an external reloc
   196  // (to be applied by the external linker). For more on how relocations
   197  // work in general, see
   198  //
   199  //	"Linkers and Loaders", by John R. Levine (Morgan Kaufmann, 1999), ch. 7
   200  //
   201  // This is a performance-critical function for the linker; be careful
   202  // to avoid introducing unnecessary allocations in the main loop.
   203  func (st *relocSymState) relocsym(s loader.Sym, P []byte) {
   204  	ldr := st.ldr
   205  	relocs := ldr.Relocs(s)
   206  	if relocs.Count() == 0 {
   207  		return
   208  	}
   209  	target := st.target
   210  	syms := st.syms
   211  	nExtReloc := 0 // number of external relocations
   212  	for ri := 0; ri < relocs.Count(); ri++ {
   213  		r := relocs.At(ri)
   214  		off := r.Off()
   215  		siz := int32(r.Siz())
   216  		rs := r.Sym()
   217  		rt := r.Type()
   218  		weak := r.Weak()
   219  		if off < 0 || off+siz > int32(len(P)) {
   220  			rname := ""
   221  			if rs != 0 {
   222  				rname = ldr.SymName(rs)
   223  			}
   224  			st.err.Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(P))
   225  			continue
   226  		}
   227  		if siz == 0 { // informational relocation - no work to do
   228  			continue
   229  		}
   230  
   231  		var rst sym.SymKind
   232  		if rs != 0 {
   233  			rst = ldr.SymType(rs)
   234  		}
   235  
   236  		if rs != 0 && (rst == sym.Sxxx || rst == sym.SXREF) {
   237  			// When putting the runtime but not main into a shared library
   238  			// these symbols are undefined and that's OK.
   239  			if target.IsShared() || target.IsPlugin() {
   240  				if ldr.SymName(rs) == "main.main" || (!target.IsPlugin() && ldr.SymName(rs) == "main..inittask") {
   241  					sb := ldr.MakeSymbolUpdater(rs)
   242  					sb.SetType(sym.SDYNIMPORT)
   243  				} else if strings.HasPrefix(ldr.SymName(rs), "go:info.") {
   244  					// Skip go.info symbols. They are only needed to communicate
   245  					// DWARF info between the compiler and linker.
   246  					continue
   247  				}
   248  			} else if target.IsPPC64() && ldr.SymName(rs) == ".TOC." {
   249  				// TOC symbol doesn't have a type but we do assign a value
   250  				// (see the address pass) and we can resolve it.
   251  				// TODO: give it a type.
   252  			} else {
   253  				st.err.errorUnresolved(ldr, s, rs)
   254  				continue
   255  			}
   256  		}
   257  
   258  		if rt >= objabi.ElfRelocOffset {
   259  			continue
   260  		}
   261  
   262  		// We need to be able to reference dynimport symbols when linking against
   263  		// shared libraries, and AIX, Darwin, OpenBSD and Solaris always need it.
   264  		if !target.IsAIX() && !target.IsDarwin() && !target.IsSolaris() && !target.IsOpenbsd() && rs != 0 && rst == sym.SDYNIMPORT && !target.IsDynlinkingGo() && !ldr.AttrSubSymbol(rs) {
   265  			if !(target.IsPPC64() && target.IsExternal() && ldr.SymName(rs) == ".TOC.") {
   266  				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))
   267  			}
   268  		}
   269  		if rs != 0 && rst != sym.STLSBSS && !weak && rt != objabi.R_METHODOFF && !ldr.AttrReachable(rs) {
   270  			st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
   271  		}
   272  
   273  		var rv sym.RelocVariant
   274  		if target.IsPPC64() || target.IsS390X() {
   275  			rv = ldr.RelocVariant(s, ri)
   276  		}
   277  
   278  		// TODO(mundaym): remove this special case - see issue 14218.
   279  		if target.IsS390X() {
   280  			switch rt {
   281  			case objabi.R_PCRELDBL:
   282  				rt = objabi.R_PCREL
   283  				rv = sym.RV_390_DBL
   284  			case objabi.R_CALL:
   285  				rv = sym.RV_390_DBL
   286  			}
   287  		}
   288  
   289  		var o int64
   290  		switch rt {
   291  		default:
   292  			switch siz {
   293  			default:
   294  				st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
   295  			case 1:
   296  				o = int64(P[off])
   297  			case 2:
   298  				o = int64(target.Arch.ByteOrder.Uint16(P[off:]))
   299  			case 4:
   300  				o = int64(target.Arch.ByteOrder.Uint32(P[off:]))
   301  			case 8:
   302  				o = int64(target.Arch.ByteOrder.Uint64(P[off:]))
   303  			}
   304  			out, n, ok := thearch.Archreloc(target, ldr, syms, r, s, o)
   305  			if target.IsExternal() {
   306  				nExtReloc += n
   307  			}
   308  			if ok {
   309  				o = out
   310  			} else {
   311  				st.err.Errorf(s, "unknown reloc to %v: %d (%s)", ldr.SymName(rs), rt, sym.RelocName(target.Arch, rt))
   312  			}
   313  		case objabi.R_TLS_LE:
   314  			if target.IsExternal() && target.IsElf() {
   315  				nExtReloc++
   316  				o = 0
   317  				if !target.IsAMD64() {
   318  					o = r.Add()
   319  				}
   320  				break
   321  			}
   322  
   323  			if target.IsElf() && target.IsARM() {
   324  				// On ELF ARM, the thread pointer is 8 bytes before
   325  				// the start of the thread-local data block, so add 8
   326  				// to the actual TLS offset (r->sym->value).
   327  				// This 8 seems to be a fundamental constant of
   328  				// ELF on ARM (or maybe Glibc on ARM); it is not
   329  				// related to the fact that our own TLS storage happens
   330  				// to take up 8 bytes.
   331  				o = 8 + ldr.SymValue(rs)
   332  			} else if target.IsElf() || target.IsPlan9() || target.IsDarwin() {
   333  				o = int64(syms.Tlsoffset) + r.Add()
   334  			} else if target.IsWindows() {
   335  				o = r.Add()
   336  			} else {
   337  				log.Fatalf("unexpected R_TLS_LE relocation for %v", target.HeadType)
   338  			}
   339  		case objabi.R_TLS_IE:
   340  			if target.IsExternal() && target.IsElf() {
   341  				nExtReloc++
   342  				o = 0
   343  				if !target.IsAMD64() {
   344  					o = r.Add()
   345  				}
   346  				if target.Is386() {
   347  					nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
   348  				}
   349  				break
   350  			}
   351  			if target.IsPIE() && target.IsElf() {
   352  				// We are linking the final executable, so we
   353  				// can optimize any TLS IE relocation to LE.
   354  				if thearch.TLSIEtoLE == nil {
   355  					log.Fatalf("internal linking of TLS IE not supported on %v", target.Arch.Family)
   356  				}
   357  				thearch.TLSIEtoLE(P, int(off), int(siz))
   358  				o = int64(syms.Tlsoffset)
   359  			} else {
   360  				log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", ldr.SymName(s))
   361  			}
   362  		case objabi.R_ADDR, objabi.R_PEIMAGEOFF:
   363  			if weak && !ldr.AttrReachable(rs) {
   364  				// Redirect it to runtime.unreachableMethod, which will throw if called.
   365  				rs = syms.unreachableMethod
   366  			}
   367  			if target.IsExternal() {
   368  				nExtReloc++
   369  
   370  				// set up addend for eventual relocation via outer symbol.
   371  				rs := rs
   372  				rs, off := FoldSubSymbolOffset(ldr, rs)
   373  				xadd := r.Add() + off
   374  				rst := ldr.SymType(rs)
   375  				if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
   376  					st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
   377  				}
   378  
   379  				o = xadd
   380  				if target.IsElf() {
   381  					if target.IsAMD64() {
   382  						o = 0
   383  					}
   384  				} else if target.IsDarwin() {
   385  					if ldr.SymType(s).IsDWARF() {
   386  						// We generally use symbol-targeted relocations.
   387  						// DWARF tools seem to only handle section-targeted relocations,
   388  						// so generate section-targeted relocations in DWARF sections.
   389  						// See also machoreloc1.
   390  						o += ldr.SymValue(rs)
   391  					}
   392  				} else if target.IsWindows() {
   393  					// nothing to do
   394  				} else if target.IsAIX() {
   395  					o = ldr.SymValue(rs) + xadd
   396  				} else {
   397  					st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
   398  				}
   399  
   400  				break
   401  			}
   402  
   403  			// On AIX, a second relocation must be done by the loader,
   404  			// as section addresses can change once loaded.
   405  			// The "default" symbol address is still needed by the loader so
   406  			// the current relocation can't be skipped.
   407  			if target.IsAIX() && rst != sym.SDYNIMPORT {
   408  				// It's not possible to make a loader relocation in a
   409  				// symbol which is not inside .data section.
   410  				// FIXME: It should be forbidden to have R_ADDR from a
   411  				// symbol which isn't in .data. However, as .text has the
   412  				// same address once loaded, this is possible.
   413  				if ldr.SymSect(s).Seg == &Segdata {
   414  					Xcoffadddynrel(target, ldr, syms, s, r, ri)
   415  				}
   416  			}
   417  
   418  			o = ldr.SymValue(rs) + r.Add()
   419  			if rt == objabi.R_PEIMAGEOFF {
   420  				// The R_PEIMAGEOFF offset is a RVA, so subtract
   421  				// the base address for the executable.
   422  				o -= PEBASE
   423  			}
   424  
   425  			// On amd64, 4-byte offsets will be sign-extended, so it is impossible to
   426  			// access more than 2GB of static data; fail at link time is better than
   427  			// fail at runtime. See https://golang.org/issue/7980.
   428  			// Instead of special casing only amd64, we treat this as an error on all
   429  			// 64-bit architectures so as to be future-proof.
   430  			if int32(o) < 0 && target.Arch.PtrSize > 4 && siz == 4 {
   431  				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())
   432  				errorexit()
   433  			}
   434  		case objabi.R_DWARFSECREF:
   435  			if ldr.SymSect(rs) == nil {
   436  				st.err.Errorf(s, "missing DWARF section for relocation target %s", ldr.SymName(rs))
   437  			}
   438  
   439  			if target.IsExternal() {
   440  				// On most platforms, the external linker needs to adjust DWARF references
   441  				// as it combines DWARF sections. However, on Darwin, dsymutil does the
   442  				// DWARF linking, and it understands how to follow section offsets.
   443  				// Leaving in the relocation records confuses it (see
   444  				// https://golang.org/issue/22068) so drop them for Darwin.
   445  				if !target.IsDarwin() {
   446  					nExtReloc++
   447  				}
   448  
   449  				xadd := r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
   450  
   451  				o = xadd
   452  				if target.IsElf() && target.IsAMD64() {
   453  					o = 0
   454  				}
   455  				break
   456  			}
   457  			o = ldr.SymValue(rs) + r.Add() - int64(ldr.SymSect(rs).Vaddr)
   458  		case objabi.R_METHODOFF:
   459  			if !ldr.AttrReachable(rs) {
   460  				// Set it to a sentinel value. The runtime knows this is not pointing to
   461  				// anything valid.
   462  				o = -1
   463  				break
   464  			}
   465  			fallthrough
   466  		case objabi.R_ADDROFF:
   467  			if weak && !ldr.AttrReachable(rs) {
   468  				continue
   469  			}
   470  			sect := ldr.SymSect(rs)
   471  			if sect == nil {
   472  				if rst == sym.SDYNIMPORT {
   473  					st.err.Errorf(s, "cannot target DYNIMPORT sym in section-relative reloc: %s", ldr.SymName(rs))
   474  				} else if rst == sym.SUNDEFEXT {
   475  					st.err.Errorf(s, "undefined symbol in relocation: %s", ldr.SymName(rs))
   476  				} else {
   477  					st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
   478  				}
   479  				continue
   480  			}
   481  
   482  			// The method offset tables using this relocation expect the offset to be relative
   483  			// to the start of the first text section, even if there are multiple.
   484  			if sect.Name == ".text" {
   485  				o = ldr.SymValue(rs) - int64(Segtext.Sections[0].Vaddr) + r.Add()
   486  			} else {
   487  				o = ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr) + r.Add()
   488  			}
   489  
   490  		case objabi.R_ADDRCUOFF:
   491  			// debug_range and debug_loc elements use this relocation type to get an
   492  			// offset from the start of the compile unit.
   493  			o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(loader.Sym(ldr.SymUnit(rs).Textp[0]))
   494  
   495  		// r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
   496  		case objabi.R_GOTPCREL:
   497  			if target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
   498  				nExtReloc++
   499  				o = r.Add()
   500  				break
   501  			}
   502  			if target.Is386() && target.IsExternal() && target.IsELF {
   503  				nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
   504  			}
   505  			fallthrough
   506  		case objabi.R_CALL, objabi.R_PCREL:
   507  			if target.IsExternal() && rs != 0 && rst == sym.SUNDEFEXT {
   508  				// pass through to the external linker.
   509  				nExtReloc++
   510  				o = 0
   511  				break
   512  			}
   513  			if target.IsExternal() && rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
   514  				nExtReloc++
   515  
   516  				// set up addend for eventual relocation via outer symbol.
   517  				rs := rs
   518  				rs, off := FoldSubSymbolOffset(ldr, rs)
   519  				xadd := r.Add() + off - int64(siz) // relative to address after the relocated chunk
   520  				rst := ldr.SymType(rs)
   521  				if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && ldr.SymSect(rs) == nil {
   522  					st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
   523  				}
   524  
   525  				o = xadd
   526  				if target.IsElf() {
   527  					if target.IsAMD64() {
   528  						o = 0
   529  					}
   530  				} else if target.IsDarwin() {
   531  					if rt == objabi.R_CALL {
   532  						if target.IsExternal() && rst == sym.SDYNIMPORT {
   533  							if target.IsAMD64() {
   534  								// AMD64 dynamic relocations are relative to the end of the relocation.
   535  								o += int64(siz)
   536  							}
   537  						} else {
   538  							if rst != sym.SHOSTOBJ {
   539  								o += int64(uint64(ldr.SymValue(rs)) - ldr.SymSect(rs).Vaddr)
   540  							}
   541  							o -= int64(off) // relative to section offset, not symbol
   542  						}
   543  					} else {
   544  						o += int64(siz)
   545  					}
   546  				} else if target.IsWindows() && target.IsAMD64() { // only amd64 needs PCREL
   547  					// PE/COFF's PC32 relocation uses the address after the relocated
   548  					// bytes as the base. Compensate by skewing the addend.
   549  					o += int64(siz)
   550  				} else {
   551  					st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
   552  				}
   553  
   554  				break
   555  			}
   556  
   557  			o = 0
   558  			if rs != 0 {
   559  				o = ldr.SymValue(rs)
   560  			}
   561  
   562  			o += r.Add() - (ldr.SymValue(s) + int64(off) + int64(siz))
   563  		case objabi.R_SIZE:
   564  			o = ldr.SymSize(rs) + r.Add()
   565  
   566  		case objabi.R_XCOFFREF:
   567  			if !target.IsAIX() {
   568  				st.err.Errorf(s, "find XCOFF R_REF on non-XCOFF files")
   569  			}
   570  			if !target.IsExternal() {
   571  				st.err.Errorf(s, "find XCOFF R_REF with internal linking")
   572  			}
   573  			nExtReloc++
   574  			continue
   575  
   576  		case objabi.R_DWARFFILEREF:
   577  			// We don't renumber files in dwarf.go:writelines anymore.
   578  			continue
   579  
   580  		case objabi.R_CONST:
   581  			o = r.Add()
   582  
   583  		case objabi.R_GOTOFF:
   584  			o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(syms.GOT)
   585  		}
   586  
   587  		if target.IsPPC64() || target.IsS390X() {
   588  			if rv != sym.RV_NONE {
   589  				o = thearch.Archrelocvariant(target, ldr, r, rv, s, o, P)
   590  			}
   591  		}
   592  
   593  		switch siz {
   594  		default:
   595  			st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
   596  		case 1:
   597  			P[off] = byte(int8(o))
   598  		case 2:
   599  			if (rt == objabi.R_PCREL || rt == objabi.R_CALL) && o != int64(int16(o)) {
   600  				st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
   601  			} else if o != int64(int16(o)) && o != int64(uint16(o)) {
   602  				st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
   603  			}
   604  			target.Arch.ByteOrder.PutUint16(P[off:], uint16(o))
   605  		case 4:
   606  			if (rt == objabi.R_PCREL || rt == objabi.R_CALL) && o != int64(int32(o)) {
   607  				st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
   608  			} else if o != int64(int32(o)) && o != int64(uint32(o)) {
   609  				st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
   610  			}
   611  			target.Arch.ByteOrder.PutUint32(P[off:], uint32(o))
   612  		case 8:
   613  			target.Arch.ByteOrder.PutUint64(P[off:], uint64(o))
   614  		}
   615  	}
   616  	if target.IsExternal() {
   617  		// We'll stream out the external relocations in asmb2 (e.g. elfrelocsect)
   618  		// and we only need the count here.
   619  		atomic.AddUint32(&ldr.SymSect(s).Relcount, uint32(nExtReloc))
   620  	}
   621  }
   622  
   623  // Convert a Go relocation to an external relocation.
   624  func extreloc(ctxt *Link, ldr *loader.Loader, s loader.Sym, r loader.Reloc) (loader.ExtReloc, bool) {
   625  	var rr loader.ExtReloc
   626  	target := &ctxt.Target
   627  	siz := int32(r.Siz())
   628  	if siz == 0 { // informational relocation - no work to do
   629  		return rr, false
   630  	}
   631  
   632  	rt := r.Type()
   633  	if rt >= objabi.ElfRelocOffset {
   634  		return rr, false
   635  	}
   636  	rr.Type = rt
   637  	rr.Size = uint8(siz)
   638  
   639  	// TODO(mundaym): remove this special case - see issue 14218.
   640  	if target.IsS390X() {
   641  		switch rt {
   642  		case objabi.R_PCRELDBL:
   643  			rt = objabi.R_PCREL
   644  		}
   645  	}
   646  
   647  	switch rt {
   648  	default:
   649  		return thearch.Extreloc(target, ldr, r, s)
   650  
   651  	case objabi.R_TLS_LE, objabi.R_TLS_IE:
   652  		if target.IsElf() {
   653  			rs := r.Sym()
   654  			rr.Xsym = rs
   655  			if rr.Xsym == 0 {
   656  				rr.Xsym = ctxt.Tlsg
   657  			}
   658  			rr.Xadd = r.Add()
   659  			break
   660  		}
   661  		return rr, false
   662  
   663  	case objabi.R_ADDR, objabi.R_PEIMAGEOFF:
   664  		// set up addend for eventual relocation via outer symbol.
   665  		rs := r.Sym()
   666  		if r.Weak() && !ldr.AttrReachable(rs) {
   667  			rs = ctxt.ArchSyms.unreachableMethod
   668  		}
   669  		rs, off := FoldSubSymbolOffset(ldr, rs)
   670  		rr.Xadd = r.Add() + off
   671  		rr.Xsym = rs
   672  
   673  	case objabi.R_DWARFSECREF:
   674  		// On most platforms, the external linker needs to adjust DWARF references
   675  		// as it combines DWARF sections. However, on Darwin, dsymutil does the
   676  		// DWARF linking, and it understands how to follow section offsets.
   677  		// Leaving in the relocation records confuses it (see
   678  		// https://golang.org/issue/22068) so drop them for Darwin.
   679  		if target.IsDarwin() {
   680  			return rr, false
   681  		}
   682  		rs := r.Sym()
   683  		rr.Xsym = loader.Sym(ldr.SymSect(rs).Sym)
   684  		rr.Xadd = r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
   685  
   686  	// r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
   687  	case objabi.R_GOTPCREL, objabi.R_CALL, objabi.R_PCREL:
   688  		rs := r.Sym()
   689  		if rt == objabi.R_GOTPCREL && target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
   690  			rr.Xadd = r.Add()
   691  			rr.Xadd -= int64(siz) // relative to address after the relocated chunk
   692  			rr.Xsym = rs
   693  			break
   694  		}
   695  		if rs != 0 && ldr.SymType(rs) == sym.SUNDEFEXT {
   696  			// pass through to the external linker.
   697  			rr.Xadd = 0
   698  			if target.IsElf() {
   699  				rr.Xadd -= int64(siz)
   700  			}
   701  			rr.Xsym = rs
   702  			break
   703  		}
   704  		if rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
   705  			// set up addend for eventual relocation via outer symbol.
   706  			rs := rs
   707  			rs, off := FoldSubSymbolOffset(ldr, rs)
   708  			rr.Xadd = r.Add() + off
   709  			rr.Xadd -= int64(siz) // relative to address after the relocated chunk
   710  			rr.Xsym = rs
   711  			break
   712  		}
   713  		return rr, false
   714  
   715  	case objabi.R_XCOFFREF:
   716  		return ExtrelocSimple(ldr, r), true
   717  
   718  	// These reloc types don't need external relocations.
   719  	case objabi.R_ADDROFF, objabi.R_METHODOFF, objabi.R_ADDRCUOFF,
   720  		objabi.R_SIZE, objabi.R_CONST, objabi.R_GOTOFF:
   721  		return rr, false
   722  	}
   723  	return rr, true
   724  }
   725  
   726  // ExtrelocSimple creates a simple external relocation from r, with the same
   727  // symbol and addend.
   728  func ExtrelocSimple(ldr *loader.Loader, r loader.Reloc) loader.ExtReloc {
   729  	var rr loader.ExtReloc
   730  	rs := r.Sym()
   731  	rr.Xsym = rs
   732  	rr.Xadd = r.Add()
   733  	rr.Type = r.Type()
   734  	rr.Size = r.Siz()
   735  	return rr
   736  }
   737  
   738  // ExtrelocViaOuterSym creates an external relocation from r targeting the
   739  // outer symbol and folding the subsymbol's offset into the addend.
   740  func ExtrelocViaOuterSym(ldr *loader.Loader, r loader.Reloc, s loader.Sym) loader.ExtReloc {
   741  	// set up addend for eventual relocation via outer symbol.
   742  	var rr loader.ExtReloc
   743  	rs := r.Sym()
   744  	rs, off := FoldSubSymbolOffset(ldr, rs)
   745  	rr.Xadd = r.Add() + off
   746  	rst := ldr.SymType(rs)
   747  	if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
   748  		ldr.Errorf(s, "missing section for %s", ldr.SymName(rs))
   749  	}
   750  	rr.Xsym = rs
   751  	rr.Type = r.Type()
   752  	rr.Size = r.Siz()
   753  	return rr
   754  }
   755  
   756  // relocSymState hold state information needed when making a series of
   757  // successive calls to relocsym(). The items here are invariant
   758  // (meaning that they are set up once initially and then don't change
   759  // during the execution of relocsym), with the exception of a slice
   760  // used to facilitate batch allocation of external relocations. Calls
   761  // to relocsym happen in parallel; the assumption is that each
   762  // parallel thread will have its own state object.
   763  type relocSymState struct {
   764  	target *Target
   765  	ldr    *loader.Loader
   766  	err    *ErrorReporter
   767  	syms   *ArchSyms
   768  }
   769  
   770  // makeRelocSymState creates a relocSymState container object to
   771  // pass to relocsym(). If relocsym() calls happen in parallel,
   772  // each parallel thread should have its own state object.
   773  func (ctxt *Link) makeRelocSymState() *relocSymState {
   774  	return &relocSymState{
   775  		target: &ctxt.Target,
   776  		ldr:    ctxt.loader,
   777  		err:    &ctxt.ErrorReporter,
   778  		syms:   &ctxt.ArchSyms,
   779  	}
   780  }
   781  
   782  // windynrelocsym examines a text symbol 's' and looks for relocations
   783  // from it that correspond to references to symbols defined in DLLs,
   784  // then fixes up those relocations as needed. A reference to a symbol
   785  // XYZ from some DLL will fall into one of two categories: an indirect
   786  // ref via "__imp_XYZ", or a direct ref to "XYZ". Here's an example of
   787  // an indirect ref (this is an excerpt from objdump -ldr):
   788  //
   789  //	     1c1: 48 89 c6                     	movq	%rax, %rsi
   790  //	     1c4: ff 15 00 00 00 00            	callq	*(%rip)
   791  //			00000000000001c6:  IMAGE_REL_AMD64_REL32	__imp__errno
   792  //
   793  // In the assembly above, the code loads up the value of __imp_errno
   794  // and then does an indirect call to that value.
   795  //
   796  // Here is what a direct reference might look like:
   797  //
   798  //	     137: e9 20 06 00 00               	jmp	0x75c <pow+0x75c>
   799  //	     13c: e8 00 00 00 00               	callq	0x141 <pow+0x141>
   800  //			000000000000013d:  IMAGE_REL_AMD64_REL32	_errno
   801  //
   802  // The assembly below dispenses with the import symbol and just makes
   803  // a direct call to _errno.
   804  //
   805  // The code below handles indirect refs by redirecting the target of
   806  // the relocation from "__imp_XYZ" to "XYZ" (since the latter symbol
   807  // is what the Windows loader is expected to resolve). For direct refs
   808  // the call is redirected to a stub, where the stub first loads the
   809  // symbol and then direct an indirect call to that value.
   810  //
   811  // Note that for a given symbol (as above) it is perfectly legal to
   812  // have both direct and indirect references.
   813  func windynrelocsym(ctxt *Link, rel *loader.SymbolBuilder, s loader.Sym) error {
   814  	var su *loader.SymbolBuilder
   815  	relocs := ctxt.loader.Relocs(s)
   816  	for ri := 0; ri < relocs.Count(); ri++ {
   817  		r := relocs.At(ri)
   818  		if r.IsMarker() {
   819  			continue // skip marker relocations
   820  		}
   821  		targ := r.Sym()
   822  		if targ == 0 {
   823  			continue
   824  		}
   825  		if !ctxt.loader.AttrReachable(targ) {
   826  			if r.Weak() {
   827  				continue
   828  			}
   829  			return fmt.Errorf("dynamic relocation to unreachable symbol %s",
   830  				ctxt.loader.SymName(targ))
   831  		}
   832  		tgot := ctxt.loader.SymGot(targ)
   833  		if tgot == loadpe.RedirectToDynImportGotToken {
   834  
   835  			// Consistency check: name should be __imp_X
   836  			sname := ctxt.loader.SymName(targ)
   837  			if !strings.HasPrefix(sname, "__imp_") {
   838  				return fmt.Errorf("internal error in windynrelocsym: redirect GOT token applied to non-import symbol %s", sname)
   839  			}
   840  
   841  			// Locate underlying symbol (which originally had type
   842  			// SDYNIMPORT but has since been retyped to SWINDOWS).
   843  			ds, err := loadpe.LookupBaseFromImport(targ, ctxt.loader, ctxt.Arch)
   844  			if err != nil {
   845  				return err
   846  			}
   847  			dstyp := ctxt.loader.SymType(ds)
   848  			if dstyp != sym.SWINDOWS {
   849  				return fmt.Errorf("internal error in windynrelocsym: underlying sym for %q has wrong type %s", sname, dstyp.String())
   850  			}
   851  
   852  			// Redirect relocation to the dynimport.
   853  			r.SetSym(ds)
   854  			continue
   855  		}
   856  
   857  		tplt := ctxt.loader.SymPlt(targ)
   858  		if tplt == loadpe.CreateImportStubPltToken {
   859  
   860  			// Consistency check: don't want to see both PLT and GOT tokens.
   861  			if tgot != -1 {
   862  				return fmt.Errorf("internal error in windynrelocsym: invalid GOT setting %d for reloc to %s", tgot, ctxt.loader.SymName(targ))
   863  			}
   864  
   865  			// make dynimport JMP table for PE object files.
   866  			tplt := int32(rel.Size())
   867  			ctxt.loader.SetPlt(targ, tplt)
   868  
   869  			if su == nil {
   870  				su = ctxt.loader.MakeSymbolUpdater(s)
   871  			}
   872  			r.SetSym(rel.Sym())
   873  			r.SetAdd(int64(tplt))
   874  
   875  			// jmp *addr
   876  			switch ctxt.Arch.Family {
   877  			default:
   878  				return fmt.Errorf("internal error in windynrelocsym: unsupported arch %v", ctxt.Arch.Family)
   879  			case sys.I386:
   880  				rel.AddUint8(0xff)
   881  				rel.AddUint8(0x25)
   882  				rel.AddAddrPlus(ctxt.Arch, targ, 0)
   883  				rel.AddUint8(0x90)
   884  				rel.AddUint8(0x90)
   885  			case sys.AMD64:
   886  				rel.AddUint8(0xff)
   887  				rel.AddUint8(0x24)
   888  				rel.AddUint8(0x25)
   889  				rel.AddAddrPlus4(ctxt.Arch, targ, 0)
   890  				rel.AddUint8(0x90)
   891  			}
   892  		} else if tplt >= 0 {
   893  			if su == nil {
   894  				su = ctxt.loader.MakeSymbolUpdater(s)
   895  			}
   896  			r.SetSym(rel.Sym())
   897  			r.SetAdd(int64(tplt))
   898  		}
   899  	}
   900  	return nil
   901  }
   902  
   903  // windynrelocsyms generates jump table to C library functions that will be
   904  // added later. windynrelocsyms writes the table into .rel symbol.
   905  func (ctxt *Link) windynrelocsyms() {
   906  	if !(ctxt.IsWindows() && iscgo && ctxt.IsInternal()) {
   907  		return
   908  	}
   909  
   910  	rel := ctxt.loader.CreateSymForUpdate(".rel", 0)
   911  	rel.SetType(sym.STEXT)
   912  
   913  	for _, s := range ctxt.Textp {
   914  		if err := windynrelocsym(ctxt, rel, s); err != nil {
   915  			ctxt.Errorf(s, "%v", err)
   916  		}
   917  	}
   918  
   919  	ctxt.Textp = append(ctxt.Textp, rel.Sym())
   920  }
   921  
   922  func dynrelocsym(ctxt *Link, s loader.Sym) {
   923  	target := &ctxt.Target
   924  	ldr := ctxt.loader
   925  	syms := &ctxt.ArchSyms
   926  	relocs := ldr.Relocs(s)
   927  	for ri := 0; ri < relocs.Count(); ri++ {
   928  		r := relocs.At(ri)
   929  		if r.IsMarker() {
   930  			continue // skip marker relocations
   931  		}
   932  		rSym := r.Sym()
   933  		if r.Weak() && !ldr.AttrReachable(rSym) {
   934  			continue
   935  		}
   936  		if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal {
   937  			// It's expected that some relocations will be done
   938  			// later by relocsym (R_TLS_LE, R_ADDROFF), so
   939  			// don't worry if Adddynrel returns false.
   940  			thearch.Adddynrel(target, ldr, syms, s, r, ri)
   941  			continue
   942  		}
   943  
   944  		if rSym != 0 && ldr.SymType(rSym) == sym.SDYNIMPORT || r.Type() >= objabi.ElfRelocOffset {
   945  			if rSym != 0 && !ldr.AttrReachable(rSym) {
   946  				ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s", ldr.SymName(rSym))
   947  			}
   948  			if !thearch.Adddynrel(target, ldr, syms, s, r, ri) {
   949  				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))
   950  			}
   951  		}
   952  	}
   953  }
   954  
   955  func (state *dodataState) dynreloc(ctxt *Link) {
   956  	if ctxt.HeadType == objabi.Hwindows {
   957  		return
   958  	}
   959  	// -d suppresses dynamic loader format, so we may as well not
   960  	// compute these sections or mark their symbols as reachable.
   961  	if *FlagD {
   962  		return
   963  	}
   964  
   965  	for _, s := range ctxt.Textp {
   966  		dynrelocsym(ctxt, s)
   967  	}
   968  	for _, syms := range state.data {
   969  		for _, s := range syms {
   970  			dynrelocsym(ctxt, s)
   971  		}
   972  	}
   973  	if ctxt.IsELF {
   974  		elfdynhash(ctxt)
   975  	}
   976  }
   977  
   978  func CodeblkPad(ctxt *Link, out *OutBuf, addr int64, size int64, pad []byte) {
   979  	writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.Textp, addr, size, pad)
   980  }
   981  
   982  const blockSize = 1 << 20 // 1MB chunks written at a time.
   983  
   984  // writeBlocks writes a specified chunk of symbols to the output buffer. It
   985  // breaks the write up into ≥blockSize chunks to write them out, and schedules
   986  // as many goroutines as necessary to accomplish this task. This call then
   987  // blocks, waiting on the writes to complete. Note that we use the sem parameter
   988  // to limit the number of concurrent writes taking place.
   989  func writeBlocks(ctxt *Link, out *OutBuf, sem chan int, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
   990  	for i, s := range syms {
   991  		if ldr.SymValue(s) >= addr && !ldr.AttrSubSymbol(s) {
   992  			syms = syms[i:]
   993  			break
   994  		}
   995  	}
   996  
   997  	var wg sync.WaitGroup
   998  	max, lastAddr, written := int64(blockSize), addr+size, int64(0)
   999  	for addr < lastAddr {
  1000  		// Find the last symbol we'd write.
  1001  		idx := -1
  1002  		for i, s := range syms {
  1003  			if ldr.AttrSubSymbol(s) {
  1004  				continue
  1005  			}
  1006  
  1007  			// If the next symbol's size would put us out of bounds on the total length,
  1008  			// stop looking.
  1009  			end := ldr.SymValue(s) + ldr.SymSize(s)
  1010  			if end > lastAddr {
  1011  				break
  1012  			}
  1013  
  1014  			// We're gonna write this symbol.
  1015  			idx = i
  1016  
  1017  			// If we cross over the max size, we've got enough symbols.
  1018  			if end > addr+max {
  1019  				break
  1020  			}
  1021  		}
  1022  
  1023  		// If we didn't find any symbols to write, we're done here.
  1024  		if idx < 0 {
  1025  			break
  1026  		}
  1027  
  1028  		// Compute the length to write, including padding.
  1029  		// We need to write to the end address (lastAddr), or the next symbol's
  1030  		// start address, whichever comes first. If there is no more symbols,
  1031  		// just write to lastAddr. This ensures we don't leave holes between the
  1032  		// blocks or at the end.
  1033  		length := int64(0)
  1034  		if idx+1 < len(syms) {
  1035  			// Find the next top-level symbol.
  1036  			// Skip over sub symbols so we won't split a container symbol
  1037  			// into two blocks.
  1038  			next := syms[idx+1]
  1039  			for ldr.AttrSubSymbol(next) {
  1040  				idx++
  1041  				next = syms[idx+1]
  1042  			}
  1043  			length = ldr.SymValue(next) - addr
  1044  		}
  1045  		if length == 0 || length > lastAddr-addr {
  1046  			length = lastAddr - addr
  1047  		}
  1048  
  1049  		// Start the block output operator.
  1050  		if o, err := out.View(uint64(out.Offset() + written)); err == nil {
  1051  			sem <- 1
  1052  			wg.Add(1)
  1053  			go func(o *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
  1054  				writeBlock(ctxt, o, ldr, syms, addr, size, pad)
  1055  				wg.Done()
  1056  				<-sem
  1057  			}(o, ldr, syms, addr, length, pad)
  1058  		} else { // output not mmaped, don't parallelize.
  1059  			writeBlock(ctxt, out, ldr, syms, addr, length, pad)
  1060  		}
  1061  
  1062  		// Prepare for the next loop.
  1063  		if idx != -1 {
  1064  			syms = syms[idx+1:]
  1065  		}
  1066  		written += length
  1067  		addr += length
  1068  	}
  1069  	wg.Wait()
  1070  }
  1071  
  1072  func writeBlock(ctxt *Link, out *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
  1073  
  1074  	st := ctxt.makeRelocSymState()
  1075  
  1076  	// This doesn't distinguish the memory size from the file
  1077  	// size, and it lays out the file based on Symbol.Value, which
  1078  	// is the virtual address. DWARF compression changes file sizes,
  1079  	// so dwarfcompress will fix this up later if necessary.
  1080  	eaddr := addr + size
  1081  	var prev loader.Sym
  1082  	for _, s := range syms {
  1083  		if ldr.AttrSubSymbol(s) {
  1084  			continue
  1085  		}
  1086  		val := ldr.SymValue(s)
  1087  		if val >= eaddr {
  1088  			break
  1089  		}
  1090  		if val < addr {
  1091  			ldr.Errorf(s, "phase error: addr=%#x but val=%#x sym=%s type=%v sect=%v sect.addr=%#x prev=%s", addr, val, ldr.SymName(s), ldr.SymType(s), ldr.SymSect(s).Name, ldr.SymSect(s).Vaddr, ldr.SymName(prev))
  1092  			panic("PHASE")
  1093  			errorexit()
  1094  		}
  1095  		prev = s
  1096  		if addr < val {
  1097  			out.WriteStringPad("", int(val-addr), pad)
  1098  			addr = val
  1099  		}
  1100  		P := out.WriteSym(ldr, s)
  1101  		st.relocsym(s, P)
  1102  		if ldr.IsGeneratedSym(s) {
  1103  			f := ctxt.generatorSyms[s]
  1104  			f(ctxt, s)
  1105  		}
  1106  		addr += int64(len(P))
  1107  		siz := ldr.SymSize(s)
  1108  		if addr < val+siz {
  1109  			out.WriteStringPad("", int(val+siz-addr), pad)
  1110  			addr = val + siz
  1111  		}
  1112  		if addr != val+siz {
  1113  			ldr.Errorf(s, "phase error: addr=%#x value+size=%#x", addr, val+siz)
  1114  			errorexit()
  1115  		}
  1116  		if val+siz >= eaddr {
  1117  			break
  1118  		}
  1119  	}
  1120  
  1121  	if addr < eaddr {
  1122  		out.WriteStringPad("", int(eaddr-addr), pad)
  1123  	}
  1124  }
  1125  
  1126  type writeFn func(*Link, *OutBuf, int64, int64)
  1127  
  1128  // writeParallel handles scheduling parallel execution of data write functions.
  1129  func writeParallel(wg *sync.WaitGroup, fn writeFn, ctxt *Link, seek, vaddr, length uint64) {
  1130  	if out, err := ctxt.Out.View(seek); err != nil {
  1131  		ctxt.Out.SeekSet(int64(seek))
  1132  		fn(ctxt, ctxt.Out, int64(vaddr), int64(length))
  1133  	} else {
  1134  		wg.Add(1)
  1135  		go func() {
  1136  			defer wg.Done()
  1137  			fn(ctxt, out, int64(vaddr), int64(length))
  1138  		}()
  1139  	}
  1140  }
  1141  
  1142  func datblk(ctxt *Link, out *OutBuf, addr, size int64) {
  1143  	writeDatblkToOutBuf(ctxt, out, addr, size)
  1144  }
  1145  
  1146  // Used only on Wasm for now.
  1147  func DatblkBytes(ctxt *Link, addr int64, size int64) []byte {
  1148  	buf := make([]byte, size)
  1149  	out := &OutBuf{heap: buf}
  1150  	writeDatblkToOutBuf(ctxt, out, addr, size)
  1151  	return buf
  1152  }
  1153  
  1154  func writeDatblkToOutBuf(ctxt *Link, out *OutBuf, addr int64, size int64) {
  1155  	writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.datap, addr, size, zeros[:])
  1156  }
  1157  
  1158  func dwarfblk(ctxt *Link, out *OutBuf, addr int64, size int64) {
  1159  	// Concatenate the section symbol lists into a single list to pass
  1160  	// to writeBlocks.
  1161  	//
  1162  	// NB: ideally we would do a separate writeBlocks call for each
  1163  	// section, but this would run the risk of undoing any file offset
  1164  	// adjustments made during layout.
  1165  	n := 0
  1166  	for i := range dwarfp {
  1167  		n += len(dwarfp[i].syms)
  1168  	}
  1169  	syms := make([]loader.Sym, 0, n)
  1170  	for i := range dwarfp {
  1171  		syms = append(syms, dwarfp[i].syms...)
  1172  	}
  1173  	writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, syms, addr, size, zeros[:])
  1174  }
  1175  
  1176  func pdatablk(ctxt *Link, out *OutBuf, addr int64, size int64) {
  1177  	writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, sehp.pdata, addr, size, zeros[:])
  1178  }
  1179  
  1180  func xdatablk(ctxt *Link, out *OutBuf, addr int64, size int64) {
  1181  	writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, sehp.xdata, addr, size, zeros[:])
  1182  }
  1183  
  1184  var covCounterDataStartOff, covCounterDataLen uint64
  1185  
  1186  var zeros [512]byte
  1187  
  1188  var (
  1189  	strdata  = make(map[string]string)
  1190  	strnames []string
  1191  )
  1192  
  1193  func addstrdata1(ctxt *Link, arg string) {
  1194  	eq := strings.Index(arg, "=")
  1195  	dot := strings.LastIndex(arg[:eq+1], ".")
  1196  	if eq < 0 || dot < 0 {
  1197  		Exitf("-X flag requires argument of the form importpath.name=value")
  1198  	}
  1199  	pkg := arg[:dot]
  1200  	if ctxt.BuildMode == BuildModePlugin && pkg == "main" {
  1201  		pkg = *flagPluginPath
  1202  	}
  1203  	pkg = objabi.PathToPrefix(pkg)
  1204  	name := pkg + arg[dot:eq]
  1205  	value := arg[eq+1:]
  1206  	if _, ok := strdata[name]; !ok {
  1207  		strnames = append(strnames, name)
  1208  	}
  1209  	strdata[name] = value
  1210  }
  1211  
  1212  // addstrdata sets the initial value of the string variable name to value.
  1213  func addstrdata(arch *sys.Arch, l *loader.Loader, name, value string) {
  1214  	s := l.Lookup(name, 0)
  1215  	if s == 0 {
  1216  		return
  1217  	}
  1218  	if goType := l.SymGoType(s); goType == 0 {
  1219  		return
  1220  	} else if typeName := l.SymName(goType); typeName != "type:string" {
  1221  		Errorf("%s: cannot set with -X: not a var of type string (%s)", name, typeName)
  1222  		return
  1223  	}
  1224  	if !l.AttrReachable(s) {
  1225  		return // don't bother setting unreachable variable
  1226  	}
  1227  	bld := l.MakeSymbolUpdater(s)
  1228  	if bld.Type() == sym.SBSS {
  1229  		bld.SetType(sym.SDATA)
  1230  	}
  1231  
  1232  	p := fmt.Sprintf("%s.str", name)
  1233  	sbld := l.CreateSymForUpdate(p, 0)
  1234  	sbld.Addstring(value)
  1235  	sbld.SetType(sym.SRODATA)
  1236  
  1237  	// Don't reset the variable's size. String variable usually has size of
  1238  	// 2*PtrSize, but in ASAN build it can be larger due to red zone.
  1239  	// (See issue 56175.)
  1240  	bld.SetData(make([]byte, arch.PtrSize*2))
  1241  	bld.SetReadOnly(false)
  1242  	bld.ResetRelocs()
  1243  	bld.SetAddrPlus(arch, 0, sbld.Sym(), 0)
  1244  	bld.SetUint(arch, int64(arch.PtrSize), uint64(len(value)))
  1245  }
  1246  
  1247  func (ctxt *Link) dostrdata() {
  1248  	for _, name := range strnames {
  1249  		addstrdata(ctxt.Arch, ctxt.loader, name, strdata[name])
  1250  	}
  1251  }
  1252  
  1253  // addgostring adds str, as a Go string value, to s. symname is the name of the
  1254  // symbol used to define the string data and must be unique per linked object.
  1255  func addgostring(ctxt *Link, ldr *loader.Loader, s *loader.SymbolBuilder, symname, str string) {
  1256  	sdata := ldr.CreateSymForUpdate(symname, 0)
  1257  	if sdata.Type() != sym.Sxxx {
  1258  		ctxt.Errorf(s.Sym(), "duplicate symname in addgostring: %s", symname)
  1259  	}
  1260  	sdata.SetLocal(true)
  1261  	sdata.SetType(sym.SRODATA)
  1262  	sdata.SetSize(int64(len(str)))
  1263  	sdata.SetData([]byte(str))
  1264  	s.AddAddr(ctxt.Arch, sdata.Sym())
  1265  	s.AddUint(ctxt.Arch, uint64(len(str)))
  1266  }
  1267  
  1268  func addinitarrdata(ctxt *Link, ldr *loader.Loader, s loader.Sym) {
  1269  	p := ldr.SymName(s) + ".ptr"
  1270  	sp := ldr.CreateSymForUpdate(p, 0)
  1271  	sp.SetType(sym.SINITARR)
  1272  	sp.SetSize(0)
  1273  	sp.SetDuplicateOK(true)
  1274  	sp.AddAddr(ctxt.Arch, s)
  1275  }
  1276  
  1277  // symalign returns the required alignment for the given symbol s.
  1278  func symalign(ldr *loader.Loader, s loader.Sym) int32 {
  1279  	min := int32(thearch.Minalign)
  1280  	align := ldr.SymAlign(s)
  1281  	if align >= min {
  1282  		return align
  1283  	} else if align != 0 {
  1284  		return min
  1285  	}
  1286  	align = int32(thearch.Maxalign)
  1287  	ssz := ldr.SymSize(s)
  1288  	for int64(align) > ssz && align > min {
  1289  		align >>= 1
  1290  	}
  1291  	ldr.SetSymAlign(s, align)
  1292  	return align
  1293  }
  1294  
  1295  func aligndatsize(state *dodataState, datsize int64, s loader.Sym) int64 {
  1296  	return Rnd(datsize, int64(symalign(state.ctxt.loader, s)))
  1297  }
  1298  
  1299  const debugGCProg = false
  1300  
  1301  type GCProg struct {
  1302  	ctxt *Link
  1303  	sym  *loader.SymbolBuilder
  1304  	w    gcprog.Writer
  1305  }
  1306  
  1307  func (p *GCProg) Init(ctxt *Link, name string) {
  1308  	p.ctxt = ctxt
  1309  	p.sym = ctxt.loader.CreateSymForUpdate(name, 0)
  1310  	p.w.Init(p.writeByte())
  1311  	if debugGCProg {
  1312  		fmt.Fprintf(os.Stderr, "ld: start GCProg %s\n", name)
  1313  		p.w.Debug(os.Stderr)
  1314  	}
  1315  }
  1316  
  1317  func (p *GCProg) writeByte() func(x byte) {
  1318  	return func(x byte) {
  1319  		p.sym.AddUint8(x)
  1320  	}
  1321  }
  1322  
  1323  func (p *GCProg) End(size int64) {
  1324  	p.w.ZeroUntil(size / int64(p.ctxt.Arch.PtrSize))
  1325  	p.w.End()
  1326  	if debugGCProg {
  1327  		fmt.Fprintf(os.Stderr, "ld: end GCProg\n")
  1328  	}
  1329  }
  1330  
  1331  func (p *GCProg) AddSym(s loader.Sym) {
  1332  	ldr := p.ctxt.loader
  1333  	typ := ldr.SymGoType(s)
  1334  
  1335  	// Things without pointers should be in sym.SNOPTRDATA or sym.SNOPTRBSS;
  1336  	// everything we see should have pointers and should therefore have a type.
  1337  	if typ == 0 {
  1338  		switch ldr.SymName(s) {
  1339  		case "runtime.data", "runtime.edata", "runtime.bss", "runtime.ebss":
  1340  			// Ignore special symbols that are sometimes laid out
  1341  			// as real symbols. See comment about dyld on darwin in
  1342  			// the address function.
  1343  			return
  1344  		}
  1345  		p.ctxt.Errorf(p.sym.Sym(), "missing Go type information for global symbol %s: size %d", ldr.SymName(s), ldr.SymSize(s))
  1346  		return
  1347  	}
  1348  
  1349  	ptrsize := int64(p.ctxt.Arch.PtrSize)
  1350  	typData := ldr.Data(typ)
  1351  	nptr := decodetypePtrdata(p.ctxt.Arch, typData) / ptrsize
  1352  
  1353  	if debugGCProg {
  1354  		fmt.Fprintf(os.Stderr, "gcprog sym: %s at %d (ptr=%d+%d)\n", ldr.SymName(s), ldr.SymValue(s), ldr.SymValue(s)/ptrsize, nptr)
  1355  	}
  1356  
  1357  	sval := ldr.SymValue(s)
  1358  	if !decodetypeUsegcprog(p.ctxt.Arch, typData) {
  1359  		// Copy pointers from mask into program.
  1360  		mask := decodetypeGcmask(p.ctxt, typ)
  1361  		for i := int64(0); i < nptr; i++ {
  1362  			if (mask[i/8]>>uint(i%8))&1 != 0 {
  1363  				p.w.Ptr(sval/ptrsize + i)
  1364  			}
  1365  		}
  1366  		return
  1367  	}
  1368  
  1369  	// Copy program.
  1370  	prog := decodetypeGcprog(p.ctxt, typ)
  1371  	p.w.ZeroUntil(sval / ptrsize)
  1372  	p.w.Append(prog[4:], nptr)
  1373  }
  1374  
  1375  // cutoff is the maximum data section size permitted by the linker
  1376  // (see issue #9862).
  1377  const cutoff = 2e9 // 2 GB (or so; looks better in errors than 2^31)
  1378  
  1379  // check accumulated size of data sections
  1380  func (state *dodataState) checkdatsize(symn sym.SymKind) {
  1381  	if state.datsize > cutoff {
  1382  		Errorf("too much data, last section %v (%d, over %v bytes)", symn, state.datsize, cutoff)
  1383  	}
  1384  }
  1385  
  1386  func checkSectSize(sect *sym.Section) {
  1387  	// TODO: consider using 4 GB size limit for DWARF sections, and
  1388  	// make sure we generate unsigned offset in relocations and check
  1389  	// for overflow.
  1390  	if sect.Length > cutoff {
  1391  		Errorf("too much data in section %s (%d, over %v bytes)", sect.Name, sect.Length, cutoff)
  1392  	}
  1393  }
  1394  
  1395  // fixZeroSizedSymbols gives a few special symbols with zero size some space.
  1396  func fixZeroSizedSymbols(ctxt *Link) {
  1397  	// The values in moduledata are filled out by relocations
  1398  	// pointing to the addresses of these special symbols.
  1399  	// Typically these symbols have no size and are not laid
  1400  	// out with their matching section.
  1401  	//
  1402  	// However on darwin, dyld will find the special symbol
  1403  	// in the first loaded module, even though it is local.
  1404  	//
  1405  	// (An hypothesis, formed without looking in the dyld sources:
  1406  	// these special symbols have no size, so their address
  1407  	// matches a real symbol. The dynamic linker assumes we
  1408  	// want the normal symbol with the same address and finds
  1409  	// it in the other module.)
  1410  	//
  1411  	// To work around this we lay out the symbls whose
  1412  	// addresses are vital for multi-module programs to work
  1413  	// as normal symbols, and give them a little size.
  1414  	//
  1415  	// On AIX, as all DATA sections are merged together, ld might not put
  1416  	// these symbols at the beginning of their respective section if there
  1417  	// aren't real symbols, their alignment might not match the
  1418  	// first symbol alignment. Therefore, there are explicitly put at the
  1419  	// beginning of their section with the same alignment.
  1420  	if !(ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) && !(ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
  1421  		return
  1422  	}
  1423  
  1424  	ldr := ctxt.loader
  1425  	bss := ldr.CreateSymForUpdate("runtime.bss", 0)
  1426  	bss.SetSize(8)
  1427  	ldr.SetAttrSpecial(bss.Sym(), false)
  1428  
  1429  	ebss := ldr.CreateSymForUpdate("runtime.ebss", 0)
  1430  	ldr.SetAttrSpecial(ebss.Sym(), false)
  1431  
  1432  	data := ldr.CreateSymForUpdate("runtime.data", 0)
  1433  	data.SetSize(8)
  1434  	ldr.SetAttrSpecial(data.Sym(), false)
  1435  
  1436  	edata := ldr.CreateSymForUpdate("runtime.edata", 0)
  1437  	ldr.SetAttrSpecial(edata.Sym(), false)
  1438  
  1439  	if ctxt.HeadType == objabi.Haix {
  1440  		// XCOFFTOC symbols are part of .data section.
  1441  		edata.SetType(sym.SXCOFFTOC)
  1442  	}
  1443  
  1444  	noptrbss := ldr.CreateSymForUpdate("runtime.noptrbss", 0)
  1445  	noptrbss.SetSize(8)
  1446  	ldr.SetAttrSpecial(noptrbss.Sym(), false)
  1447  
  1448  	enoptrbss := ldr.CreateSymForUpdate("runtime.enoptrbss", 0)
  1449  	ldr.SetAttrSpecial(enoptrbss.Sym(), false)
  1450  
  1451  	noptrdata := ldr.CreateSymForUpdate("runtime.noptrdata", 0)
  1452  	noptrdata.SetSize(8)
  1453  	ldr.SetAttrSpecial(noptrdata.Sym(), false)
  1454  
  1455  	enoptrdata := ldr.CreateSymForUpdate("runtime.enoptrdata", 0)
  1456  	ldr.SetAttrSpecial(enoptrdata.Sym(), false)
  1457  
  1458  	types := ldr.CreateSymForUpdate("runtime.types", 0)
  1459  	types.SetType(sym.STYPE)
  1460  	types.SetSize(8)
  1461  	ldr.SetAttrSpecial(types.Sym(), false)
  1462  
  1463  	etypes := ldr.CreateSymForUpdate("runtime.etypes", 0)
  1464  	etypes.SetType(sym.SFUNCTAB)
  1465  	ldr.SetAttrSpecial(etypes.Sym(), false)
  1466  
  1467  	if ctxt.HeadType == objabi.Haix {
  1468  		rodata := ldr.CreateSymForUpdate("runtime.rodata", 0)
  1469  		rodata.SetType(sym.SSTRING)
  1470  		rodata.SetSize(8)
  1471  		ldr.SetAttrSpecial(rodata.Sym(), false)
  1472  
  1473  		erodata := ldr.CreateSymForUpdate("runtime.erodata", 0)
  1474  		ldr.SetAttrSpecial(erodata.Sym(), false)
  1475  	}
  1476  }
  1477  
  1478  // makeRelroForSharedLib creates a section of readonly data if necessary.
  1479  func (state *dodataState) makeRelroForSharedLib(target *Link) {
  1480  	if !target.UseRelro() {
  1481  		return
  1482  	}
  1483  
  1484  	// "read only" data with relocations needs to go in its own section
  1485  	// when building a shared library. We do this by boosting objects of
  1486  	// type SXXX with relocations to type SXXXRELRO.
  1487  	ldr := target.loader
  1488  	for _, symnro := range sym.ReadOnly {
  1489  		symnrelro := sym.RelROMap[symnro]
  1490  
  1491  		ro := []loader.Sym{}
  1492  		relro := state.data[symnrelro]
  1493  
  1494  		for _, s := range state.data[symnro] {
  1495  			relocs := ldr.Relocs(s)
  1496  			isRelro := relocs.Count() > 0
  1497  			switch state.symType(s) {
  1498  			case sym.STYPE, sym.STYPERELRO, sym.SGOFUNCRELRO:
  1499  				// Symbols are not sorted yet, so it is possible
  1500  				// that an Outer symbol has been changed to a
  1501  				// relro Type before it reaches here.
  1502  				isRelro = true
  1503  			case sym.SFUNCTAB:
  1504  				if ldr.SymName(s) == "runtime.etypes" {
  1505  					// runtime.etypes must be at the end of
  1506  					// the relro data.
  1507  					isRelro = true
  1508  				}
  1509  			case sym.SGOFUNC:
  1510  				// The only SGOFUNC symbols that contain relocations are .stkobj,
  1511  				// and their relocations are of type objabi.R_ADDROFF,
  1512  				// which always get resolved during linking.
  1513  				isRelro = false
  1514  			}
  1515  			if isRelro {
  1516  				if symnrelro == sym.Sxxx {
  1517  					state.ctxt.Errorf(s, "cannot contain relocations (type %v)", symnro)
  1518  				}
  1519  				state.setSymType(s, symnrelro)
  1520  				if outer := ldr.OuterSym(s); outer != 0 {
  1521  					state.setSymType(outer, symnrelro)
  1522  				}
  1523  				relro = append(relro, s)
  1524  			} else {
  1525  				ro = append(ro, s)
  1526  			}
  1527  		}
  1528  
  1529  		// Check that we haven't made two symbols with the same .Outer into
  1530  		// different types (because references two symbols with non-nil Outer
  1531  		// become references to the outer symbol + offset it's vital that the
  1532  		// symbol and the outer end up in the same section).
  1533  		for _, s := range relro {
  1534  			if outer := ldr.OuterSym(s); outer != 0 {
  1535  				st := state.symType(s)
  1536  				ost := state.symType(outer)
  1537  				if st != ost {
  1538  					state.ctxt.Errorf(s, "inconsistent types for symbol and its Outer %s (%v != %v)",
  1539  						ldr.SymName(outer), st, ost)
  1540  				}
  1541  			}
  1542  		}
  1543  
  1544  		state.data[symnro] = ro
  1545  		state.data[symnrelro] = relro
  1546  	}
  1547  }
  1548  
  1549  // dodataState holds bits of state information needed by dodata() and the
  1550  // various helpers it calls. The lifetime of these items should not extend
  1551  // past the end of dodata().
  1552  type dodataState struct {
  1553  	// Link context
  1554  	ctxt *Link
  1555  	// Data symbols bucketed by type.
  1556  	data [sym.SXREF][]loader.Sym
  1557  	// Max alignment for each flavor of data symbol.
  1558  	dataMaxAlign [sym.SXREF]int32
  1559  	// Overridden sym type
  1560  	symGroupType []sym.SymKind
  1561  	// Current data size so far.
  1562  	datsize int64
  1563  }
  1564  
  1565  // A note on symType/setSymType below:
  1566  //
  1567  // In the legacy linker, the types of symbols (notably data symbols) are
  1568  // changed during the symtab() phase so as to insure that similar symbols
  1569  // are bucketed together, then their types are changed back again during
  1570  // dodata. Symbol to section assignment also plays tricks along these lines
  1571  // in the case where a relro segment is needed.
  1572  //
  1573  // The value returned from setType() below reflects the effects of
  1574  // any overrides made by symtab and/or dodata.
  1575  
  1576  // symType returns the (possibly overridden) type of 's'.
  1577  func (state *dodataState) symType(s loader.Sym) sym.SymKind {
  1578  	if int(s) < len(state.symGroupType) {
  1579  		if override := state.symGroupType[s]; override != 0 {
  1580  			return override
  1581  		}
  1582  	}
  1583  	return state.ctxt.loader.SymType(s)
  1584  }
  1585  
  1586  // setSymType sets a new override type for 's'.
  1587  func (state *dodataState) setSymType(s loader.Sym, kind sym.SymKind) {
  1588  	if s == 0 {
  1589  		panic("bad")
  1590  	}
  1591  	if int(s) < len(state.symGroupType) {
  1592  		state.symGroupType[s] = kind
  1593  	} else {
  1594  		su := state.ctxt.loader.MakeSymbolUpdater(s)
  1595  		su.SetType(kind)
  1596  	}
  1597  }
  1598  
  1599  func (ctxt *Link) dodata(symGroupType []sym.SymKind) {
  1600  
  1601  	// Give zeros sized symbols space if necessary.
  1602  	fixZeroSizedSymbols(ctxt)
  1603  
  1604  	// Collect data symbols by type into data.
  1605  	state := dodataState{ctxt: ctxt, symGroupType: symGroupType}
  1606  	ldr := ctxt.loader
  1607  	for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
  1608  		if !ldr.AttrReachable(s) || ldr.AttrSpecial(s) || ldr.AttrSubSymbol(s) ||
  1609  			!ldr.TopLevelSym(s) {
  1610  			continue
  1611  		}
  1612  
  1613  		st := state.symType(s)
  1614  
  1615  		if st <= sym.STEXT || st >= sym.SXREF {
  1616  			continue
  1617  		}
  1618  		state.data[st] = append(state.data[st], s)
  1619  
  1620  		// Similarly with checking the onlist attr.
  1621  		if ldr.AttrOnList(s) {
  1622  			log.Fatalf("symbol %s listed multiple times", ldr.SymName(s))
  1623  		}
  1624  		ldr.SetAttrOnList(s, true)
  1625  	}
  1626  
  1627  	// Now that we have the data symbols, but before we start
  1628  	// to assign addresses, record all the necessary
  1629  	// dynamic relocations. These will grow the relocation
  1630  	// symbol, which is itself data.
  1631  	//
  1632  	// On darwin, we need the symbol table numbers for dynreloc.
  1633  	if ctxt.HeadType == objabi.Hdarwin {
  1634  		machosymorder(ctxt)
  1635  	}
  1636  	state.dynreloc(ctxt)
  1637  
  1638  	// Move any RO data with relocations to a separate section.
  1639  	state.makeRelroForSharedLib(ctxt)
  1640  
  1641  	// Set alignment for the symbol with the largest known index,
  1642  	// so as to trigger allocation of the loader's internal
  1643  	// alignment array. This will avoid data races in the parallel
  1644  	// section below.
  1645  	lastSym := loader.Sym(ldr.NSym() - 1)
  1646  	ldr.SetSymAlign(lastSym, ldr.SymAlign(lastSym))
  1647  
  1648  	// Sort symbols.
  1649  	var wg sync.WaitGroup
  1650  	for symn := range state.data {
  1651  		symn := sym.SymKind(symn)
  1652  		wg.Add(1)
  1653  		go func() {
  1654  			state.data[symn], state.dataMaxAlign[symn] = state.dodataSect(ctxt, symn, state.data[symn])
  1655  			wg.Done()
  1656  		}()
  1657  	}
  1658  	wg.Wait()
  1659  
  1660  	if ctxt.IsELF {
  1661  		// Make .rela and .rela.plt contiguous, the ELF ABI requires this
  1662  		// and Solaris actually cares.
  1663  		syms := state.data[sym.SELFROSECT]
  1664  		reli, plti := -1, -1
  1665  		for i, s := range syms {
  1666  			switch ldr.SymName(s) {
  1667  			case ".rel.plt", ".rela.plt":
  1668  				plti = i
  1669  			case ".rel", ".rela":
  1670  				reli = i
  1671  			}
  1672  		}
  1673  		if reli >= 0 && plti >= 0 && plti != reli+1 {
  1674  			var first, second int
  1675  			if plti > reli {
  1676  				first, second = reli, plti
  1677  			} else {
  1678  				first, second = plti, reli
  1679  			}
  1680  			rel, plt := syms[reli], syms[plti]
  1681  			copy(syms[first+2:], syms[first+1:second])
  1682  			syms[first+0] = rel
  1683  			syms[first+1] = plt
  1684  
  1685  			// Make sure alignment doesn't introduce a gap.
  1686  			// Setting the alignment explicitly prevents
  1687  			// symalign from basing it on the size and
  1688  			// getting it wrong.
  1689  			ldr.SetSymAlign(rel, int32(ctxt.Arch.RegSize))
  1690  			ldr.SetSymAlign(plt, int32(ctxt.Arch.RegSize))
  1691  		}
  1692  		state.data[sym.SELFROSECT] = syms
  1693  	}
  1694  
  1695  	if ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal {
  1696  		// These symbols must have the same alignment as their section.
  1697  		// Otherwise, ld might change the layout of Go sections.
  1698  		ldr.SetSymAlign(ldr.Lookup("runtime.data", 0), state.dataMaxAlign[sym.SDATA])
  1699  		ldr.SetSymAlign(ldr.Lookup("runtime.bss", 0), state.dataMaxAlign[sym.SBSS])
  1700  	}
  1701  
  1702  	// Create *sym.Section objects and assign symbols to sections for
  1703  	// data/rodata (and related) symbols.
  1704  	state.allocateDataSections(ctxt)
  1705  
  1706  	state.allocateSEHSections(ctxt)
  1707  
  1708  	// Create *sym.Section objects and assign symbols to sections for
  1709  	// DWARF symbols.
  1710  	state.allocateDwarfSections(ctxt)
  1711  
  1712  	/* number the sections */
  1713  	n := int16(1)
  1714  
  1715  	for _, sect := range Segtext.Sections {
  1716  		sect.Extnum = n
  1717  		n++
  1718  	}
  1719  	for _, sect := range Segrodata.Sections {
  1720  		sect.Extnum = n
  1721  		n++
  1722  	}
  1723  	for _, sect := range Segrelrodata.Sections {
  1724  		sect.Extnum = n
  1725  		n++
  1726  	}
  1727  	for _, sect := range Segdata.Sections {
  1728  		sect.Extnum = n
  1729  		n++
  1730  	}
  1731  	for _, sect := range Segdwarf.Sections {
  1732  		sect.Extnum = n
  1733  		n++
  1734  	}
  1735  	for _, sect := range Segpdata.Sections {
  1736  		sect.Extnum = n
  1737  		n++
  1738  	}
  1739  	for _, sect := range Segxdata.Sections {
  1740  		sect.Extnum = n
  1741  		n++
  1742  	}
  1743  }
  1744  
  1745  // allocateDataSectionForSym creates a new sym.Section into which a
  1746  // single symbol will be placed. Here "seg" is the segment into which
  1747  // the section will go, "s" is the symbol to be placed into the new
  1748  // section, and "rwx" contains permissions for the section.
  1749  func (state *dodataState) allocateDataSectionForSym(seg *sym.Segment, s loader.Sym, rwx int) *sym.Section {
  1750  	ldr := state.ctxt.loader
  1751  	sname := ldr.SymName(s)
  1752  	if strings.HasPrefix(sname, "go:") {
  1753  		sname = ".go." + sname[len("go:"):]
  1754  	}
  1755  	sect := addsection(ldr, state.ctxt.Arch, seg, sname, rwx)
  1756  	sect.Align = symalign(ldr, s)
  1757  	state.datsize = Rnd(state.datsize, int64(sect.Align))
  1758  	sect.Vaddr = uint64(state.datsize)
  1759  	return sect
  1760  }
  1761  
  1762  // allocateNamedDataSection creates a new sym.Section for a category
  1763  // of data symbols. Here "seg" is the segment into which the section
  1764  // will go, "sName" is the name to give to the section, "types" is a
  1765  // range of symbol types to be put into the section, and "rwx"
  1766  // contains permissions for the section.
  1767  func (state *dodataState) allocateNamedDataSection(seg *sym.Segment, sName string, types []sym.SymKind, rwx int) *sym.Section {
  1768  	sect := addsection(state.ctxt.loader, state.ctxt.Arch, seg, sName, rwx)
  1769  	if len(types) == 0 {
  1770  		sect.Align = 1
  1771  	} else if len(types) == 1 {
  1772  		sect.Align = state.dataMaxAlign[types[0]]
  1773  	} else {
  1774  		for _, symn := range types {
  1775  			align := state.dataMaxAlign[symn]
  1776  			if sect.Align < align {
  1777  				sect.Align = align
  1778  			}
  1779  		}
  1780  	}
  1781  	state.datsize = Rnd(state.datsize, int64(sect.Align))
  1782  	sect.Vaddr = uint64(state.datsize)
  1783  	return sect
  1784  }
  1785  
  1786  // assignDsymsToSection assigns a collection of data symbols to a
  1787  // newly created section. "sect" is the section into which to place
  1788  // the symbols, "syms" holds the list of symbols to assign,
  1789  // "forceType" (if non-zero) contains a new sym type to apply to each
  1790  // sym during the assignment, and "aligner" is a hook to call to
  1791  // handle alignment during the assignment process.
  1792  func (state *dodataState) assignDsymsToSection(sect *sym.Section, syms []loader.Sym, forceType sym.SymKind, aligner func(state *dodataState, datsize int64, s loader.Sym) int64) {
  1793  	ldr := state.ctxt.loader
  1794  	for _, s := range syms {
  1795  		state.datsize = aligner(state, state.datsize, s)
  1796  		ldr.SetSymSect(s, sect)
  1797  		if forceType != sym.Sxxx {
  1798  			state.setSymType(s, forceType)
  1799  		}
  1800  		ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
  1801  		state.datsize += ldr.SymSize(s)
  1802  	}
  1803  	sect.Length = uint64(state.datsize) - sect.Vaddr
  1804  }
  1805  
  1806  func (state *dodataState) assignToSection(sect *sym.Section, symn sym.SymKind, forceType sym.SymKind) {
  1807  	state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
  1808  	state.checkdatsize(symn)
  1809  }
  1810  
  1811  // allocateSingleSymSections walks through the bucketed data symbols
  1812  // with type 'symn', creates a new section for each sym, and assigns
  1813  // the sym to a newly created section. Section name is set from the
  1814  // symbol name. "Seg" is the segment into which to place the new
  1815  // section, "forceType" is the new sym.SymKind to assign to the symbol
  1816  // within the section, and "rwx" holds section permissions.
  1817  func (state *dodataState) allocateSingleSymSections(seg *sym.Segment, symn sym.SymKind, forceType sym.SymKind, rwx int) {
  1818  	ldr := state.ctxt.loader
  1819  	for _, s := range state.data[symn] {
  1820  		sect := state.allocateDataSectionForSym(seg, s, rwx)
  1821  		ldr.SetSymSect(s, sect)
  1822  		state.setSymType(s, forceType)
  1823  		ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
  1824  		state.datsize += ldr.SymSize(s)
  1825  		sect.Length = uint64(state.datsize) - sect.Vaddr
  1826  	}
  1827  	state.checkdatsize(symn)
  1828  }
  1829  
  1830  // allocateNamedSectionAndAssignSyms creates a new section with the
  1831  // specified name, then walks through the bucketed data symbols with
  1832  // type 'symn' and assigns each of them to this new section. "Seg" is
  1833  // the segment into which to place the new section, "secName" is the
  1834  // name to give to the new section, "forceType" (if non-zero) contains
  1835  // a new sym type to apply to each sym during the assignment, and
  1836  // "rwx" holds section permissions.
  1837  func (state *dodataState) allocateNamedSectionAndAssignSyms(seg *sym.Segment, secName string, symn sym.SymKind, forceType sym.SymKind, rwx int) *sym.Section {
  1838  
  1839  	sect := state.allocateNamedDataSection(seg, secName, []sym.SymKind{symn}, rwx)
  1840  	state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
  1841  	return sect
  1842  }
  1843  
  1844  // allocateDataSections allocates sym.Section objects for data/rodata
  1845  // (and related) symbols, and then assigns symbols to those sections.
  1846  func (state *dodataState) allocateDataSections(ctxt *Link) {
  1847  	// Allocate sections.
  1848  	// Data is processed before segtext, because we need
  1849  	// to see all symbols in the .data and .bss sections in order
  1850  	// to generate garbage collection information.
  1851  
  1852  	// Writable data sections that do not need any specialized handling.
  1853  	writable := []sym.SymKind{
  1854  		sym.SBUILDINFO,
  1855  		sym.SFIPSINFO,
  1856  		sym.SELFSECT,
  1857  		sym.SMACHO,
  1858  		sym.SMACHOGOT,
  1859  		sym.SWINDOWS,
  1860  	}
  1861  	for _, symn := range writable {
  1862  		state.allocateSingleSymSections(&Segdata, symn, sym.SDATA, 06)
  1863  	}
  1864  	ldr := ctxt.loader
  1865  
  1866  	// writable .got (note that for PIE binaries .got goes in relro)
  1867  	if len(state.data[sym.SELFGOT]) > 0 {
  1868  		state.allocateNamedSectionAndAssignSyms(&Segdata, ".got", sym.SELFGOT, sym.SDATA, 06)
  1869  	}
  1870  
  1871  	/* pointer-free data */
  1872  	sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrdata", sym.SNOPTRDATA, sym.SDATA, 06)
  1873  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrdata", 0), sect)
  1874  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrdata", 0), sect)
  1875  
  1876  	state.assignToSection(sect, sym.SNOPTRDATAFIPSSTART, sym.SDATA)
  1877  	state.assignToSection(sect, sym.SNOPTRDATAFIPS, sym.SDATA)
  1878  	state.assignToSection(sect, sym.SNOPTRDATAFIPSEND, sym.SDATA)
  1879  	state.assignToSection(sect, sym.SNOPTRDATAEND, sym.SDATA)
  1880  
  1881  	hasinitarr := ctxt.linkShared
  1882  
  1883  	/* shared library initializer */
  1884  	switch ctxt.BuildMode {
  1885  	case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePlugin:
  1886  		hasinitarr = true
  1887  	}
  1888  
  1889  	if ctxt.HeadType == objabi.Haix {
  1890  		if len(state.data[sym.SINITARR]) > 0 {
  1891  			Errorf("XCOFF format doesn't allow .init_array section")
  1892  		}
  1893  	}
  1894  
  1895  	if hasinitarr && len(state.data[sym.SINITARR]) > 0 {
  1896  		state.allocateNamedSectionAndAssignSyms(&Segdata, ".init_array", sym.SINITARR, sym.Sxxx, 06)
  1897  	}
  1898  
  1899  	/* data */
  1900  	sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".data", sym.SDATA, sym.SDATA, 06)
  1901  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.data", 0), sect)
  1902  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.edata", 0), sect)
  1903  
  1904  	state.assignToSection(sect, sym.SDATAFIPSSTART, sym.SDATA)
  1905  	state.assignToSection(sect, sym.SDATAFIPS, sym.SDATA)
  1906  	state.assignToSection(sect, sym.SDATAFIPSEND, sym.SDATA)
  1907  	state.assignToSection(sect, sym.SDATAEND, sym.SDATA)
  1908  
  1909  	dataGcEnd := state.datsize - int64(sect.Vaddr)
  1910  
  1911  	// On AIX, TOC entries must be the last of .data
  1912  	// These aren't part of gc as they won't change during the runtime.
  1913  	state.assignToSection(sect, sym.SXCOFFTOC, sym.SDATA)
  1914  	state.checkdatsize(sym.SDATA)
  1915  	sect.Length = uint64(state.datsize) - sect.Vaddr
  1916  
  1917  	/* bss */
  1918  	sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".bss", sym.SBSS, sym.Sxxx, 06)
  1919  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.bss", 0), sect)
  1920  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ebss", 0), sect)
  1921  	bssGcEnd := state.datsize - int64(sect.Vaddr)
  1922  
  1923  	// Emit gcdata for bss symbols now that symbol values have been assigned.
  1924  	gcsToEmit := []struct {
  1925  		symName string
  1926  		symKind sym.SymKind
  1927  		gcEnd   int64
  1928  	}{
  1929  		{"runtime.gcdata", sym.SDATA, dataGcEnd},
  1930  		{"runtime.gcbss", sym.SBSS, bssGcEnd},
  1931  	}
  1932  	for _, g := range gcsToEmit {
  1933  		var gc GCProg
  1934  		gc.Init(ctxt, g.symName)
  1935  		for _, s := range state.data[g.symKind] {
  1936  			gc.AddSym(s)
  1937  		}
  1938  		gc.End(g.gcEnd)
  1939  	}
  1940  
  1941  	/* pointer-free bss */
  1942  	sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrbss", sym.SNOPTRBSS, sym.Sxxx, 06)
  1943  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrbss", 0), sect)
  1944  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrbss", 0), sect)
  1945  
  1946  	// Code coverage counters are assigned to the .noptrbss section.
  1947  	// We assign them in a separate pass so that they stay aggregated
  1948  	// together in a single blob (coverage runtime depends on this).
  1949  	covCounterDataStartOff = sect.Length
  1950  	state.assignToSection(sect, sym.SCOVERAGE_COUNTER, sym.SNOPTRBSS)
  1951  	covCounterDataLen = sect.Length - covCounterDataStartOff
  1952  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.covctrs", 0), sect)
  1953  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ecovctrs", 0), sect)
  1954  
  1955  	// Coverage instrumentation counters for libfuzzer.
  1956  	if len(state.data[sym.SLIBFUZZER_8BIT_COUNTER]) > 0 {
  1957  		sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".go.fuzzcntrs", sym.SLIBFUZZER_8BIT_COUNTER, sym.Sxxx, 06)
  1958  		ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.__start___sancov_cntrs", 0), sect)
  1959  		ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.__stop___sancov_cntrs", 0), sect)
  1960  		ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._counters", 0), sect)
  1961  		ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._ecounters", 0), sect)
  1962  	}
  1963  
  1964  	// Assign runtime.end to the last section of data segment.
  1965  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.end", 0), Segdata.Sections[len(Segdata.Sections)-1])
  1966  
  1967  	if len(state.data[sym.STLSBSS]) > 0 {
  1968  		var sect *sym.Section
  1969  		// FIXME: not clear why it is sometimes necessary to suppress .tbss section creation.
  1970  		if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && (ctxt.LinkMode == LinkExternal || !*FlagD) {
  1971  			sect = addsection(ldr, ctxt.Arch, &Segdata, ".tbss", 06)
  1972  			sect.Align = int32(ctxt.Arch.PtrSize)
  1973  			// FIXME: why does this need to be set to zero?
  1974  			sect.Vaddr = 0
  1975  		}
  1976  		state.datsize = 0
  1977  
  1978  		for _, s := range state.data[sym.STLSBSS] {
  1979  			state.datsize = aligndatsize(state, state.datsize, s)
  1980  			if sect != nil {
  1981  				ldr.SetSymSect(s, sect)
  1982  			}
  1983  			ldr.SetSymValue(s, state.datsize)
  1984  			state.datsize += ldr.SymSize(s)
  1985  		}
  1986  		state.checkdatsize(sym.STLSBSS)
  1987  
  1988  		if sect != nil {
  1989  			sect.Length = uint64(state.datsize)
  1990  		}
  1991  	}
  1992  
  1993  	/*
  1994  	 * We finished data, begin read-only data.
  1995  	 * Not all systems support a separate read-only non-executable data section.
  1996  	 * ELF and Windows PE systems do.
  1997  	 * OS X and Plan 9 do not.
  1998  	 * And if we're using external linking mode, the point is moot,
  1999  	 * since it's not our decision; that code expects the sections in
  2000  	 * segtext.
  2001  	 */
  2002  	var segro *sym.Segment
  2003  	if ctxt.IsELF && ctxt.LinkMode == LinkInternal {
  2004  		segro = &Segrodata
  2005  	} else if ctxt.HeadType == objabi.Hwindows {
  2006  		segro = &Segrodata
  2007  	} else {
  2008  		segro = &Segtext
  2009  	}
  2010  
  2011  	state.datsize = 0
  2012  
  2013  	/* read-only executable ELF, Mach-O sections */
  2014  	if len(state.data[sym.STEXT]) != 0 {
  2015  		culprit := ldr.SymName(state.data[sym.STEXT][0])
  2016  		Errorf("dodata found an sym.STEXT symbol: %s", culprit)
  2017  	}
  2018  	state.allocateSingleSymSections(&Segtext, sym.SELFRXSECT, sym.SRODATA, 05)
  2019  	state.allocateSingleSymSections(&Segtext, sym.SMACHOPLT, sym.SRODATA, 05)
  2020  
  2021  	/* read-only data */
  2022  	sect = state.allocateNamedDataSection(segro, ".rodata", sym.ReadOnly, 04)
  2023  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.rodata", 0), sect)
  2024  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.erodata", 0), sect)
  2025  	if !ctxt.UseRelro() {
  2026  		ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
  2027  		ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
  2028  	}
  2029  	for _, symn := range sym.ReadOnly {
  2030  		symnStartValue := state.datsize
  2031  		if len(state.data[symn]) != 0 {
  2032  			symnStartValue = aligndatsize(state, symnStartValue, state.data[symn][0])
  2033  		}
  2034  		state.assignToSection(sect, symn, sym.SRODATA)
  2035  		setCarrierSize(symn, state.datsize-symnStartValue)
  2036  		if ctxt.HeadType == objabi.Haix {
  2037  			// Read-only symbols might be wrapped inside their outer
  2038  			// symbol.
  2039  			// XCOFF symbol table needs to know the size of
  2040  			// these outer symbols.
  2041  			xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
  2042  		}
  2043  	}
  2044  
  2045  	/* read-only ELF, Mach-O sections */
  2046  	state.allocateSingleSymSections(segro, sym.SELFROSECT, sym.SRODATA, 04)
  2047  
  2048  	// There is some data that are conceptually read-only but are written to by
  2049  	// relocations. On GNU systems, we can arrange for the dynamic linker to
  2050  	// mprotect sections after relocations are applied by giving them write
  2051  	// permissions in the object file and calling them ".data.rel.ro.FOO". We
  2052  	// divide the .rodata section between actual .rodata and .data.rel.ro.rodata,
  2053  	// but for the other sections that this applies to, we just write a read-only
  2054  	// .FOO section or a read-write .data.rel.ro.FOO section depending on the
  2055  	// situation.
  2056  	// TODO(mwhudson): It would make sense to do this more widely, but it makes
  2057  	// the system linker segfault on darwin.
  2058  	const relroPerm = 06
  2059  	const fallbackPerm = 04
  2060  	relroSecPerm := fallbackPerm
  2061  	genrelrosecname := func(suffix string) string {
  2062  		if suffix == "" {
  2063  			return ".rodata"
  2064  		}
  2065  		return suffix
  2066  	}
  2067  	seg := segro
  2068  
  2069  	if ctxt.UseRelro() {
  2070  		segrelro := &Segrelrodata
  2071  		if ctxt.LinkMode == LinkExternal && !ctxt.IsAIX() && !ctxt.IsDarwin() {
  2072  			// Using a separate segment with an external
  2073  			// linker results in some programs moving
  2074  			// their data sections unexpectedly, which
  2075  			// corrupts the moduledata. So we use the
  2076  			// rodata segment and let the external linker
  2077  			// sort out a rel.ro segment.
  2078  			segrelro = segro
  2079  		} else {
  2080  			// Reset datsize for new segment.
  2081  			state.datsize = 0
  2082  		}
  2083  
  2084  		if !ctxt.IsDarwin() { // We don't need the special names on darwin.
  2085  			genrelrosecname = func(suffix string) string {
  2086  				return ".data.rel.ro" + suffix
  2087  			}
  2088  		}
  2089  
  2090  		relroReadOnly := []sym.SymKind{}
  2091  		for _, symnro := range sym.ReadOnly {
  2092  			symn := sym.RelROMap[symnro]
  2093  			relroReadOnly = append(relroReadOnly, symn)
  2094  		}
  2095  		seg = segrelro
  2096  		relroSecPerm = relroPerm
  2097  
  2098  		/* data only written by relocations */
  2099  		sect = state.allocateNamedDataSection(segrelro, genrelrosecname(""), relroReadOnly, relroSecPerm)
  2100  
  2101  		ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
  2102  		ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
  2103  
  2104  		for i, symnro := range sym.ReadOnly {
  2105  			if i == 0 && symnro == sym.STYPE && ctxt.HeadType != objabi.Haix {
  2106  				// Skip forward so that no type
  2107  				// reference uses a zero offset.
  2108  				// This is unlikely but possible in small
  2109  				// programs with no other read-only data.
  2110  				state.datsize++
  2111  			}
  2112  
  2113  			symn := sym.RelROMap[symnro]
  2114  			if symn == sym.Sxxx {
  2115  				continue
  2116  			}
  2117  			symnStartValue := state.datsize
  2118  			if len(state.data[symn]) != 0 {
  2119  				symnStartValue = aligndatsize(state, symnStartValue, state.data[symn][0])
  2120  			}
  2121  
  2122  			for _, s := range state.data[symn] {
  2123  				outer := ldr.OuterSym(s)
  2124  				if s != 0 && ldr.SymSect(outer) != nil && ldr.SymSect(outer) != sect {
  2125  					ctxt.Errorf(s, "s.Outer (%s) in different section from s, %s != %s", ldr.SymName(outer), ldr.SymSect(outer).Name, sect.Name)
  2126  				}
  2127  			}
  2128  			state.assignToSection(sect, symn, sym.SRODATA)
  2129  			setCarrierSize(symn, state.datsize-symnStartValue)
  2130  			if ctxt.HeadType == objabi.Haix {
  2131  				// Read-only symbols might be wrapped inside their outer
  2132  				// symbol.
  2133  				// XCOFF symbol table needs to know the size of
  2134  				// these outer symbols.
  2135  				xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
  2136  			}
  2137  		}
  2138  		sect.Length = uint64(state.datsize) - sect.Vaddr
  2139  
  2140  		state.allocateSingleSymSections(segrelro, sym.SELFRELROSECT, sym.SRODATA, relroSecPerm)
  2141  	}
  2142  
  2143  	/* typelink */
  2144  	sect = state.allocateNamedDataSection(seg, genrelrosecname(".typelink"), []sym.SymKind{sym.STYPELINK}, relroSecPerm)
  2145  
  2146  	typelink := ldr.CreateSymForUpdate("runtime.typelink", 0)
  2147  	ldr.SetSymSect(typelink.Sym(), sect)
  2148  	typelink.SetType(sym.SRODATA)
  2149  	state.datsize += typelink.Size()
  2150  	state.checkdatsize(sym.STYPELINK)
  2151  	sect.Length = uint64(state.datsize) - sect.Vaddr
  2152  
  2153  	/* itablink */
  2154  	sect = state.allocateNamedDataSection(seg, genrelrosecname(".itablink"), []sym.SymKind{sym.SITABLINK}, relroSecPerm)
  2155  
  2156  	itablink := ldr.CreateSymForUpdate("runtime.itablink", 0)
  2157  	ldr.SetSymSect(itablink.Sym(), sect)
  2158  	itablink.SetType(sym.SRODATA)
  2159  	state.datsize += itablink.Size()
  2160  	state.checkdatsize(sym.SITABLINK)
  2161  	sect.Length = uint64(state.datsize) - sect.Vaddr
  2162  
  2163  	/* gosymtab */
  2164  	sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gosymtab"), sym.SSYMTAB, sym.SRODATA, relroSecPerm)
  2165  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.symtab", 0), sect)
  2166  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.esymtab", 0), sect)
  2167  
  2168  	/* gopclntab */
  2169  	sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gopclntab"), sym.SPCLNTAB, sym.SRODATA, relroSecPerm)
  2170  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0), sect)
  2171  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pcheader", 0), sect)
  2172  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.funcnametab", 0), sect)
  2173  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.cutab", 0), sect)
  2174  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.filetab", 0), sect)
  2175  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pctab", 0), sect)
  2176  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.functab", 0), sect)
  2177  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.epclntab", 0), sect)
  2178  	setCarrierSize(sym.SPCLNTAB, int64(sect.Length))
  2179  	if ctxt.HeadType == objabi.Haix {
  2180  		xcoffUpdateOuterSize(ctxt, int64(sect.Length), sym.SPCLNTAB)
  2181  	}
  2182  
  2183  	// 6g uses 4-byte relocation offsets, so the entire segment must fit in 32 bits.
  2184  	if state.datsize != int64(uint32(state.datsize)) {
  2185  		Errorf("read-only data segment too large: %d", state.datsize)
  2186  	}
  2187  
  2188  	siz := 0
  2189  	for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
  2190  		siz += len(state.data[symn])
  2191  	}
  2192  	ctxt.datap = make([]loader.Sym, 0, siz)
  2193  	for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
  2194  		ctxt.datap = append(ctxt.datap, state.data[symn]...)
  2195  	}
  2196  }
  2197  
  2198  // allocateDwarfSections allocates sym.Section objects for DWARF
  2199  // symbols, and assigns symbols to sections.
  2200  func (state *dodataState) allocateDwarfSections(ctxt *Link) {
  2201  
  2202  	alignOne := func(state *dodataState, datsize int64, s loader.Sym) int64 { return datsize }
  2203  
  2204  	ldr := ctxt.loader
  2205  	for i := 0; i < len(dwarfp); i++ {
  2206  		// First the section symbol.
  2207  		s := dwarfp[i].secSym()
  2208  		sect := state.allocateNamedDataSection(&Segdwarf, ldr.SymName(s), []sym.SymKind{}, 04)
  2209  		ldr.SetSymSect(s, sect)
  2210  		sect.Sym = sym.LoaderSym(s)
  2211  		curType := ldr.SymType(s)
  2212  		state.setSymType(s, sym.SRODATA)
  2213  		ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
  2214  		state.datsize += ldr.SymSize(s)
  2215  
  2216  		// Then any sub-symbols for the section symbol.
  2217  		subSyms := dwarfp[i].subSyms()
  2218  		state.assignDsymsToSection(sect, subSyms, sym.SRODATA, alignOne)
  2219  
  2220  		for j := 0; j < len(subSyms); j++ {
  2221  			s := subSyms[j]
  2222  			if ctxt.HeadType == objabi.Haix && curType == sym.SDWARFLOC {
  2223  				// Update the size of .debug_loc for this symbol's
  2224  				// package.
  2225  				addDwsectCUSize(".debug_loc", ldr.SymPkg(s), uint64(ldr.SymSize(s)))
  2226  			}
  2227  		}
  2228  		sect.Length = uint64(state.datsize) - sect.Vaddr
  2229  		checkSectSize(sect)
  2230  	}
  2231  }
  2232  
  2233  // allocateSEHSections allocate a sym.Section object for SEH
  2234  // symbols, and assigns symbols to sections.
  2235  func (state *dodataState) allocateSEHSections(ctxt *Link) {
  2236  	if len(sehp.pdata) > 0 {
  2237  		sect := state.allocateNamedDataSection(&Segpdata, ".pdata", []sym.SymKind{}, 04)
  2238  		state.assignDsymsToSection(sect, sehp.pdata, sym.SRODATA, aligndatsize)
  2239  		state.checkdatsize(sym.SSEHSECT)
  2240  	}
  2241  	if len(sehp.xdata) > 0 {
  2242  		sect := state.allocateNamedDataSection(&Segxdata, ".xdata", []sym.SymKind{}, 04)
  2243  		state.assignDsymsToSection(sect, sehp.xdata, sym.SRODATA, aligndatsize)
  2244  		state.checkdatsize(sym.SSEHSECT)
  2245  	}
  2246  }
  2247  
  2248  type symNameSize struct {
  2249  	name string
  2250  	sz   int64
  2251  	val  int64
  2252  	sym  loader.Sym
  2253  }
  2254  
  2255  func (state *dodataState) dodataSect(ctxt *Link, symn sym.SymKind, syms []loader.Sym) (result []loader.Sym, maxAlign int32) {
  2256  	var head, tail, zerobase loader.Sym
  2257  	ldr := ctxt.loader
  2258  	sl := make([]symNameSize, len(syms))
  2259  
  2260  	// For ppc64, we want to interleave the .got and .toc sections
  2261  	// from input files. Both are type sym.SELFGOT, so in that case
  2262  	// we skip size comparison and do the name comparison instead
  2263  	// (conveniently, .got sorts before .toc).
  2264  	sortBySize := symn != sym.SELFGOT
  2265  
  2266  	for k, s := range syms {
  2267  		ss := ldr.SymSize(s)
  2268  		sl[k] = symNameSize{sz: ss, sym: s}
  2269  		if !sortBySize {
  2270  			sl[k].name = ldr.SymName(s)
  2271  		}
  2272  		ds := int64(len(ldr.Data(s)))
  2273  		switch {
  2274  		case ss < ds:
  2275  			ctxt.Errorf(s, "initialize bounds (%d < %d)", ss, ds)
  2276  		case ss < 0:
  2277  			ctxt.Errorf(s, "negative size (%d bytes)", ss)
  2278  		case ss > cutoff:
  2279  			ctxt.Errorf(s, "symbol too large (%d bytes)", ss)
  2280  		}
  2281  
  2282  		// If the usually-special section-marker symbols are being laid
  2283  		// out as regular symbols, put them either at the beginning or
  2284  		// end of their section.
  2285  		if (ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) || (ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
  2286  			switch ldr.SymName(s) {
  2287  			case "runtime.text", "runtime.bss", "runtime.data", "runtime.types", "runtime.rodata",
  2288  				"runtime.noptrdata", "runtime.noptrbss":
  2289  				head = s
  2290  				continue
  2291  			case "runtime.etext", "runtime.ebss", "runtime.edata", "runtime.etypes", "runtime.erodata",
  2292  				"runtime.enoptrdata", "runtime.enoptrbss":
  2293  				tail = s
  2294  				continue
  2295  			}
  2296  		}
  2297  	}
  2298  	zerobase = ldr.Lookup("runtime.zerobase", 0)
  2299  
  2300  	// Perform the sort.
  2301  	if symn != sym.SPCLNTAB {
  2302  		sort.Slice(sl, func(i, j int) bool {
  2303  			si, sj := sl[i].sym, sl[j].sym
  2304  			isz, jsz := sl[i].sz, sl[j].sz
  2305  			switch {
  2306  			case si == head, sj == tail:
  2307  				return true
  2308  			case sj == head, si == tail:
  2309  				return false
  2310  			}
  2311  			if sortBySize {
  2312  				switch {
  2313  				// put zerobase right after all the zero-sized symbols,
  2314  				// so zero-sized symbols have the same address as zerobase.
  2315  				case si == zerobase:
  2316  					return jsz != 0 // zerobase < nonzero-sized, zerobase > zero-sized
  2317  				case sj == zerobase:
  2318  					return isz == 0 // 0-sized < zerobase, nonzero-sized > zerobase
  2319  				case isz != jsz:
  2320  					return isz < jsz
  2321  				}
  2322  			} else {
  2323  				iname := sl[i].name
  2324  				jname := sl[j].name
  2325  				if iname != jname {
  2326  					return iname < jname
  2327  				}
  2328  			}
  2329  			return si < sj // break ties by symbol number
  2330  		})
  2331  	} else {
  2332  		// PCLNTAB was built internally, and already has the proper order.
  2333  	}
  2334  
  2335  	// Set alignment, construct result
  2336  	syms = syms[:0]
  2337  	for k := range sl {
  2338  		s := sl[k].sym
  2339  		if s != head && s != tail {
  2340  			align := symalign(ldr, s)
  2341  			if maxAlign < align {
  2342  				maxAlign = align
  2343  			}
  2344  		}
  2345  		syms = append(syms, s)
  2346  	}
  2347  
  2348  	return syms, maxAlign
  2349  }
  2350  
  2351  // Add buildid to beginning of text segment, on non-ELF systems.
  2352  // Non-ELF binary formats are not always flexible enough to
  2353  // give us a place to put the Go build ID. On those systems, we put it
  2354  // at the very beginning of the text segment.
  2355  // This “header” is read by cmd/go.
  2356  func (ctxt *Link) textbuildid() {
  2357  	if ctxt.IsELF || *flagBuildid == "" {
  2358  		return
  2359  	}
  2360  
  2361  	ldr := ctxt.loader
  2362  	s := ldr.CreateSymForUpdate("go:buildid", 0)
  2363  	// The \xff is invalid UTF-8, meant to make it less likely
  2364  	// to find one of these accidentally.
  2365  	data := "\xff Go build ID: " + strconv.Quote(*flagBuildid) + "\n \xff"
  2366  	s.SetType(sym.STEXT)
  2367  	s.SetData([]byte(data))
  2368  	s.SetSize(int64(len(data)))
  2369  
  2370  	ctxt.Textp = append(ctxt.Textp, 0)
  2371  	copy(ctxt.Textp[1:], ctxt.Textp)
  2372  	ctxt.Textp[0] = s.Sym()
  2373  }
  2374  
  2375  func (ctxt *Link) buildinfo() {
  2376  	// Write the buildinfo symbol, which go version looks for.
  2377  	// The code reading this data is in package debug/buildinfo.
  2378  	ldr := ctxt.loader
  2379  	s := ldr.CreateSymForUpdate("go:buildinfo", 0)
  2380  	s.SetType(sym.SBUILDINFO)
  2381  	s.SetAlign(16)
  2382  
  2383  	// The \xff is invalid UTF-8, meant to make it less likely
  2384  	// to find one of these accidentally.
  2385  	const prefix = "\xff Go buildinf:" // 14 bytes, plus 1 data byte filled in below
  2386  
  2387  	// Header is always 32-bytes, a hold-over from before
  2388  	// https://go.dev/cl/369977.
  2389  	data := make([]byte, 32)
  2390  	copy(data, prefix)
  2391  	data[len(prefix)] = byte(ctxt.Arch.PtrSize)
  2392  	data[len(prefix)+1] = 0
  2393  	if ctxt.Arch.ByteOrder == binary.BigEndian {
  2394  		data[len(prefix)+1] = 1
  2395  	}
  2396  	data[len(prefix)+1] |= 2 // signals new pointer-free format
  2397  	data = appendString(data, strdata["runtime.buildVersion"])
  2398  	data = appendString(data, strdata["runtime.modinfo"])
  2399  	// MacOS linker gets very upset if the size is not a multiple of alignment.
  2400  	for len(data)%16 != 0 {
  2401  		data = append(data, 0)
  2402  	}
  2403  	s.SetData(data)
  2404  	s.SetSize(int64(len(data)))
  2405  
  2406  	// Add reference to go:buildinfo from the rodata section,
  2407  	// so that external linking with -Wl,--gc-sections does not
  2408  	// delete the build info.
  2409  	sr := ldr.CreateSymForUpdate("go:buildinfo.ref", 0)
  2410  	sr.SetType(sym.SRODATA)
  2411  	sr.SetAlign(int32(ctxt.Arch.PtrSize))
  2412  	sr.AddAddr(ctxt.Arch, s.Sym())
  2413  }
  2414  
  2415  // appendString appends s to data, prefixed by its varint-encoded length.
  2416  func appendString(data []byte, s string) []byte {
  2417  	var v [binary.MaxVarintLen64]byte
  2418  	n := binary.PutUvarint(v[:], uint64(len(s)))
  2419  	data = append(data, v[:n]...)
  2420  	data = append(data, s...)
  2421  	return data
  2422  }
  2423  
  2424  // assign addresses to text
  2425  func (ctxt *Link) textaddress() {
  2426  	addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
  2427  
  2428  	// Assign PCs in text segment.
  2429  	// Could parallelize, by assigning to text
  2430  	// and then letting threads copy down, but probably not worth it.
  2431  	sect := Segtext.Sections[0]
  2432  
  2433  	sect.Align = int32(Funcalign)
  2434  
  2435  	ldr := ctxt.loader
  2436  
  2437  	if *flagRandLayout != 0 {
  2438  		r := rand.New(rand.NewSource(*flagRandLayout))
  2439  		textp := ctxt.Textp
  2440  		i := 0
  2441  		// don't move the buildid symbol
  2442  		if len(textp) > 0 && ldr.SymName(textp[0]) == "go:buildid" {
  2443  			i++
  2444  		}
  2445  		// Skip over C symbols, as functions in a (C object) section must stay together.
  2446  		// TODO: maybe we can move a section as a whole.
  2447  		// Note: we load C symbols before Go symbols, so we can scan from the start.
  2448  		for i < len(textp) && (ldr.SubSym(textp[i]) != 0 || ldr.AttrSubSymbol(textp[i])) {
  2449  			i++
  2450  		}
  2451  		textp = textp[i:]
  2452  		r.Shuffle(len(textp), func(i, j int) {
  2453  			textp[i], textp[j] = textp[j], textp[i]
  2454  		})
  2455  	}
  2456  
  2457  	// Sort the text symbols by type, so that FIPS symbols are
  2458  	// gathered together, with the FIPS start and end symbols
  2459  	// bracketing them , even if we've randomized the overall order.
  2460  	sort.SliceStable(ctxt.Textp, func(i, j int) bool {
  2461  		return ldr.SymType(ctxt.Textp[i]) < ldr.SymType(ctxt.Textp[j])
  2462  	})
  2463  
  2464  	text := ctxt.xdefine("runtime.text", sym.STEXT, 0)
  2465  	etext := ctxt.xdefine("runtime.etext", sym.STEXTEND, 0)
  2466  	ldr.SetSymSect(text, sect)
  2467  	if ctxt.IsAIX() && ctxt.IsExternal() {
  2468  		// Setting runtime.text has a real symbol prevents ld to
  2469  		// change its base address resulting in wrong offsets for
  2470  		// reflect methods.
  2471  		u := ldr.MakeSymbolUpdater(text)
  2472  		u.SetAlign(sect.Align)
  2473  		u.SetSize(8)
  2474  	}
  2475  
  2476  	if (ctxt.DynlinkingGo() && ctxt.IsDarwin()) || (ctxt.IsAIX() && ctxt.IsExternal()) {
  2477  		ldr.SetSymSect(etext, sect)
  2478  		ctxt.Textp = append(ctxt.Textp, etext, 0)
  2479  		copy(ctxt.Textp[1:], ctxt.Textp)
  2480  		ctxt.Textp[0] = text
  2481  	}
  2482  
  2483  	start := uint64(Rnd(*FlagTextAddr, int64(Funcalign)))
  2484  	va := start
  2485  	n := 1
  2486  	sect.Vaddr = va
  2487  
  2488  	limit := thearch.TrampLimit
  2489  	if limit == 0 {
  2490  		limit = 1 << 63 // unlimited
  2491  	}
  2492  	if *FlagDebugTextSize != 0 {
  2493  		limit = uint64(*FlagDebugTextSize)
  2494  	}
  2495  	if *FlagDebugTramp > 1 {
  2496  		limit = 1 // debug mode, force generating trampolines for everything
  2497  	}
  2498  
  2499  	if ctxt.IsAIX() && ctxt.IsExternal() {
  2500  		// On AIX, normally we won't generate direct calls to external symbols,
  2501  		// except in one test, cmd/go/testdata/script/link_syso_issue33139.txt.
  2502  		// That test doesn't make much sense, and I'm not sure it ever works.
  2503  		// Just generate trampoline for now (which will turn a direct call to
  2504  		// an indirect call, which at least builds).
  2505  		limit = 1
  2506  	}
  2507  
  2508  	// First pass: assign addresses assuming the program is small and will
  2509  	// not require trampoline generation.
  2510  	big := false
  2511  	for _, s := range ctxt.Textp {
  2512  		sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
  2513  		if va-start >= limit {
  2514  			big = true
  2515  			break
  2516  		}
  2517  	}
  2518  
  2519  	// Second pass: only if it is too big, insert trampolines for too-far
  2520  	// jumps and targets with unknown addresses.
  2521  	if big {
  2522  		// reset addresses
  2523  		for _, s := range ctxt.Textp {
  2524  			if s != text {
  2525  				resetAddress(ctxt, s)
  2526  			}
  2527  		}
  2528  		va = start
  2529  
  2530  		ntramps := 0
  2531  		var curPkg string
  2532  		for i, s := range ctxt.Textp {
  2533  			// When we find the first symbol in a package, perform a
  2534  			// single iteration that assigns temporary addresses to all
  2535  			// of the text in the same package, using the maximum possible
  2536  			// number of trampolines. This allows for better decisions to
  2537  			// be made regarding reachability and the need for trampolines.
  2538  			if symPkg := ldr.SymPkg(s); symPkg != "" && curPkg != symPkg {
  2539  				curPkg = symPkg
  2540  				vaTmp := va
  2541  				for j := i; j < len(ctxt.Textp); j++ {
  2542  					curSym := ctxt.Textp[j]
  2543  					if symPkg := ldr.SymPkg(curSym); symPkg == "" || curPkg != symPkg {
  2544  						break
  2545  					}
  2546  					// We do not pass big to assignAddress here, as this
  2547  					// can result in side effects such as section splitting.
  2548  					sect, n, vaTmp = assignAddress(ctxt, sect, n, curSym, vaTmp, false, false)
  2549  					vaTmp += maxSizeTrampolines(ctxt, ldr, curSym, false)
  2550  				}
  2551  			}
  2552  
  2553  			// Reset address for current symbol.
  2554  			if s != text {
  2555  				resetAddress(ctxt, s)
  2556  			}
  2557  
  2558  			// Assign actual address for current symbol.
  2559  			sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
  2560  
  2561  			// Resolve jumps, adding trampolines if they are needed.
  2562  			trampoline(ctxt, s)
  2563  
  2564  			// lay down trampolines after each function
  2565  			for ; ntramps < len(ctxt.tramps); ntramps++ {
  2566  				tramp := ctxt.tramps[ntramps]
  2567  				if ctxt.IsAIX() && strings.HasPrefix(ldr.SymName(tramp), "runtime.text.") {
  2568  					// Already set in assignAddress
  2569  					continue
  2570  				}
  2571  				sect, n, va = assignAddress(ctxt, sect, n, tramp, va, true, big)
  2572  			}
  2573  		}
  2574  
  2575  		// merge tramps into Textp, keeping Textp in address order
  2576  		if ntramps != 0 {
  2577  			newtextp := make([]loader.Sym, 0, len(ctxt.Textp)+ntramps)
  2578  			i := 0
  2579  			for _, s := range ctxt.Textp {
  2580  				for ; i < ntramps && ldr.SymValue(ctxt.tramps[i]) < ldr.SymValue(s); i++ {
  2581  					newtextp = append(newtextp, ctxt.tramps[i])
  2582  				}
  2583  				newtextp = append(newtextp, s)
  2584  			}
  2585  			newtextp = append(newtextp, ctxt.tramps[i:ntramps]...)
  2586  
  2587  			ctxt.Textp = newtextp
  2588  		}
  2589  	}
  2590  
  2591  	// Add MinLC size after etext, so it won't collide with the next symbol
  2592  	// (which may confuse some symbolizer).
  2593  	sect.Length = va - sect.Vaddr + uint64(ctxt.Arch.MinLC)
  2594  	ldr.SetSymSect(etext, sect)
  2595  	if ldr.SymValue(etext) == 0 {
  2596  		// Set the address of the start/end symbols, if not already
  2597  		// (i.e. not darwin+dynlink or AIX+external, see above).
  2598  		ldr.SetSymValue(etext, int64(va))
  2599  		ldr.SetSymValue(text, int64(Segtext.Sections[0].Vaddr))
  2600  	}
  2601  }
  2602  
  2603  // assigns address for a text symbol, returns (possibly new) section, its number, and the address.
  2604  func assignAddress(ctxt *Link, sect *sym.Section, n int, s loader.Sym, va uint64, isTramp, big bool) (*sym.Section, int, uint64) {
  2605  	ldr := ctxt.loader
  2606  	if thearch.AssignAddress != nil {
  2607  		return thearch.AssignAddress(ldr, sect, n, s, va, isTramp)
  2608  	}
  2609  
  2610  	ldr.SetSymSect(s, sect)
  2611  	if ldr.AttrSubSymbol(s) {
  2612  		return sect, n, va
  2613  	}
  2614  
  2615  	align := ldr.SymAlign(s)
  2616  	if align == 0 {
  2617  		align = int32(Funcalign)
  2618  	}
  2619  	va = uint64(Rnd(int64(va), int64(align)))
  2620  	if sect.Align < align {
  2621  		sect.Align = align
  2622  	}
  2623  
  2624  	funcsize := uint64(abi.MINFUNC) // spacing required for findfunctab
  2625  	if ldr.SymSize(s) > abi.MINFUNC {
  2626  		funcsize = uint64(ldr.SymSize(s))
  2627  	}
  2628  
  2629  	// If we need to split text sections, and this function doesn't fit in the current
  2630  	// section, then create a new one.
  2631  	//
  2632  	// Only break at outermost syms.
  2633  	if big && splitTextSections(ctxt) && ldr.OuterSym(s) == 0 {
  2634  		// For debugging purposes, allow text size limit to be cranked down,
  2635  		// so as to stress test the code that handles multiple text sections.
  2636  		var textSizelimit uint64 = thearch.TrampLimit
  2637  		if *FlagDebugTextSize != 0 {
  2638  			textSizelimit = uint64(*FlagDebugTextSize)
  2639  		}
  2640  
  2641  		// Sanity check: make sure the limit is larger than any
  2642  		// individual text symbol.
  2643  		if funcsize > textSizelimit {
  2644  			panic(fmt.Sprintf("error: text size limit %d less than text symbol %s size of %d", textSizelimit, ldr.SymName(s), funcsize))
  2645  		}
  2646  
  2647  		if va-sect.Vaddr+funcsize+maxSizeTrampolines(ctxt, ldr, s, isTramp) > textSizelimit {
  2648  			sectAlign := int32(thearch.Funcalign)
  2649  			if ctxt.IsPPC64() {
  2650  				// Align the next text section to the worst case function alignment likely
  2651  				// to be encountered when processing function symbols. The start address
  2652  				// is rounded against the final alignment of the text section later on in
  2653  				// (*Link).address. This may happen due to usage of PCALIGN directives
  2654  				// larger than Funcalign, or usage of ISA 3.1 prefixed instructions
  2655  				// (see ISA 3.1 Book I 1.9).
  2656  				const ppc64maxFuncalign = 64
  2657  				sectAlign = ppc64maxFuncalign
  2658  				va = uint64(Rnd(int64(va), ppc64maxFuncalign))
  2659  			}
  2660  
  2661  			// Set the length for the previous text section
  2662  			sect.Length = va - sect.Vaddr
  2663  
  2664  			// Create new section, set the starting Vaddr
  2665  			sect = addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
  2666  
  2667  			sect.Vaddr = va
  2668  			sect.Align = sectAlign
  2669  			ldr.SetSymSect(s, sect)
  2670  
  2671  			// Create a symbol for the start of the secondary text sections
  2672  			ntext := ldr.CreateSymForUpdate(fmt.Sprintf("runtime.text.%d", n), 0)
  2673  			ntext.SetSect(sect)
  2674  			if ctxt.IsAIX() {
  2675  				// runtime.text.X must be a real symbol on AIX.
  2676  				// Assign its address directly in order to be the
  2677  				// first symbol of this new section.
  2678  				ntext.SetType(sym.STEXT)
  2679  				ntext.SetSize(int64(abi.MINFUNC))
  2680  				ntext.SetOnList(true)
  2681  				ntext.SetAlign(sectAlign)
  2682  				ctxt.tramps = append(ctxt.tramps, ntext.Sym())
  2683  
  2684  				ntext.SetValue(int64(va))
  2685  				va += uint64(ntext.Size())
  2686  
  2687  				if align := ldr.SymAlign(s); align != 0 {
  2688  					va = uint64(Rnd(int64(va), int64(align)))
  2689  				} else {
  2690  					va = uint64(Rnd(int64(va), int64(Funcalign)))
  2691  				}
  2692  			}
  2693  			n++
  2694  		}
  2695  	}
  2696  
  2697  	ldr.SetSymValue(s, 0)
  2698  	for sub := s; sub != 0; sub = ldr.SubSym(sub) {
  2699  		ldr.SetSymValue(sub, ldr.SymValue(sub)+int64(va))
  2700  		if ctxt.Debugvlog > 2 {
  2701  			fmt.Println("assign text address:", ldr.SymName(sub), ldr.SymValue(sub))
  2702  		}
  2703  	}
  2704  
  2705  	va += funcsize
  2706  
  2707  	return sect, n, va
  2708  }
  2709  
  2710  func resetAddress(ctxt *Link, s loader.Sym) {
  2711  	ldr := ctxt.loader
  2712  	if ldr.OuterSym(s) != 0 {
  2713  		return
  2714  	}
  2715  	oldv := ldr.SymValue(s)
  2716  	for sub := s; sub != 0; sub = ldr.SubSym(sub) {
  2717  		ldr.SetSymValue(sub, ldr.SymValue(sub)-oldv)
  2718  	}
  2719  }
  2720  
  2721  // Return whether we may need to split text sections.
  2722  //
  2723  // On PPC64x, when external linking, a text section should not be
  2724  // larger than 2^25 bytes due to the size of call target offset field
  2725  // in the 'bl' instruction. Splitting into smaller text sections
  2726  // smaller than this limit allows the system linker to modify the long
  2727  // calls appropriately. The limit allows for the space needed for
  2728  // tables inserted by the linker.
  2729  //
  2730  // The same applies to Darwin/ARM64, with 2^27 byte threshold.
  2731  //
  2732  // Similarly for ARM, we split sections (at 2^25 bytes) to avoid
  2733  // inconsistencies between the Go linker's reachability calculations
  2734  // (e.g. will direct call from X to Y need a trampoline) and similar
  2735  // machinery in the external linker; see #58425 for more on the
  2736  // history here.
  2737  func splitTextSections(ctxt *Link) bool {
  2738  	return (ctxt.IsARM() || ctxt.IsPPC64() || (ctxt.IsARM64() && ctxt.IsDarwin())) && ctxt.IsExternal()
  2739  }
  2740  
  2741  // On Wasm, we reserve 4096 bytes for zero page, then 8192 bytes for wasm_exec.js
  2742  // to store command line args and environment variables.
  2743  // Data sections starts from at least address 12288.
  2744  // Keep in sync with wasm_exec.js.
  2745  const wasmMinDataAddr = 4096 + 8192
  2746  
  2747  // address assigns virtual addresses to all segments and sections and
  2748  // returns all segments in file order.
  2749  func (ctxt *Link) address() []*sym.Segment {
  2750  	var order []*sym.Segment // Layout order
  2751  
  2752  	va := uint64(*FlagTextAddr)
  2753  	order = append(order, &Segtext)
  2754  	Segtext.Rwx = 05
  2755  	Segtext.Vaddr = va
  2756  	for i, s := range Segtext.Sections {
  2757  		va = uint64(Rnd(int64(va), int64(s.Align)))
  2758  		s.Vaddr = va
  2759  		va += s.Length
  2760  
  2761  		if ctxt.IsWasm() && i == 0 && va < wasmMinDataAddr {
  2762  			va = wasmMinDataAddr
  2763  		}
  2764  	}
  2765  
  2766  	Segtext.Length = va - uint64(*FlagTextAddr)
  2767  
  2768  	if len(Segrodata.Sections) > 0 {
  2769  		// align to page boundary so as not to mix
  2770  		// rodata and executable text.
  2771  		//
  2772  		// Note: gold or GNU ld will reduce the size of the executable
  2773  		// file by arranging for the relro segment to end at a page
  2774  		// boundary, and overlap the end of the text segment with the
  2775  		// start of the relro segment in the file.  The PT_LOAD segments
  2776  		// will be such that the last page of the text segment will be
  2777  		// mapped twice, once r-x and once starting out rw- and, after
  2778  		// relocation processing, changed to r--.
  2779  		//
  2780  		// Ideally the last page of the text segment would not be
  2781  		// writable even for this short period.
  2782  		va = uint64(Rnd(int64(va), *FlagRound))
  2783  
  2784  		order = append(order, &Segrodata)
  2785  		Segrodata.Rwx = 04
  2786  		Segrodata.Vaddr = va
  2787  		for _, s := range Segrodata.Sections {
  2788  			va = uint64(Rnd(int64(va), int64(s.Align)))
  2789  			s.Vaddr = va
  2790  			va += s.Length
  2791  		}
  2792  
  2793  		Segrodata.Length = va - Segrodata.Vaddr
  2794  	}
  2795  	if len(Segrelrodata.Sections) > 0 {
  2796  		// align to page boundary so as not to mix
  2797  		// rodata, rel-ro data, and executable text.
  2798  		va = uint64(Rnd(int64(va), *FlagRound))
  2799  		if ctxt.HeadType == objabi.Haix {
  2800  			// Relro data are inside data segment on AIX.
  2801  			va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
  2802  		}
  2803  
  2804  		order = append(order, &Segrelrodata)
  2805  		Segrelrodata.Rwx = 06
  2806  		Segrelrodata.Vaddr = va
  2807  		for _, s := range Segrelrodata.Sections {
  2808  			va = uint64(Rnd(int64(va), int64(s.Align)))
  2809  			s.Vaddr = va
  2810  			va += s.Length
  2811  		}
  2812  
  2813  		Segrelrodata.Length = va - Segrelrodata.Vaddr
  2814  	}
  2815  
  2816  	va = uint64(Rnd(int64(va), *FlagRound))
  2817  	if ctxt.HeadType == objabi.Haix && len(Segrelrodata.Sections) == 0 {
  2818  		// Data sections are moved to an unreachable segment
  2819  		// to ensure that they are position-independent.
  2820  		// Already done if relro sections exist.
  2821  		va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
  2822  	}
  2823  	order = append(order, &Segdata)
  2824  	Segdata.Rwx = 06
  2825  	Segdata.Vaddr = va
  2826  	var data *sym.Section
  2827  	var noptr *sym.Section
  2828  	var bss *sym.Section
  2829  	var noptrbss *sym.Section
  2830  	var fuzzCounters *sym.Section
  2831  	for i, s := range Segdata.Sections {
  2832  		if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && s.Name == ".tbss" {
  2833  			continue
  2834  		}
  2835  		vlen := int64(s.Length)
  2836  		if i+1 < len(Segdata.Sections) && !((ctxt.IsELF || ctxt.HeadType == objabi.Haix) && Segdata.Sections[i+1].Name == ".tbss") {
  2837  			vlen = int64(Segdata.Sections[i+1].Vaddr - s.Vaddr)
  2838  		}
  2839  		s.Vaddr = va
  2840  		va += uint64(vlen)
  2841  		Segdata.Length = va - Segdata.Vaddr
  2842  		switch s.Name {
  2843  		case ".data":
  2844  			data = s
  2845  		case ".noptrdata":
  2846  			noptr = s
  2847  		case ".bss":
  2848  			bss = s
  2849  		case ".noptrbss":
  2850  			noptrbss = s
  2851  		case ".go.fuzzcntrs":
  2852  			fuzzCounters = s
  2853  		}
  2854  	}
  2855  
  2856  	// Assign Segdata's Filelen omitting the BSS. We do this here
  2857  	// simply because right now we know where the BSS starts.
  2858  	Segdata.Filelen = bss.Vaddr - Segdata.Vaddr
  2859  
  2860  	if len(Segpdata.Sections) > 0 {
  2861  		va = uint64(Rnd(int64(va), *FlagRound))
  2862  		order = append(order, &Segpdata)
  2863  		Segpdata.Rwx = 04
  2864  		Segpdata.Vaddr = va
  2865  		// Segpdata.Sections is intended to contain just one section.
  2866  		// Loop through the slice anyway for consistency.
  2867  		for _, s := range Segpdata.Sections {
  2868  			va = uint64(Rnd(int64(va), int64(s.Align)))
  2869  			s.Vaddr = va
  2870  			va += s.Length
  2871  		}
  2872  		Segpdata.Length = va - Segpdata.Vaddr
  2873  	}
  2874  
  2875  	if len(Segxdata.Sections) > 0 {
  2876  		va = uint64(Rnd(int64(va), *FlagRound))
  2877  		order = append(order, &Segxdata)
  2878  		Segxdata.Rwx = 04
  2879  		Segxdata.Vaddr = va
  2880  		// Segxdata.Sections is intended to contain just one section.
  2881  		// Loop through the slice anyway for consistency.
  2882  		for _, s := range Segxdata.Sections {
  2883  			va = uint64(Rnd(int64(va), int64(s.Align)))
  2884  			s.Vaddr = va
  2885  			va += s.Length
  2886  		}
  2887  		Segxdata.Length = va - Segxdata.Vaddr
  2888  	}
  2889  
  2890  	va = uint64(Rnd(int64(va), *FlagRound))
  2891  	order = append(order, &Segdwarf)
  2892  	Segdwarf.Rwx = 06
  2893  	Segdwarf.Vaddr = va
  2894  	for i, s := range Segdwarf.Sections {
  2895  		vlen := int64(s.Length)
  2896  		if i+1 < len(Segdwarf.Sections) {
  2897  			vlen = int64(Segdwarf.Sections[i+1].Vaddr - s.Vaddr)
  2898  		}
  2899  		s.Vaddr = va
  2900  		va += uint64(vlen)
  2901  		if ctxt.HeadType == objabi.Hwindows {
  2902  			va = uint64(Rnd(int64(va), PEFILEALIGN))
  2903  		}
  2904  		Segdwarf.Length = va - Segdwarf.Vaddr
  2905  	}
  2906  
  2907  	ldr := ctxt.loader
  2908  	var (
  2909  		rodata  = ldr.SymSect(ldr.LookupOrCreateSym("runtime.rodata", 0))
  2910  		symtab  = ldr.SymSect(ldr.LookupOrCreateSym("runtime.symtab", 0))
  2911  		pclntab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0))
  2912  		types   = ldr.SymSect(ldr.LookupOrCreateSym("runtime.types", 0))
  2913  	)
  2914  
  2915  	for _, s := range ctxt.datap {
  2916  		if sect := ldr.SymSect(s); sect != nil {
  2917  			ldr.AddToSymValue(s, int64(sect.Vaddr))
  2918  		}
  2919  		v := ldr.SymValue(s)
  2920  		for sub := ldr.SubSym(s); sub != 0; sub = ldr.SubSym(sub) {
  2921  			ldr.AddToSymValue(sub, v)
  2922  		}
  2923  	}
  2924  
  2925  	for _, si := range dwarfp {
  2926  		for _, s := range si.syms {
  2927  			if sect := ldr.SymSect(s); sect != nil {
  2928  				ldr.AddToSymValue(s, int64(sect.Vaddr))
  2929  			}
  2930  			sub := ldr.SubSym(s)
  2931  			if sub != 0 {
  2932  				panic(fmt.Sprintf("unexpected sub-sym for %s %s", ldr.SymName(s), ldr.SymType(s).String()))
  2933  			}
  2934  			v := ldr.SymValue(s)
  2935  			for ; sub != 0; sub = ldr.SubSym(sub) {
  2936  				ldr.AddToSymValue(s, v)
  2937  			}
  2938  		}
  2939  	}
  2940  
  2941  	for _, s := range sehp.pdata {
  2942  		if sect := ldr.SymSect(s); sect != nil {
  2943  			ldr.AddToSymValue(s, int64(sect.Vaddr))
  2944  		}
  2945  	}
  2946  	for _, s := range sehp.xdata {
  2947  		if sect := ldr.SymSect(s); sect != nil {
  2948  			ldr.AddToSymValue(s, int64(sect.Vaddr))
  2949  		}
  2950  	}
  2951  
  2952  	if ctxt.BuildMode == BuildModeShared {
  2953  		s := ldr.LookupOrCreateSym("go:link.abihashbytes", 0)
  2954  		sect := ldr.SymSect(ldr.LookupOrCreateSym(".note.go.abihash", 0))
  2955  		ldr.SetSymSect(s, sect)
  2956  		ldr.SetSymValue(s, int64(sect.Vaddr+16))
  2957  	}
  2958  
  2959  	// If there are multiple text sections, create runtime.text.n for
  2960  	// their section Vaddr, using n for index
  2961  	n := 1
  2962  	for _, sect := range Segtext.Sections[1:] {
  2963  		if sect.Name != ".text" {
  2964  			break
  2965  		}
  2966  		symname := fmt.Sprintf("runtime.text.%d", n)
  2967  		if ctxt.HeadType != objabi.Haix || ctxt.LinkMode != LinkExternal {
  2968  			// Addresses are already set on AIX with external linker
  2969  			// because these symbols are part of their sections.
  2970  			ctxt.xdefine(symname, sym.STEXT, int64(sect.Vaddr))
  2971  		}
  2972  		n++
  2973  	}
  2974  
  2975  	ctxt.xdefine("runtime.rodata", sym.SRODATA, int64(rodata.Vaddr))
  2976  	ctxt.xdefine("runtime.erodata", sym.SRODATA, int64(rodata.Vaddr+rodata.Length))
  2977  	ctxt.xdefine("runtime.types", sym.SRODATA, int64(types.Vaddr))
  2978  	ctxt.xdefine("runtime.etypes", sym.SRODATA, int64(types.Vaddr+types.Length))
  2979  
  2980  	s := ldr.Lookup("runtime.gcdata", 0)
  2981  	ldr.SetAttrLocal(s, true)
  2982  	ctxt.xdefine("runtime.egcdata", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
  2983  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcdata", 0), ldr.SymSect(s))
  2984  
  2985  	s = ldr.LookupOrCreateSym("runtime.gcbss", 0)
  2986  	ldr.SetAttrLocal(s, true)
  2987  	ctxt.xdefine("runtime.egcbss", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
  2988  	ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcbss", 0), ldr.SymSect(s))
  2989  
  2990  	ctxt.xdefine("runtime.symtab", sym.SRODATA, int64(symtab.Vaddr))
  2991  	ctxt.xdefine("runtime.esymtab", sym.SRODATA, int64(symtab.Vaddr+symtab.Length))
  2992  	ctxt.xdefine("runtime.pclntab", sym.SRODATA, int64(pclntab.Vaddr))
  2993  	ctxt.defineInternal("runtime.pcheader", sym.SRODATA)
  2994  	ctxt.defineInternal("runtime.funcnametab", sym.SRODATA)
  2995  	ctxt.defineInternal("runtime.cutab", sym.SRODATA)
  2996  	ctxt.defineInternal("runtime.filetab", sym.SRODATA)
  2997  	ctxt.defineInternal("runtime.pctab", sym.SRODATA)
  2998  	ctxt.defineInternal("runtime.functab", sym.SRODATA)
  2999  	ctxt.xdefine("runtime.epclntab", sym.SRODATA, int64(pclntab.Vaddr+pclntab.Length))
  3000  	ctxt.xdefine("runtime.noptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr))
  3001  	ctxt.xdefine("runtime.enoptrdata", sym.SNOPTRDATAEND, int64(noptr.Vaddr+noptr.Length))
  3002  	ctxt.xdefine("runtime.bss", sym.SBSS, int64(bss.Vaddr))
  3003  	ctxt.xdefine("runtime.ebss", sym.SBSS, int64(bss.Vaddr+bss.Length))
  3004  	ctxt.xdefine("runtime.data", sym.SDATA, int64(data.Vaddr))
  3005  	ctxt.xdefine("runtime.edata", sym.SDATAEND, int64(data.Vaddr+data.Length))
  3006  	ctxt.xdefine("runtime.noptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr))
  3007  	ctxt.xdefine("runtime.enoptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr+noptrbss.Length))
  3008  	ctxt.xdefine("runtime.covctrs", sym.SCOVERAGE_COUNTER, int64(noptrbss.Vaddr+covCounterDataStartOff))
  3009  	ctxt.xdefine("runtime.ecovctrs", sym.SCOVERAGE_COUNTER, int64(noptrbss.Vaddr+covCounterDataStartOff+covCounterDataLen))
  3010  	ctxt.xdefine("runtime.end", sym.SBSS, int64(Segdata.Vaddr+Segdata.Length))
  3011  
  3012  	if fuzzCounters != nil {
  3013  		if *flagAsan {
  3014  			// ASAN requires that the symbol marking the end
  3015  			// of the section be aligned on an 8 byte boundary.
  3016  			// See issue #66966.
  3017  			fuzzCounters.Length = uint64(Rnd(int64(fuzzCounters.Length), 8))
  3018  		}
  3019  		ctxt.xdefine("runtime.__start___sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr))
  3020  		ctxt.xdefine("runtime.__stop___sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
  3021  		ctxt.xdefine("internal/fuzz._counters", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr))
  3022  		ctxt.xdefine("internal/fuzz._ecounters", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
  3023  	}
  3024  
  3025  	if ctxt.IsSolaris() {
  3026  		// On Solaris, in the runtime it sets the external names of the
  3027  		// end symbols. Unset them and define separate symbols, so we
  3028  		// keep both.
  3029  		etext := ldr.Lookup("runtime.etext", 0)
  3030  		edata := ldr.Lookup("runtime.edata", 0)
  3031  		end := ldr.Lookup("runtime.end", 0)
  3032  		ldr.SetSymExtname(etext, "runtime.etext")
  3033  		ldr.SetSymExtname(edata, "runtime.edata")
  3034  		ldr.SetSymExtname(end, "runtime.end")
  3035  		ctxt.xdefine("_etext", ldr.SymType(etext), ldr.SymValue(etext))
  3036  		ctxt.xdefine("_edata", ldr.SymType(edata), ldr.SymValue(edata))
  3037  		ctxt.xdefine("_end", ldr.SymType(end), ldr.SymValue(end))
  3038  		ldr.SetSymSect(ldr.Lookup("_etext", 0), ldr.SymSect(etext))
  3039  		ldr.SetSymSect(ldr.Lookup("_edata", 0), ldr.SymSect(edata))
  3040  		ldr.SetSymSect(ldr.Lookup("_end", 0), ldr.SymSect(end))
  3041  	}
  3042  
  3043  	if ctxt.IsPPC64() && ctxt.IsElf() {
  3044  		// Resolve .TOC. symbols for all objects. Only one TOC region is supported. If a
  3045  		// GOT section is present, compute it as suggested by the ELFv2 ABI. Otherwise,
  3046  		// choose a similar offset from the start of the data segment.
  3047  		tocAddr := int64(Segdata.Vaddr) + 0x8000
  3048  		if gotAddr := ldr.SymValue(ctxt.GOT); gotAddr != 0 {
  3049  			tocAddr = gotAddr + 0x8000
  3050  		}
  3051  		for i := range ctxt.DotTOC {
  3052  			if i >= sym.SymVerABICount && i < sym.SymVerStatic { // these versions are not used currently
  3053  				continue
  3054  			}
  3055  			if toc := ldr.Lookup(".TOC.", i); toc != 0 {
  3056  				ldr.SetSymValue(toc, tocAddr)
  3057  			}
  3058  		}
  3059  	}
  3060  
  3061  	return order
  3062  }
  3063  
  3064  // layout assigns file offsets and lengths to the segments in order.
  3065  // Returns the file size containing all the segments.
  3066  func (ctxt *Link) layout(order []*sym.Segment) uint64 {
  3067  	var prev *sym.Segment
  3068  	for _, seg := range order {
  3069  		if prev == nil {
  3070  			seg.Fileoff = uint64(HEADR)
  3071  		} else {
  3072  			switch ctxt.HeadType {
  3073  			default:
  3074  				// Assuming the previous segment was
  3075  				// aligned, the following rounding
  3076  				// should ensure that this segment's
  3077  				// VA ≡ Fileoff mod FlagRound.
  3078  				seg.Fileoff = uint64(Rnd(int64(prev.Fileoff+prev.Filelen), *FlagRound))
  3079  				if seg.Vaddr%uint64(*FlagRound) != seg.Fileoff%uint64(*FlagRound) {
  3080  					Exitf("bad segment rounding (Vaddr=%#x Fileoff=%#x FlagRound=%#x)", seg.Vaddr, seg.Fileoff, *FlagRound)
  3081  				}
  3082  			case objabi.Hwindows:
  3083  				seg.Fileoff = prev.Fileoff + uint64(Rnd(int64(prev.Filelen), PEFILEALIGN))
  3084  			case objabi.Hplan9:
  3085  				seg.Fileoff = prev.Fileoff + prev.Filelen
  3086  			}
  3087  		}
  3088  		if seg != &Segdata {
  3089  			// Link.address already set Segdata.Filelen to
  3090  			// account for BSS.
  3091  			seg.Filelen = seg.Length
  3092  		}
  3093  		prev = seg
  3094  	}
  3095  	return prev.Fileoff + prev.Filelen
  3096  }
  3097  
  3098  // add a trampoline with symbol s (to be laid down after the current function)
  3099  func (ctxt *Link) AddTramp(s *loader.SymbolBuilder) {
  3100  	s.SetType(sym.STEXT)
  3101  	s.SetReachable(true)
  3102  	s.SetOnList(true)
  3103  	ctxt.tramps = append(ctxt.tramps, s.Sym())
  3104  	if *FlagDebugTramp > 0 && ctxt.Debugvlog > 0 {
  3105  		ctxt.Logf("trampoline %s inserted\n", s.Name())
  3106  	}
  3107  }
  3108  
  3109  // compressSyms compresses syms and returns the contents of the
  3110  // compressed section. If the section would get larger, it returns nil.
  3111  func compressSyms(ctxt *Link, syms []loader.Sym) []byte {
  3112  	ldr := ctxt.loader
  3113  	var total int64
  3114  	for _, sym := range syms {
  3115  		total += ldr.SymSize(sym)
  3116  	}
  3117  
  3118  	var buf bytes.Buffer
  3119  	if ctxt.IsELF {
  3120  		switch ctxt.Arch.PtrSize {
  3121  		case 8:
  3122  			binary.Write(&buf, ctxt.Arch.ByteOrder, elf.Chdr64{
  3123  				Type:      uint32(elf.COMPRESS_ZLIB),
  3124  				Size:      uint64(total),
  3125  				Addralign: uint64(ctxt.Arch.Alignment),
  3126  			})
  3127  		case 4:
  3128  			binary.Write(&buf, ctxt.Arch.ByteOrder, elf.Chdr32{
  3129  				Type:      uint32(elf.COMPRESS_ZLIB),
  3130  				Size:      uint32(total),
  3131  				Addralign: uint32(ctxt.Arch.Alignment),
  3132  			})
  3133  		default:
  3134  			log.Fatalf("can't compress header size:%d", ctxt.Arch.PtrSize)
  3135  		}
  3136  	} else {
  3137  		buf.Write([]byte("ZLIB"))
  3138  		var sizeBytes [8]byte
  3139  		binary.BigEndian.PutUint64(sizeBytes[:], uint64(total))
  3140  		buf.Write(sizeBytes[:])
  3141  	}
  3142  
  3143  	var relocbuf []byte // temporary buffer for applying relocations
  3144  
  3145  	// Using zlib.BestSpeed achieves very nearly the same
  3146  	// compression levels of zlib.DefaultCompression, but takes
  3147  	// substantially less time. This is important because DWARF
  3148  	// compression can be a significant fraction of link time.
  3149  	z, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
  3150  	if err != nil {
  3151  		log.Fatalf("NewWriterLevel failed: %s", err)
  3152  	}
  3153  	st := ctxt.makeRelocSymState()
  3154  	for _, s := range syms {
  3155  		// Symbol data may be read-only. Apply relocations in a
  3156  		// temporary buffer, and immediately write it out.
  3157  		P := ldr.Data(s)
  3158  		relocs := ldr.Relocs(s)
  3159  		if relocs.Count() != 0 {
  3160  			relocbuf = append(relocbuf[:0], P...)
  3161  			P = relocbuf
  3162  			st.relocsym(s, P)
  3163  		}
  3164  		if _, err := z.Write(P); err != nil {
  3165  			log.Fatalf("compression failed: %s", err)
  3166  		}
  3167  		for i := ldr.SymSize(s) - int64(len(P)); i > 0; {
  3168  			b := zeros[:]
  3169  			if i < int64(len(b)) {
  3170  				b = b[:i]
  3171  			}
  3172  			n, err := z.Write(b)
  3173  			if err != nil {
  3174  				log.Fatalf("compression failed: %s", err)
  3175  			}
  3176  			i -= int64(n)
  3177  		}
  3178  	}
  3179  	if err := z.Close(); err != nil {
  3180  		log.Fatalf("compression failed: %s", err)
  3181  	}
  3182  	if int64(buf.Len()) >= total {
  3183  		// Compression didn't save any space.
  3184  		return nil
  3185  	}
  3186  	return buf.Bytes()
  3187  }
  3188  

View as plain text