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

View as plain text