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

View as plain text