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

     1  // Inferno utils/8l/asm.c
     2  // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/8l/asm.c
     3  //
     4  //	Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
     5  //	Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
     6  //	Portions Copyright © 1997-1999 Vita Nuova Limited
     7  //	Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
     8  //	Portions Copyright © 2004,2006 Bruce Ellis
     9  //	Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
    10  //	Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
    11  //	Portions Copyright © 2009 The Go Authors. All rights reserved.
    12  //
    13  // Permission is hereby granted, free of charge, to any person obtaining a copy
    14  // of this software and associated documentation files (the "Software"), to deal
    15  // in the Software without restriction, including without limitation the rights
    16  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    17  // copies of the Software, and to permit persons to whom the Software is
    18  // furnished to do so, subject to the following conditions:
    19  //
    20  // The above copyright notice and this permission notice shall be included in
    21  // all copies or substantial portions of the Software.
    22  //
    23  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    24  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    25  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
    26  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    27  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    28  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    29  // THE SOFTWARE.
    30  
    31  package ld
    32  
    33  import (
    34  	"bytes"
    35  	"debug/elf"
    36  	"debug/macho"
    37  	"debug/pe"
    38  	"encoding/base64"
    39  	"encoding/binary"
    40  	"fmt"
    41  	"internal/buildcfg"
    42  	"internal/platform"
    43  	"io"
    44  	"log"
    45  	"os"
    46  	"os/exec"
    47  	"path/filepath"
    48  	"runtime"
    49  	"slices"
    50  	"sort"
    51  	"strings"
    52  	"sync"
    53  	"time"
    54  
    55  	"cmd/internal/bio"
    56  	"cmd/internal/goobj"
    57  	"cmd/internal/hash"
    58  	"cmd/internal/objabi"
    59  	"cmd/internal/sys"
    60  	"cmd/link/internal/loadelf"
    61  	"cmd/link/internal/loader"
    62  	"cmd/link/internal/loadmacho"
    63  	"cmd/link/internal/loadpe"
    64  	"cmd/link/internal/loadxcoff"
    65  	"cmd/link/internal/sym"
    66  )
    67  
    68  // Data layout and relocation.
    69  
    70  // Derived from Inferno utils/6l/l.h
    71  // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/l.h
    72  //
    73  //	Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
    74  //	Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
    75  //	Portions Copyright © 1997-1999 Vita Nuova Limited
    76  //	Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
    77  //	Portions Copyright © 2004,2006 Bruce Ellis
    78  //	Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
    79  //	Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
    80  //	Portions Copyright © 2009 The Go Authors. All rights reserved.
    81  //
    82  // Permission is hereby granted, free of charge, to any person obtaining a copy
    83  // of this software and associated documentation files (the "Software"), to deal
    84  // in the Software without restriction, including without limitation the rights
    85  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    86  // copies of the Software, and to permit persons to whom the Software is
    87  // furnished to do so, subject to the following conditions:
    88  //
    89  // The above copyright notice and this permission notice shall be included in
    90  // all copies or substantial portions of the Software.
    91  //
    92  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    93  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    94  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
    95  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    96  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    97  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    98  // THE SOFTWARE.
    99  
   100  // ArchSyms holds a number of architecture specific symbols used during
   101  // relocation.  Rather than allowing them universal access to all symbols,
   102  // we keep a subset for relocation application.
   103  type ArchSyms struct {
   104  	Rel     loader.Sym
   105  	Rela    loader.Sym
   106  	RelPLT  loader.Sym
   107  	RelaPLT loader.Sym
   108  
   109  	LinkEditGOT loader.Sym
   110  	LinkEditPLT loader.Sym
   111  
   112  	TOC    loader.Sym
   113  	DotTOC []loader.Sym // for each version
   114  
   115  	GOT    loader.Sym
   116  	PLT    loader.Sym
   117  	GOTPLT loader.Sym
   118  
   119  	Tlsg      loader.Sym
   120  	Tlsoffset int
   121  
   122  	Dynamic loader.Sym
   123  	DynSym  loader.Sym
   124  	DynStr  loader.Sym
   125  
   126  	unreachableMethod loader.Sym
   127  
   128  	// Symbol containing a list of all the inittasks that need
   129  	// to be run at startup.
   130  	mainInittasks loader.Sym
   131  }
   132  
   133  // mkArchSym is a helper for setArchSyms, to set up a special symbol.
   134  func (ctxt *Link) mkArchSym(name string, ver int, ls *loader.Sym) {
   135  	*ls = ctxt.loader.LookupOrCreateSym(name, ver)
   136  	ctxt.loader.SetAttrReachable(*ls, true)
   137  }
   138  
   139  // mkArchSymVec is similar to  setArchSyms, but operates on elements within
   140  // a slice, where each element corresponds to some symbol version.
   141  func (ctxt *Link) mkArchSymVec(name string, ver int, ls []loader.Sym) {
   142  	ls[ver] = ctxt.loader.LookupOrCreateSym(name, ver)
   143  	ctxt.loader.SetAttrReachable(ls[ver], true)
   144  }
   145  
   146  // setArchSyms sets up the ArchSyms structure, and must be called before
   147  // relocations are applied.
   148  func (ctxt *Link) setArchSyms() {
   149  	ctxt.mkArchSym(".got", 0, &ctxt.GOT)
   150  	ctxt.mkArchSym(".plt", 0, &ctxt.PLT)
   151  	ctxt.mkArchSym(".got.plt", 0, &ctxt.GOTPLT)
   152  	ctxt.mkArchSym(".dynamic", 0, &ctxt.Dynamic)
   153  	ctxt.mkArchSym(".dynsym", 0, &ctxt.DynSym)
   154  	ctxt.mkArchSym(".dynstr", 0, &ctxt.DynStr)
   155  	ctxt.mkArchSym("runtime.unreachableMethod", abiInternalVer, &ctxt.unreachableMethod)
   156  
   157  	if ctxt.IsPPC64() {
   158  		ctxt.mkArchSym("TOC", 0, &ctxt.TOC)
   159  
   160  		ctxt.DotTOC = make([]loader.Sym, ctxt.MaxVersion()+1)
   161  		for i := 0; i <= ctxt.MaxVersion(); i++ {
   162  			if i >= sym.SymVerABICount && i < sym.SymVerStatic { // these versions are not used currently
   163  				continue
   164  			}
   165  			ctxt.mkArchSymVec(".TOC.", i, ctxt.DotTOC)
   166  		}
   167  	}
   168  	if ctxt.IsElf() {
   169  		ctxt.mkArchSym(".rel", 0, &ctxt.Rel)
   170  		ctxt.mkArchSym(".rela", 0, &ctxt.Rela)
   171  		ctxt.mkArchSym(".rel.plt", 0, &ctxt.RelPLT)
   172  		ctxt.mkArchSym(".rela.plt", 0, &ctxt.RelaPLT)
   173  	}
   174  	if ctxt.IsDarwin() {
   175  		ctxt.mkArchSym(".linkedit.got", 0, &ctxt.LinkEditGOT)
   176  		ctxt.mkArchSym(".linkedit.plt", 0, &ctxt.LinkEditPLT)
   177  	}
   178  }
   179  
   180  type Arch struct {
   181  	Funcalign  int
   182  	Maxalign   int
   183  	Minalign   int
   184  	Dwarfregsp int
   185  	Dwarfreglr int
   186  
   187  	// Threshold of total text size, used for trampoline insertion. If the total
   188  	// text size is smaller than TrampLimit, we won't need to insert trampolines.
   189  	// It is pretty close to the offset range of a direct CALL machine instruction.
   190  	// We leave some room for extra stuff like PLT stubs.
   191  	TrampLimit uint64
   192  
   193  	// Empty spaces between codeblocks will be padded with this value.
   194  	// For example an architecture might want to pad with a trap instruction to
   195  	// catch wayward programs. Architectures that do not define a padding value
   196  	// are padded with zeros.
   197  	CodePad []byte
   198  
   199  	// Plan 9 variables.
   200  	Plan9Magic  uint32
   201  	Plan9_64Bit bool
   202  
   203  	Adddynrel func(*Target, *loader.Loader, *ArchSyms, loader.Sym, loader.Reloc, int) bool
   204  	Archinit  func(*Link)
   205  	// Archreloc is an arch-specific hook that assists in relocation processing
   206  	// (invoked by 'relocsym'); it handles target-specific relocation tasks.
   207  	// Here "rel" is the current relocation being examined, "sym" is the symbol
   208  	// containing the chunk of data to which the relocation applies, and "off"
   209  	// is the contents of the to-be-relocated data item (from sym.P). Return
   210  	// value is the appropriately relocated value (to be written back to the
   211  	// same spot in sym.P), number of external _host_ relocations needed (i.e.
   212  	// ELF/Mach-O/etc. relocations, not Go relocations, this must match ELF.Reloc1,
   213  	// etc.), and a boolean indicating success/failure (a failing value indicates
   214  	// a fatal error).
   215  	Archreloc func(*Target, *loader.Loader, *ArchSyms, loader.Reloc, loader.Sym,
   216  		int64) (relocatedOffset int64, nExtReloc int, ok bool)
   217  	// Archrelocvariant is a second arch-specific hook used for
   218  	// relocation processing; it handles relocations where r.Type is
   219  	// insufficient to describe the relocation (r.Variant !=
   220  	// sym.RV_NONE). Here "rel" is the relocation being applied, "sym"
   221  	// is the symbol containing the chunk of data to which the
   222  	// relocation applies, and "off" is the contents of the
   223  	// to-be-relocated data item (from sym.P). Return is an updated
   224  	// offset value.
   225  	Archrelocvariant func(target *Target, ldr *loader.Loader, rel loader.Reloc,
   226  		rv sym.RelocVariant, sym loader.Sym, offset int64, data []byte) (relocatedOffset int64)
   227  
   228  	// Generate a trampoline for a call from s to rs if necessary. ri is
   229  	// index of the relocation.
   230  	Trampoline func(ctxt *Link, ldr *loader.Loader, ri int, rs, s loader.Sym)
   231  
   232  	// Assembling the binary breaks into two phases, writing the code/data/
   233  	// dwarf information (which is rather generic), and some more architecture
   234  	// specific work like setting up the elf headers/dynamic relocations, etc.
   235  	// The phases are called "Asmb" and "Asmb2". Asmb2 needs to be defined for
   236  	// every architecture, but only if architecture has an Asmb function will
   237  	// it be used for assembly.  Otherwise a generic assembly Asmb function is
   238  	// used.
   239  	Asmb  func(*Link, *loader.Loader)
   240  	Asmb2 func(*Link, *loader.Loader)
   241  
   242  	// Extreloc is an arch-specific hook that converts a Go relocation to an
   243  	// external relocation. Return the external relocation and whether it is
   244  	// needed.
   245  	Extreloc func(*Target, *loader.Loader, loader.Reloc, loader.Sym) (loader.ExtReloc, bool)
   246  
   247  	Gentext        func(*Link, *loader.Loader) // Generate text before addressing has been performed.
   248  	Machoreloc1    func(*sys.Arch, *OutBuf, *loader.Loader, loader.Sym, loader.ExtReloc, int64) bool
   249  	MachorelocSize uint32 // size of an Mach-O relocation record, must match Machoreloc1.
   250  	PEreloc1       func(*sys.Arch, *OutBuf, *loader.Loader, loader.Sym, loader.ExtReloc, int64) bool
   251  	Xcoffreloc1    func(*sys.Arch, *OutBuf, *loader.Loader, loader.Sym, loader.ExtReloc, int64) bool
   252  
   253  	// Generate additional symbols for the native symbol table just prior to
   254  	// code generation.
   255  	GenSymsLate func(*Link, *loader.Loader)
   256  
   257  	// TLSIEtoLE converts a TLS Initial Executable relocation to
   258  	// a TLS Local Executable relocation.
   259  	//
   260  	// This is possible when a TLS IE relocation refers to a local
   261  	// symbol in an executable, which is typical when internally
   262  	// linking PIE binaries.
   263  	TLSIEtoLE func(P []byte, off, size int)
   264  
   265  	// optional override for assignAddress
   266  	AssignAddress func(ldr *loader.Loader, sect *sym.Section, n int, s loader.Sym, va uint64, isTramp bool) (*sym.Section, int, uint64)
   267  
   268  	// ELF specific information.
   269  	ELF ELFArch
   270  }
   271  
   272  var (
   273  	thearch Arch
   274  	lcSize  int32
   275  	rpath   Rpath
   276  	spSize  int32
   277  	symSize int32
   278  )
   279  
   280  // Symbol version of ABIInternal symbols. It is sym.SymVerABIInternal if ABI wrappers
   281  // are used, 0 otherwise.
   282  var abiInternalVer = sym.SymVerABIInternal
   283  
   284  // DynlinkingGo reports whether we are producing Go code that can live
   285  // in separate shared libraries linked together at runtime.
   286  func (ctxt *Link) DynlinkingGo() bool {
   287  	if !ctxt.Loaded {
   288  		panic("DynlinkingGo called before all symbols loaded")
   289  	}
   290  	return ctxt.BuildMode == BuildModeShared || ctxt.linkShared || ctxt.BuildMode == BuildModePlugin || ctxt.canUsePlugins
   291  }
   292  
   293  // CanUsePlugins reports whether a plugins can be used
   294  func (ctxt *Link) CanUsePlugins() bool {
   295  	if !ctxt.Loaded {
   296  		panic("CanUsePlugins called before all symbols loaded")
   297  	}
   298  	return ctxt.canUsePlugins
   299  }
   300  
   301  // NeedCodeSign reports whether we need to code-sign the output binary.
   302  func (ctxt *Link) NeedCodeSign() bool {
   303  	return ctxt.IsDarwin() && ctxt.IsARM64()
   304  }
   305  
   306  var (
   307  	dynlib          []string
   308  	ldflag          []string
   309  	havedynamic     int
   310  	Funcalign       int
   311  	iscgo           bool
   312  	elfglobalsymndx int
   313  	interpreter     string
   314  
   315  	debug_s bool // backup old value of debug['s']
   316  	HEADR   int32
   317  
   318  	nerrors  int
   319  	liveness int64 // size of liveness data (funcdata), printed if -v
   320  
   321  	// See -strictdups command line flag.
   322  	checkStrictDups   int // 0=off 1=warning 2=error
   323  	strictDupMsgCount int
   324  )
   325  
   326  var (
   327  	Segtext      sym.Segment
   328  	Segrodata    sym.Segment
   329  	Segrelrodata sym.Segment
   330  	Segdata      sym.Segment
   331  	Segdwarf     sym.Segment
   332  	Segpdata     sym.Segment // windows-only
   333  	Segxdata     sym.Segment // windows-only
   334  
   335  	Segments = []*sym.Segment{&Segtext, &Segrodata, &Segrelrodata, &Segdata, &Segdwarf, &Segpdata, &Segxdata}
   336  )
   337  
   338  const pkgdef = "__.PKGDEF"
   339  
   340  var (
   341  	// externalobj is set to true if we see an object compiled by
   342  	// the host compiler that is not from a package that is known
   343  	// to support internal linking mode.
   344  	externalobj = false
   345  
   346  	// dynimportfail is a list of packages for which generating
   347  	// the dynimport file, _cgo_import.go, failed. If there are
   348  	// any of these objects, we must link externally. Issue 52863.
   349  	dynimportfail []string
   350  
   351  	// preferlinkext is a list of packages for which the Go command
   352  	// noticed use of peculiar C flags. If we see any of these,
   353  	// default to linking externally unless overridden by the
   354  	// user. See issues #58619, #58620, and #58848.
   355  	preferlinkext []string
   356  
   357  	// unknownObjFormat is set to true if we see an object whose
   358  	// format we don't recognize.
   359  	unknownObjFormat = false
   360  
   361  	theline string
   362  )
   363  
   364  func Lflag(ctxt *Link, arg string) {
   365  	ctxt.Libdir = append(ctxt.Libdir, arg)
   366  }
   367  
   368  /*
   369   * Unix doesn't like it when we write to a running (or, sometimes,
   370   * recently run) binary, so remove the output file before writing it.
   371   * On Windows 7, remove() can force a subsequent create() to fail.
   372   * S_ISREG() does not exist on Plan 9.
   373   */
   374  func mayberemoveoutfile() {
   375  	if fi, err := os.Lstat(*flagOutfile); err == nil && !fi.Mode().IsRegular() {
   376  		return
   377  	}
   378  	os.Remove(*flagOutfile)
   379  	if *flagOutfile != "" {
   380  		os.RemoveAll(*flagOutfile + ".dSYM")
   381  	}
   382  }
   383  
   384  func libinit(ctxt *Link) {
   385  	if *FlagFuncAlign != 0 {
   386  		Funcalign = *FlagFuncAlign
   387  	} else {
   388  		Funcalign = thearch.Funcalign
   389  	}
   390  
   391  	// add goroot to the end of the libdir list.
   392  	suffix := ""
   393  
   394  	suffixsep := ""
   395  	if *flagInstallSuffix != "" {
   396  		suffixsep = "_"
   397  		suffix = *flagInstallSuffix
   398  	} else if *flagRace {
   399  		suffixsep = "_"
   400  		suffix = "race"
   401  	} else if *flagMsan {
   402  		suffixsep = "_"
   403  		suffix = "msan"
   404  	} else if *flagAsan {
   405  		suffixsep = "_"
   406  		suffix = "asan"
   407  	}
   408  
   409  	if buildcfg.GOROOT != "" {
   410  		Lflag(ctxt, filepath.Join(buildcfg.GOROOT, "pkg", fmt.Sprintf("%s_%s%s%s", buildcfg.GOOS, buildcfg.GOARCH, suffixsep, suffix)))
   411  	}
   412  
   413  	mayberemoveoutfile()
   414  
   415  	if err := ctxt.Out.Open(*flagOutfile); err != nil {
   416  		Exitf("cannot create %s: %v", *flagOutfile, err)
   417  	}
   418  
   419  	if *flagEntrySymbol == "" {
   420  		switch ctxt.BuildMode {
   421  		case BuildModeCShared, BuildModeCArchive:
   422  			*flagEntrySymbol = fmt.Sprintf("_rt0_%s_%s_lib", buildcfg.GOARCH, buildcfg.GOOS)
   423  		case BuildModeExe, BuildModePIE:
   424  			*flagEntrySymbol = fmt.Sprintf("_rt0_%s_%s", buildcfg.GOARCH, buildcfg.GOOS)
   425  		case BuildModeShared, BuildModePlugin:
   426  			// No *flagEntrySymbol for -buildmode=shared and plugin
   427  		default:
   428  			Errorf("unknown *flagEntrySymbol for buildmode %v", ctxt.BuildMode)
   429  		}
   430  	}
   431  }
   432  
   433  func exitIfErrors() {
   434  	if nerrors != 0 || checkStrictDups > 1 && strictDupMsgCount > 0 {
   435  		mayberemoveoutfile()
   436  		Exit(2)
   437  	}
   438  
   439  }
   440  
   441  func errorexit() {
   442  	exitIfErrors()
   443  	Exit(0)
   444  }
   445  
   446  func loadinternal(ctxt *Link, name string) *sym.Library {
   447  	zerofp := goobj.FingerprintType{}
   448  	if ctxt.linkShared && ctxt.PackageShlib != nil {
   449  		if shlib := ctxt.PackageShlib[name]; shlib != "" {
   450  			return addlibpath(ctxt, "internal", "internal", "", name, shlib, zerofp)
   451  		}
   452  	}
   453  	if ctxt.PackageFile != nil {
   454  		if pname := ctxt.PackageFile[name]; pname != "" {
   455  			return addlibpath(ctxt, "internal", "internal", pname, name, "", zerofp)
   456  		}
   457  		ctxt.Logf("loadinternal: cannot find %s\n", name)
   458  		return nil
   459  	}
   460  
   461  	for _, libdir := range ctxt.Libdir {
   462  		if ctxt.linkShared {
   463  			shlibname := filepath.Join(libdir, name+".shlibname")
   464  			if ctxt.Debugvlog != 0 {
   465  				ctxt.Logf("searching for %s.a in %s\n", name, shlibname)
   466  			}
   467  			if _, err := os.Stat(shlibname); err == nil {
   468  				return addlibpath(ctxt, "internal", "internal", "", name, shlibname, zerofp)
   469  			}
   470  		}
   471  		pname := filepath.Join(libdir, name+".a")
   472  		if ctxt.Debugvlog != 0 {
   473  			ctxt.Logf("searching for %s.a in %s\n", name, pname)
   474  		}
   475  		if _, err := os.Stat(pname); err == nil {
   476  			return addlibpath(ctxt, "internal", "internal", pname, name, "", zerofp)
   477  		}
   478  	}
   479  
   480  	if name == "runtime" {
   481  		Exitf("error: unable to find runtime.a")
   482  	}
   483  	ctxt.Logf("warning: unable to find %s.a\n", name)
   484  	return nil
   485  }
   486  
   487  // extld returns the current external linker.
   488  func (ctxt *Link) extld() []string {
   489  	if len(flagExtld) == 0 {
   490  		// Return the default external linker for the platform.
   491  		// This only matters when link tool is called directly without explicit -extld,
   492  		// go tool already passes the correct linker in other cases.
   493  		switch buildcfg.GOOS {
   494  		case "darwin", "freebsd", "openbsd":
   495  			flagExtld = []string{"clang"}
   496  		default:
   497  			flagExtld = []string{"gcc"}
   498  		}
   499  	}
   500  	return flagExtld
   501  }
   502  
   503  // findLibPathCmd uses cmd command to find gcc library libname.
   504  // It returns library full path if found, or "none" if not found.
   505  func (ctxt *Link) findLibPathCmd(cmd, libname string) string {
   506  	if restrictedBuild() {
   507  		return "none"
   508  	}
   509  	extld := ctxt.extld()
   510  	name, args := extld[0], extld[1:]
   511  	args = append(args, hostlinkArchArgs(ctxt.Arch)...)
   512  	args = append(args, cmd)
   513  	if ctxt.Debugvlog != 0 {
   514  		ctxt.Logf("%s %v\n", extld, args)
   515  	}
   516  	out, err := exec.Command(name, args...).Output()
   517  	if err != nil {
   518  		if ctxt.Debugvlog != 0 {
   519  			ctxt.Logf("not using a %s file because compiler failed\n%v\n%s\n", libname, err, out)
   520  		}
   521  		return "none"
   522  	}
   523  	return strings.TrimSpace(string(out))
   524  }
   525  
   526  // findLibPath searches for library libname.
   527  // It returns library full path if found, or "none" if not found.
   528  func (ctxt *Link) findLibPath(libname string) string {
   529  	return ctxt.findLibPathCmd("--print-file-name="+libname, libname)
   530  }
   531  
   532  func (ctxt *Link) loadlib() {
   533  	var flags uint32
   534  	if *flagCheckLinkname {
   535  		flags |= loader.FlagCheckLinkname
   536  	}
   537  	switch *FlagStrictDups {
   538  	case 0:
   539  		// nothing to do
   540  	case 1, 2:
   541  		flags |= loader.FlagStrictDups
   542  	default:
   543  		log.Fatalf("invalid -strictdups flag value %d", *FlagStrictDups)
   544  	}
   545  	ctxt.loader = loader.NewLoader(flags, &ctxt.ErrorReporter.ErrorReporter)
   546  	ctxt.ErrorReporter.SymName = func(s loader.Sym) string {
   547  		return ctxt.loader.SymName(s)
   548  	}
   549  
   550  	// ctxt.Library grows during the loop, so not a range loop.
   551  	i := 0
   552  	for ; i < len(ctxt.Library); i++ {
   553  		lib := ctxt.Library[i]
   554  		if lib.Shlib == "" {
   555  			if ctxt.Debugvlog > 1 {
   556  				ctxt.Logf("autolib: %s (from %s)\n", lib.File, lib.Objref)
   557  			}
   558  			loadobjfile(ctxt, lib)
   559  		}
   560  	}
   561  
   562  	// load internal packages, if not already
   563  	if *flagRace {
   564  		loadinternal(ctxt, "runtime/race")
   565  	}
   566  	if *flagMsan {
   567  		loadinternal(ctxt, "runtime/msan")
   568  	}
   569  	if *flagAsan {
   570  		loadinternal(ctxt, "runtime/asan")
   571  	}
   572  	loadinternal(ctxt, "runtime")
   573  	for ; i < len(ctxt.Library); i++ {
   574  		lib := ctxt.Library[i]
   575  		if lib.Shlib == "" {
   576  			loadobjfile(ctxt, lib)
   577  		}
   578  	}
   579  	// At this point, the Go objects are "preloaded". Not all the symbols are
   580  	// added to the symbol table (only defined package symbols are). Looking
   581  	// up symbol by name may not get expected result.
   582  
   583  	iscgo = ctxt.LibraryByPkg["runtime/cgo"] != nil
   584  
   585  	// Plugins a require cgo support to function. Similarly, plugins may require additional
   586  	// internal linker support on some platforms which may not be implemented.
   587  	ctxt.canUsePlugins = ctxt.LibraryByPkg["plugin"] != nil && iscgo &&
   588  		platform.BuildModeSupported("gc", "plugin", buildcfg.GOOS, buildcfg.GOARCH)
   589  
   590  	// We now have enough information to determine the link mode.
   591  	determineLinkMode(ctxt)
   592  
   593  	if ctxt.LinkMode == LinkExternal && !iscgo && !(buildcfg.GOOS == "darwin" && ctxt.BuildMode != BuildModePlugin && ctxt.Arch.Family == sys.AMD64) {
   594  		// This indicates a user requested -linkmode=external.
   595  		// The startup code uses an import of runtime/cgo to decide
   596  		// whether to initialize the TLS.  So give it one. This could
   597  		// be handled differently but it's an unusual case.
   598  		if lib := loadinternal(ctxt, "runtime/cgo"); lib != nil && lib.Shlib == "" {
   599  			if ctxt.BuildMode == BuildModeShared || ctxt.linkShared {
   600  				Exitf("cannot implicitly include runtime/cgo in a shared library")
   601  			}
   602  			for ; i < len(ctxt.Library); i++ {
   603  				lib := ctxt.Library[i]
   604  				if lib.Shlib == "" {
   605  					loadobjfile(ctxt, lib)
   606  				}
   607  			}
   608  		}
   609  	}
   610  
   611  	// Add non-package symbols and references of externally defined symbols.
   612  	ctxt.loader.LoadSyms(ctxt.Arch)
   613  
   614  	// Load symbols from shared libraries, after all Go object symbols are loaded.
   615  	for _, lib := range ctxt.Library {
   616  		if lib.Shlib != "" {
   617  			if ctxt.Debugvlog > 1 {
   618  				ctxt.Logf("autolib: %s (from %s)\n", lib.Shlib, lib.Objref)
   619  			}
   620  			ldshlibsyms(ctxt, lib.Shlib)
   621  		}
   622  	}
   623  
   624  	// Process cgo directives (has to be done before host object loading).
   625  	ctxt.loadcgodirectives()
   626  
   627  	// Conditionally load host objects, or setup for external linking.
   628  	hostobjs(ctxt)
   629  	hostlinksetup(ctxt)
   630  
   631  	if ctxt.LinkMode == LinkInternal && len(hostobj) != 0 {
   632  		// If we have any undefined symbols in external
   633  		// objects, try to read them from the libgcc file.
   634  		any := false
   635  		undefs, froms := ctxt.loader.UndefinedRelocTargets(1)
   636  		if len(undefs) > 0 {
   637  			any = true
   638  			if ctxt.Debugvlog > 1 {
   639  				ctxt.Logf("loadlib: first unresolved is %s [%d] from %s [%d]\n",
   640  					ctxt.loader.SymName(undefs[0]), undefs[0],
   641  					ctxt.loader.SymName(froms[0]), froms[0])
   642  			}
   643  		}
   644  		if any {
   645  			if *flagLibGCC == "" {
   646  				*flagLibGCC = ctxt.findLibPathCmd("--print-libgcc-file-name", "libgcc")
   647  			}
   648  			if runtime.GOOS == "freebsd" && strings.HasPrefix(filepath.Base(*flagLibGCC), "libclang_rt.builtins") {
   649  				// On newer versions of FreeBSD, libgcc is returned as something like
   650  				// /usr/lib/clang/18/lib/freebsd/libclang_rt.builtins-x86_64.a.
   651  				// Unfortunately this ends up missing a bunch of symbols we need from
   652  				// libcompiler_rt.
   653  				*flagLibGCC = ctxt.findLibPathCmd("--print-file-name=libcompiler_rt.a", "libcompiler_rt")
   654  			}
   655  			if runtime.GOOS == "openbsd" && *flagLibGCC == "libgcc.a" {
   656  				// On OpenBSD `clang --print-libgcc-file-name` returns "libgcc.a".
   657  				// In this case we fail to load libgcc.a and can encounter link
   658  				// errors - see if we can find libcompiler_rt.a instead.
   659  				*flagLibGCC = ctxt.findLibPathCmd("--print-file-name=libcompiler_rt.a", "libcompiler_rt")
   660  			}
   661  			if ctxt.HeadType == objabi.Hwindows {
   662  				loadWindowsHostArchives(ctxt)
   663  			}
   664  			if *flagLibGCC != "none" {
   665  				hostArchive(ctxt, *flagLibGCC)
   666  			}
   667  			// For glibc systems, the linker setup used by GCC
   668  			// looks like
   669  			//
   670  			//  GROUP ( /lib/x86_64-linux-gnu/libc.so.6
   671  			//      /usr/lib/x86_64-linux-gnu/libc_nonshared.a
   672  			//      AS_NEEDED ( /lib64/ld-linux-x86-64.so.2 ) )
   673  			//
   674  			// where libc_nonshared.a contains a small set of
   675  			// symbols including "__stack_chk_fail_local" and a
   676  			// few others. Thus if we are doing internal linking
   677  			// and "__stack_chk_fail_local" is unresolved (most
   678  			// likely due to the use of -fstack-protector), try
   679  			// loading libc_nonshared.a to resolve it.
   680  			//
   681  			// On Alpine Linux (musl-based), the library providing
   682  			// this symbol is called libssp_nonshared.a.
   683  			isunresolved := symbolsAreUnresolved(ctxt, []string{"__stack_chk_fail_local"})
   684  			if isunresolved[0] {
   685  				if p := ctxt.findLibPath("libc_nonshared.a"); p != "none" {
   686  					hostArchive(ctxt, p)
   687  				}
   688  				if p := ctxt.findLibPath("libssp_nonshared.a"); p != "none" {
   689  					hostArchive(ctxt, p)
   690  				}
   691  			}
   692  		}
   693  	}
   694  
   695  	loadfips(ctxt)
   696  
   697  	// We've loaded all the code now.
   698  	ctxt.Loaded = true
   699  
   700  	strictDupMsgCount = ctxt.loader.NStrictDupMsgs()
   701  }
   702  
   703  // loadWindowsHostArchives loads in host archives and objects when
   704  // doing internal linking on windows. Older toolchains seem to require
   705  // just a single pass through the various archives, but some modern
   706  // toolchains when linking a C program with mingw pass library paths
   707  // multiple times to the linker, e.g. "... -lmingwex -lmingw32 ...
   708  // -lmingwex -lmingw32 ...". To accommodate this behavior, we make two
   709  // passes over the host archives below.
   710  func loadWindowsHostArchives(ctxt *Link) {
   711  	any := true
   712  	for i := 0; any && i < 2; i++ {
   713  		// Link crt2.o (if present) to resolve "atexit" when
   714  		// using LLVM-based compilers.
   715  		isunresolved := symbolsAreUnresolved(ctxt, []string{"atexit"})
   716  		if isunresolved[0] {
   717  			if p := ctxt.findLibPath("crt2.o"); p != "none" {
   718  				hostObject(ctxt, "crt2", p)
   719  			}
   720  		}
   721  		if *flagRace {
   722  			if p := ctxt.findLibPath("libsynchronization.a"); p != "none" {
   723  				hostArchive(ctxt, p)
   724  			}
   725  		}
   726  		if p := ctxt.findLibPath("libmingwex.a"); p != "none" {
   727  			hostArchive(ctxt, p)
   728  		}
   729  		if p := ctxt.findLibPath("libmingw32.a"); p != "none" {
   730  			hostArchive(ctxt, p)
   731  		}
   732  		// Link libmsvcrt.a to resolve '__acrt_iob_func' symbol
   733  		// (see https://golang.org/issue/23649 for details).
   734  		if p := ctxt.findLibPath("libmsvcrt.a"); p != "none" {
   735  			hostArchive(ctxt, p)
   736  		}
   737  		any = false
   738  		undefs, froms := ctxt.loader.UndefinedRelocTargets(1)
   739  		if len(undefs) > 0 {
   740  			any = true
   741  			if ctxt.Debugvlog > 1 {
   742  				ctxt.Logf("loadWindowsHostArchives: remaining unresolved is %s [%d] from %s [%d]\n",
   743  					ctxt.loader.SymName(undefs[0]), undefs[0],
   744  					ctxt.loader.SymName(froms[0]), froms[0])
   745  			}
   746  		}
   747  	}
   748  	// If needed, create the __CTOR_LIST__ and __DTOR_LIST__
   749  	// symbols (referenced by some of the mingw support library
   750  	// routines). Creation of these symbols is normally done by the
   751  	// linker if not already present.
   752  	want := []string{"__CTOR_LIST__", "__DTOR_LIST__"}
   753  	isunresolved := symbolsAreUnresolved(ctxt, want)
   754  	for k, w := range want {
   755  		if isunresolved[k] {
   756  			sb := ctxt.loader.CreateSymForUpdate(w, 0)
   757  			sb.SetType(sym.SDATA)
   758  			sb.AddUint64(ctxt.Arch, 0)
   759  			sb.SetReachable(true)
   760  			ctxt.loader.SetAttrSpecial(sb.Sym(), true)
   761  		}
   762  	}
   763  
   764  	// Fix up references to DLL import symbols now that we're done
   765  	// pulling in new objects.
   766  	if err := loadpe.PostProcessImports(); err != nil {
   767  		Errorf("%v", err)
   768  	}
   769  
   770  	// TODO: maybe do something similar to peimporteddlls to collect
   771  	// all lib names and try link them all to final exe just like
   772  	// libmingwex.a and libmingw32.a:
   773  	/*
   774  		for:
   775  		#cgo windows LDFLAGS: -lmsvcrt -lm
   776  		import:
   777  		libmsvcrt.a libm.a
   778  	*/
   779  }
   780  
   781  // loadcgodirectives reads the previously discovered cgo directives, creating
   782  // symbols in preparation for host object loading or use later in the link.
   783  func (ctxt *Link) loadcgodirectives() {
   784  	l := ctxt.loader
   785  	hostObjSyms := make(map[loader.Sym]struct{})
   786  	for _, d := range ctxt.cgodata {
   787  		setCgoAttr(ctxt, d.file, d.pkg, d.directives, hostObjSyms)
   788  	}
   789  	ctxt.cgodata = nil
   790  
   791  	if ctxt.LinkMode == LinkInternal {
   792  		// Drop all the cgo_import_static declarations.
   793  		// Turns out we won't be needing them.
   794  		for symIdx := range hostObjSyms {
   795  			if l.SymType(symIdx) == sym.SHOSTOBJ {
   796  				// If a symbol was marked both
   797  				// cgo_import_static and cgo_import_dynamic,
   798  				// then we want to make it cgo_import_dynamic
   799  				// now.
   800  				su := l.MakeSymbolUpdater(symIdx)
   801  				if l.SymExtname(symIdx) != "" && l.SymDynimplib(symIdx) != "" && !(l.AttrCgoExportStatic(symIdx) || l.AttrCgoExportDynamic(symIdx)) {
   802  					su.SetType(sym.SDYNIMPORT)
   803  				} else {
   804  					su.SetType(0)
   805  				}
   806  			}
   807  		}
   808  	}
   809  }
   810  
   811  // Set up flags and special symbols depending on the platform build mode.
   812  // This version works with loader.Loader.
   813  func (ctxt *Link) linksetup() {
   814  	switch ctxt.BuildMode {
   815  	case BuildModeCShared, BuildModePlugin:
   816  		symIdx := ctxt.loader.LookupOrCreateSym("runtime.islibrary", 0)
   817  		sb := ctxt.loader.MakeSymbolUpdater(symIdx)
   818  		sb.SetType(sym.SNOPTRDATA)
   819  		sb.AddUint8(1)
   820  	case BuildModeCArchive:
   821  		symIdx := ctxt.loader.LookupOrCreateSym("runtime.isarchive", 0)
   822  		sb := ctxt.loader.MakeSymbolUpdater(symIdx)
   823  		sb.SetType(sym.SNOPTRDATA)
   824  		sb.AddUint8(1)
   825  	}
   826  
   827  	// Recalculate pe parameters now that we have ctxt.LinkMode set.
   828  	if ctxt.HeadType == objabi.Hwindows {
   829  		Peinit(ctxt)
   830  	}
   831  
   832  	if ctxt.LinkMode == LinkExternal {
   833  		// When external linking, we are creating an object file. The
   834  		// absolute address is irrelevant.
   835  		*FlagTextAddr = 0
   836  	}
   837  
   838  	// If there are no dynamic libraries needed, gcc disables dynamic linking.
   839  	// Because of this, glibc's dynamic ELF loader occasionally (like in version 2.13)
   840  	// assumes that a dynamic binary always refers to at least one dynamic library.
   841  	// Rather than be a source of test cases for glibc, disable dynamic linking
   842  	// the same way that gcc would.
   843  	//
   844  	// Exception: on OS X, programs such as Shark only work with dynamic
   845  	// binaries, so leave it enabled on OS X (Mach-O) binaries.
   846  	// Also leave it enabled on Solaris which doesn't support
   847  	// statically linked binaries.
   848  	if ctxt.BuildMode == BuildModeExe {
   849  		if havedynamic == 0 && ctxt.HeadType != objabi.Hdarwin && ctxt.HeadType != objabi.Hsolaris {
   850  			*FlagD = true
   851  		}
   852  	}
   853  
   854  	if ctxt.LinkMode == LinkExternal && ctxt.Arch.Family == sys.PPC64 && buildcfg.GOOS != "aix" {
   855  		toc := ctxt.loader.LookupOrCreateSym(".TOC.", 0)
   856  		sb := ctxt.loader.MakeSymbolUpdater(toc)
   857  		sb.SetType(sym.SDYNIMPORT)
   858  	}
   859  
   860  	// The Android Q linker started to complain about underalignment of the our TLS
   861  	// section. We don't actually use the section on android, so don't
   862  	// generate it.
   863  	if buildcfg.GOOS != "android" {
   864  		tlsg := ctxt.loader.LookupOrCreateSym("runtime.tlsg", 0)
   865  		sb := ctxt.loader.MakeSymbolUpdater(tlsg)
   866  
   867  		// runtime.tlsg is used for external linking on platforms that do not define
   868  		// a variable to hold g in assembly (currently only intel).
   869  		if sb.Type() == 0 {
   870  			sb.SetType(sym.STLSBSS)
   871  			sb.SetSize(int64(ctxt.Arch.PtrSize))
   872  		} else if sb.Type() != sym.SDYNIMPORT {
   873  			Errorf("runtime declared tlsg variable %v", sb.Type())
   874  		}
   875  		ctxt.loader.SetAttrReachable(tlsg, true)
   876  		ctxt.Tlsg = tlsg
   877  
   878  		if ctxt.IsWindows() && ctxt.IsExternal() {
   879  			ctxt.loader.SetAttrNotInSymbolTable(tlsg, false)
   880  			tlsOffset := ctxt.loader.Lookup("runtime.tls_g", 0)
   881  			if tlsOffset == 0 {
   882  				Errorf("missing runtime.tls_g")
   883  			} else {
   884  				rel, _ := ctxt.loader.MakeSymbolUpdater(tlsOffset).AddRel(objabi.R_ADDROFF)
   885  				rel.SetOff(0)
   886  				rel.SetSiz(4)
   887  				rel.SetSym(tlsg)
   888  			}
   889  		}
   890  	}
   891  
   892  	var moduledata loader.Sym
   893  	var mdsb *loader.SymbolBuilder
   894  	if ctxt.BuildMode == BuildModePlugin {
   895  		moduledata = ctxt.loader.LookupOrCreateSym("local.pluginmoduledata", 0)
   896  		mdsb = ctxt.loader.MakeSymbolUpdater(moduledata)
   897  		ctxt.loader.SetAttrLocal(moduledata, true)
   898  	} else {
   899  		moduledata = ctxt.loader.LookupOrCreateSym("runtime.firstmoduledata", 0)
   900  		mdsb = ctxt.loader.MakeSymbolUpdater(moduledata)
   901  	}
   902  	if mdsb.Type() != 0 && mdsb.Type() != sym.SDYNIMPORT {
   903  		// If the module (toolchain-speak for "executable or shared
   904  		// library") we are linking contains the runtime package, it
   905  		// will define the runtime.firstmoduledata symbol and we
   906  		// truncate it back to 0 bytes so we can define its entire
   907  		// contents in symtab.go:symtab().
   908  		mdsb.SetSize(0)
   909  
   910  		// In addition, on ARM, the runtime depends on the linker
   911  		// recording the value of GOARM.
   912  		if ctxt.Arch.Family == sys.ARM {
   913  			goarm := ctxt.loader.LookupOrCreateSym("runtime.goarm", 0)
   914  			sb := ctxt.loader.MakeSymbolUpdater(goarm)
   915  			sb.SetType(sym.SNOPTRDATA)
   916  			sb.SetSize(0)
   917  			sb.AddUint8(uint8(buildcfg.GOARM.Version))
   918  
   919  			goarmsoftfp := ctxt.loader.LookupOrCreateSym("runtime.goarmsoftfp", 0)
   920  			sb2 := ctxt.loader.MakeSymbolUpdater(goarmsoftfp)
   921  			sb2.SetType(sym.SNOPTRDATA)
   922  			sb2.SetSize(0)
   923  			if buildcfg.GOARM.SoftFloat {
   924  				sb2.AddUint8(1)
   925  			} else {
   926  				sb2.AddUint8(0)
   927  			}
   928  		}
   929  
   930  		// Set runtime.disableMemoryProfiling bool if
   931  		// runtime.memProfileInternal is not retained in the binary after
   932  		// deadcode (and we're not dynamically linking).
   933  		memProfile := ctxt.loader.Lookup("runtime.memProfileInternal", abiInternalVer)
   934  		if memProfile != 0 && !ctxt.loader.AttrReachable(memProfile) && !ctxt.DynlinkingGo() {
   935  			memProfSym := ctxt.loader.LookupOrCreateSym("runtime.disableMemoryProfiling", 0)
   936  			sb := ctxt.loader.MakeSymbolUpdater(memProfSym)
   937  			sb.SetType(sym.SNOPTRDATA)
   938  			sb.SetSize(0)
   939  			sb.AddUint8(1) // true bool
   940  		}
   941  	} else {
   942  		// If OTOH the module does not contain the runtime package,
   943  		// create a local symbol for the moduledata.
   944  		moduledata = ctxt.loader.LookupOrCreateSym("local.moduledata", 0)
   945  		mdsb = ctxt.loader.MakeSymbolUpdater(moduledata)
   946  		ctxt.loader.SetAttrLocal(moduledata, true)
   947  	}
   948  	mdsb.SetType(sym.SMODULEDATA)
   949  	ctxt.loader.SetAttrReachable(moduledata, true)
   950  	ctxt.Moduledata = moduledata
   951  
   952  	if ctxt.Arch == sys.Arch386 && ctxt.HeadType != objabi.Hwindows {
   953  		if (ctxt.BuildMode == BuildModeCArchive && ctxt.IsELF) || ctxt.BuildMode == BuildModeCShared || ctxt.BuildMode == BuildModePIE || ctxt.DynlinkingGo() {
   954  			got := ctxt.loader.LookupOrCreateSym("_GLOBAL_OFFSET_TABLE_", 0)
   955  			sb := ctxt.loader.MakeSymbolUpdater(got)
   956  			sb.SetType(sym.SDYNIMPORT)
   957  			ctxt.loader.SetAttrReachable(got, true)
   958  		}
   959  	}
   960  
   961  	// DWARF-gen and other phases require that the unit Textp slices
   962  	// be populated, so that it can walk the functions in each unit.
   963  	// Call into the loader to do this (requires that we collect the
   964  	// set of internal libraries first). NB: might be simpler if we
   965  	// moved isRuntimeDepPkg to cmd/internal and then did the test in
   966  	// loader.AssignTextSymbolOrder.
   967  	ctxt.Library = postorder(ctxt.Library)
   968  	intlibs := []bool{}
   969  	for _, lib := range ctxt.Library {
   970  		intlibs = append(intlibs, isRuntimeDepPkg(lib.Pkg))
   971  	}
   972  	ctxt.Textp = ctxt.loader.AssignTextSymbolOrder(ctxt.Library, intlibs, ctxt.Textp)
   973  }
   974  
   975  // mangleTypeSym shortens the names of symbols that represent Go types
   976  // if they are visible in the symbol table.
   977  //
   978  // As the names of these symbols are derived from the string of
   979  // the type, they can run to many kilobytes long. So we shorten
   980  // them using a SHA-1 when the name appears in the final binary.
   981  // This also removes characters that upset external linkers.
   982  //
   983  // These are the symbols that begin with the prefix 'type.' and
   984  // contain run-time type information used by the runtime and reflect
   985  // packages. All Go binaries contain these symbols, but only
   986  // those programs loaded dynamically in multiple parts need these
   987  // symbols to have entries in the symbol table.
   988  func (ctxt *Link) mangleTypeSym() {
   989  	if ctxt.BuildMode != BuildModeShared && !ctxt.linkShared && ctxt.BuildMode != BuildModePlugin && !ctxt.CanUsePlugins() {
   990  		return
   991  	}
   992  
   993  	ldr := ctxt.loader
   994  	for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
   995  		if !ldr.AttrReachable(s) && !ctxt.linkShared {
   996  			// If -linkshared, the gc mask generation code may need to reach
   997  			// out to the shared library for the type descriptor's data, even
   998  			// the type descriptor itself is not actually needed at run time
   999  			// (therefore not reachable). We still need to mangle its name,
  1000  			// so it is consistent with the one stored in the shared library.
  1001  			continue
  1002  		}
  1003  		name := ldr.SymName(s)
  1004  		newName := typeSymbolMangle(name)
  1005  		if newName != name {
  1006  			ldr.SetSymExtname(s, newName)
  1007  
  1008  			// When linking against a shared library, the Go object file may
  1009  			// have reference to the original symbol name whereas the shared
  1010  			// library provides a symbol with the mangled name. We need to
  1011  			// copy the payload of mangled to original.
  1012  			// XXX maybe there is a better way to do this.
  1013  			dup := ldr.Lookup(newName, ldr.SymVersion(s))
  1014  			if dup != 0 {
  1015  				st := ldr.SymType(s)
  1016  				dt := ldr.SymType(dup)
  1017  				if st == sym.Sxxx && dt != sym.Sxxx {
  1018  					ldr.CopySym(dup, s)
  1019  				}
  1020  			}
  1021  		}
  1022  	}
  1023  }
  1024  
  1025  // typeSymbolMangle mangles the given symbol name into something shorter.
  1026  //
  1027  // Keep the type:. prefix, which parts of the linker (like the
  1028  // DWARF generator) know means the symbol is not decodable.
  1029  // Leave type:runtime. symbols alone, because other parts of
  1030  // the linker manipulates them.
  1031  func typeSymbolMangle(name string) string {
  1032  	isType := strings.HasPrefix(name, "type:")
  1033  	if !isType && !strings.Contains(name, "@") {
  1034  		// Issue 58800: instantiated symbols may include a type name, which may contain "@"
  1035  		return name
  1036  	}
  1037  	if strings.HasPrefix(name, "type:runtime.") {
  1038  		return name
  1039  	}
  1040  	if strings.HasPrefix(name, "go:string.") {
  1041  		// String symbols will be grouped to a single go:string.* symbol.
  1042  		// No need to mangle individual symbol names.
  1043  		return name
  1044  	}
  1045  	if len(name) <= 14 && !strings.Contains(name, "@") { // Issue 19529
  1046  		return name
  1047  	}
  1048  	if isType {
  1049  		hb := hash.Sum32([]byte(name[5:]))
  1050  		prefix := "type:"
  1051  		if name[5] == '.' {
  1052  			prefix = "type:."
  1053  		}
  1054  		return prefix + base64.StdEncoding.EncodeToString(hb[:6])
  1055  	}
  1056  	// instantiated symbol, replace type name in []
  1057  	i := strings.IndexByte(name, '[')
  1058  	j := strings.LastIndexByte(name, ']')
  1059  	if j == -1 || j <= i {
  1060  		j = len(name)
  1061  	}
  1062  	hb := hash.Sum32([]byte(name[i+1 : j]))
  1063  	return name[:i+1] + base64.StdEncoding.EncodeToString(hb[:6]) + name[j:]
  1064  }
  1065  
  1066  /*
  1067   * look for the next file in an archive.
  1068   * adapted from libmach.
  1069   */
  1070  func nextar(bp *bio.Reader, off int64, a *ArHdr) int64 {
  1071  	if off&1 != 0 {
  1072  		off++
  1073  	}
  1074  	bp.MustSeek(off, 0)
  1075  	var buf [SAR_HDR]byte
  1076  	if n, err := io.ReadFull(bp, buf[:]); err != nil {
  1077  		if n == 0 && err != io.EOF {
  1078  			return -1
  1079  		}
  1080  		return 0
  1081  	}
  1082  
  1083  	a.name = artrim(buf[0:16])
  1084  	a.date = artrim(buf[16:28])
  1085  	a.uid = artrim(buf[28:34])
  1086  	a.gid = artrim(buf[34:40])
  1087  	a.mode = artrim(buf[40:48])
  1088  	a.size = artrim(buf[48:58])
  1089  	a.fmag = artrim(buf[58:60])
  1090  
  1091  	arsize := atolwhex(a.size)
  1092  	if arsize&1 != 0 {
  1093  		arsize++
  1094  	}
  1095  	return arsize + SAR_HDR
  1096  }
  1097  
  1098  func loadobjfile(ctxt *Link, lib *sym.Library) {
  1099  	pkg := objabi.PathToPrefix(lib.Pkg)
  1100  
  1101  	if ctxt.Debugvlog > 1 {
  1102  		ctxt.Logf("ldobj: %s (%s)\n", lib.File, pkg)
  1103  	}
  1104  	f, err := bio.Open(lib.File)
  1105  	if err != nil {
  1106  		Exitf("cannot open file %s: %v", lib.File, err)
  1107  	}
  1108  	defer f.Close()
  1109  	defer func() {
  1110  		if pkg == "main" && !lib.Main {
  1111  			Exitf("%s: not package main", lib.File)
  1112  		}
  1113  	}()
  1114  
  1115  	for i := 0; i < len(ARMAG); i++ {
  1116  		if c, err := f.ReadByte(); err == nil && c == ARMAG[i] {
  1117  			continue
  1118  		}
  1119  
  1120  		/* load it as a regular file */
  1121  		l := f.MustSeek(0, 2)
  1122  		f.MustSeek(0, 0)
  1123  		ldobj(ctxt, f, lib, l, lib.File, lib.File)
  1124  		return
  1125  	}
  1126  
  1127  	/*
  1128  	 * load all the object files from the archive now.
  1129  	 * this gives us sequential file access and keeps us
  1130  	 * from needing to come back later to pick up more
  1131  	 * objects.  it breaks the usual C archive model, but
  1132  	 * this is Go, not C.  the common case in Go is that
  1133  	 * we need to load all the objects, and then we throw away
  1134  	 * the individual symbols that are unused.
  1135  	 *
  1136  	 * loading every object will also make it possible to
  1137  	 * load foreign objects not referenced by __.PKGDEF.
  1138  	 */
  1139  	var arhdr ArHdr
  1140  	off := f.Offset()
  1141  	for {
  1142  		l := nextar(f, off, &arhdr)
  1143  		if l == 0 {
  1144  			break
  1145  		}
  1146  		if l < 0 {
  1147  			Exitf("%s: malformed archive", lib.File)
  1148  		}
  1149  		off += l
  1150  
  1151  		// __.PKGDEF isn't a real Go object file, and it's
  1152  		// absent in -linkobj builds anyway. Skipping it
  1153  		// ensures consistency between -linkobj and normal
  1154  		// build modes.
  1155  		if arhdr.name == pkgdef {
  1156  			continue
  1157  		}
  1158  
  1159  		if arhdr.name == "dynimportfail" {
  1160  			dynimportfail = append(dynimportfail, lib.Pkg)
  1161  		}
  1162  		if arhdr.name == "preferlinkext" {
  1163  			// Ignore this directive if -linkmode has been
  1164  			// set explicitly.
  1165  			if ctxt.LinkMode == LinkAuto {
  1166  				preferlinkext = append(preferlinkext, lib.Pkg)
  1167  			}
  1168  		}
  1169  
  1170  		// Skip other special (non-object-file) sections that
  1171  		// build tools may have added. Such sections must have
  1172  		// short names so that the suffix is not truncated.
  1173  		if len(arhdr.name) < 16 {
  1174  			if ext := filepath.Ext(arhdr.name); ext != ".o" && ext != ".syso" {
  1175  				continue
  1176  			}
  1177  		}
  1178  
  1179  		pname := fmt.Sprintf("%s(%s)", lib.File, arhdr.name)
  1180  		l = atolwhex(arhdr.size)
  1181  		ldobj(ctxt, f, lib, l, pname, lib.File)
  1182  	}
  1183  }
  1184  
  1185  type Hostobj struct {
  1186  	ld     func(*Link, *bio.Reader, string, int64, string)
  1187  	pkg    string
  1188  	pn     string
  1189  	file   string
  1190  	off    int64
  1191  	length int64
  1192  }
  1193  
  1194  var hostobj []Hostobj
  1195  
  1196  // These packages can use internal linking mode.
  1197  // Others trigger external mode.
  1198  var internalpkg = []string{
  1199  	"crypto/internal/boring",
  1200  	"crypto/internal/boring/syso",
  1201  	"crypto/x509",
  1202  	"internal/runtime/cgobench", // for cmd/go tests
  1203  	"net",
  1204  	"os/user",
  1205  	"runtime/cgo",
  1206  	"runtime/race",
  1207  	"runtime/race/internal/amd64v1",
  1208  	"runtime/race/internal/amd64v3",
  1209  	"runtime/msan",
  1210  	"runtime/asan",
  1211  }
  1212  
  1213  func ldhostobj(ld func(*Link, *bio.Reader, string, int64, string), headType objabi.HeadType, f *bio.Reader, pkg string, length int64, pn string, file string) *Hostobj {
  1214  	isinternal := false
  1215  	for _, intpkg := range internalpkg {
  1216  		if pkg == intpkg {
  1217  			isinternal = true
  1218  			break
  1219  		}
  1220  	}
  1221  
  1222  	// DragonFly declares errno with __thread, which results in a symbol
  1223  	// type of R_386_TLS_GD or R_X86_64_TLSGD. The Go linker does not
  1224  	// currently know how to handle TLS relocations, hence we have to
  1225  	// force external linking for any libraries that link in code that
  1226  	// uses errno. This can be removed if the Go linker ever supports
  1227  	// these relocation types.
  1228  	if headType == objabi.Hdragonfly {
  1229  		if pkg == "net" || pkg == "os/user" {
  1230  			isinternal = false
  1231  		}
  1232  	}
  1233  
  1234  	if !isinternal {
  1235  		externalobj = true
  1236  	}
  1237  
  1238  	hostobj = append(hostobj, Hostobj{})
  1239  	h := &hostobj[len(hostobj)-1]
  1240  	h.ld = ld
  1241  	h.pkg = pkg
  1242  	h.pn = pn
  1243  	h.file = file
  1244  	h.off = f.Offset()
  1245  	h.length = length
  1246  	return h
  1247  }
  1248  
  1249  func hostobjs(ctxt *Link) {
  1250  	if ctxt.LinkMode != LinkInternal {
  1251  		return
  1252  	}
  1253  	var h *Hostobj
  1254  
  1255  	for i := 0; i < len(hostobj); i++ {
  1256  		h = &hostobj[i]
  1257  		f, err := bio.Open(h.file)
  1258  		if err != nil {
  1259  			Exitf("cannot reopen %s: %v", h.pn, err)
  1260  		}
  1261  		f.MustSeek(h.off, 0)
  1262  		if h.ld == nil {
  1263  			Errorf("%s: unrecognized object file format", h.pn)
  1264  			f.Close()
  1265  			continue
  1266  		}
  1267  		h.ld(ctxt, f, h.pkg, h.length, h.pn)
  1268  		if *flagCaptureHostObjs != "" {
  1269  			captureHostObj(h)
  1270  		}
  1271  		f.Close()
  1272  	}
  1273  }
  1274  
  1275  func hostlinksetup(ctxt *Link) {
  1276  	if ctxt.LinkMode != LinkExternal {
  1277  		return
  1278  	}
  1279  
  1280  	// For external link, record that we need to tell the external linker -s,
  1281  	// and turn off -s internally: the external linker needs the symbol
  1282  	// information for its final link.
  1283  	debug_s = *FlagS
  1284  	*FlagS = false
  1285  
  1286  	// create temporary directory and arrange cleanup
  1287  	if *flagTmpdir == "" {
  1288  		dir, err := os.MkdirTemp("", "go-link-")
  1289  		if err != nil {
  1290  			log.Fatal(err)
  1291  		}
  1292  		*flagTmpdir = dir
  1293  		ownTmpDir = true
  1294  		AtExit(func() {
  1295  			os.RemoveAll(*flagTmpdir)
  1296  		})
  1297  	}
  1298  
  1299  	// change our output to temporary object file
  1300  	if err := ctxt.Out.Close(); err != nil {
  1301  		Exitf("error closing output file")
  1302  	}
  1303  	mayberemoveoutfile()
  1304  
  1305  	p := filepath.Join(*flagTmpdir, "go.o")
  1306  	if err := ctxt.Out.Open(p); err != nil {
  1307  		Exitf("cannot create %s: %v", p, err)
  1308  	}
  1309  }
  1310  
  1311  // cleanTimeStamps resets the timestamps for the specified list of
  1312  // existing files to the Unix epoch (1970-01-01 00:00:00 +0000 UTC).
  1313  // We take this step in order to help preserve reproducible builds;
  1314  // this seems to be primarily needed for external linking on Darwin
  1315  // with later versions of xcode, which (unfortunately) seem to want to
  1316  // incorporate object file times into the final output file's build
  1317  // ID. See issue 64947 for the unpleasant details.
  1318  func cleanTimeStamps(files []string) {
  1319  	epocht := time.Unix(0, 0)
  1320  	for _, f := range files {
  1321  		if err := os.Chtimes(f, epocht, epocht); err != nil {
  1322  			Exitf("cannot chtimes %s: %v", f, err)
  1323  		}
  1324  	}
  1325  }
  1326  
  1327  // hostobjCopy creates a copy of the object files in hostobj in a
  1328  // temporary directory.
  1329  func (ctxt *Link) hostobjCopy() (paths []string) {
  1330  	var wg sync.WaitGroup
  1331  	sema := make(chan struct{}, runtime.NumCPU()) // limit open file descriptors
  1332  	for i, h := range hostobj {
  1333  		h := h
  1334  		dst := filepath.Join(*flagTmpdir, fmt.Sprintf("%06d.o", i))
  1335  		paths = append(paths, dst)
  1336  		if ctxt.Debugvlog != 0 {
  1337  			ctxt.Logf("host obj copy: %s from pkg %s -> %s\n", h.pn, h.pkg, dst)
  1338  		}
  1339  
  1340  		wg.Add(1)
  1341  		go func() {
  1342  			sema <- struct{}{}
  1343  			defer func() {
  1344  				<-sema
  1345  				wg.Done()
  1346  			}()
  1347  			f, err := os.Open(h.file)
  1348  			if err != nil {
  1349  				Exitf("cannot reopen %s: %v", h.pn, err)
  1350  			}
  1351  			defer f.Close()
  1352  			if _, err := f.Seek(h.off, 0); err != nil {
  1353  				Exitf("cannot seek %s: %v", h.pn, err)
  1354  			}
  1355  
  1356  			w, err := os.Create(dst)
  1357  			if err != nil {
  1358  				Exitf("cannot create %s: %v", dst, err)
  1359  			}
  1360  			if _, err := io.CopyN(w, f, h.length); err != nil {
  1361  				Exitf("cannot write %s: %v", dst, err)
  1362  			}
  1363  			if err := w.Close(); err != nil {
  1364  				Exitf("cannot close %s: %v", dst, err)
  1365  			}
  1366  		}()
  1367  	}
  1368  	wg.Wait()
  1369  	return paths
  1370  }
  1371  
  1372  // writeGDBLinkerScript creates gcc linker script file in temp
  1373  // directory. writeGDBLinkerScript returns created file path.
  1374  // The script is used to work around gcc bug
  1375  // (see https://golang.org/issue/20183 for details).
  1376  func writeGDBLinkerScript() string {
  1377  	name := "fix_debug_gdb_scripts.ld"
  1378  	path := filepath.Join(*flagTmpdir, name)
  1379  	src := `SECTIONS
  1380  {
  1381    .debug_gdb_scripts BLOCK(__section_alignment__) (NOLOAD) :
  1382    {
  1383      *(.debug_gdb_scripts)
  1384    }
  1385  }
  1386  INSERT AFTER .debug_types;
  1387  `
  1388  	err := os.WriteFile(path, []byte(src), 0666)
  1389  	if err != nil {
  1390  		Errorf("WriteFile %s failed: %v", name, err)
  1391  	}
  1392  	return path
  1393  }
  1394  
  1395  type machoUpdateFunc func(ctxt *Link, exef *os.File, exem *macho.File, outexe string) error
  1396  
  1397  // archive builds a .a archive from the hostobj object files.
  1398  func (ctxt *Link) archive() {
  1399  	if ctxt.BuildMode != BuildModeCArchive {
  1400  		return
  1401  	}
  1402  	if restrictedBuild() {
  1403  		Exitf("c-archive build mode is not allowed when GORESTRICTEDBUILD=1")
  1404  	}
  1405  
  1406  	exitIfErrors()
  1407  
  1408  	if *flagExtar == "" {
  1409  		const printProgName = "--print-prog-name=ar"
  1410  		cc := ctxt.extld()
  1411  		*flagExtar = "ar"
  1412  		if linkerFlagSupported(ctxt.Arch, cc, "", printProgName) {
  1413  			*flagExtar = ctxt.findExtLinkTool("ar")
  1414  		}
  1415  	}
  1416  
  1417  	mayberemoveoutfile()
  1418  
  1419  	// Force the buffer to flush here so that external
  1420  	// tools will see a complete file.
  1421  	if err := ctxt.Out.Close(); err != nil {
  1422  		Exitf("error closing %v", *flagOutfile)
  1423  	}
  1424  
  1425  	argv := []string{*flagExtar, "-q", "-c", "-s"}
  1426  	if ctxt.HeadType == objabi.Haix {
  1427  		argv = append(argv, "-X64")
  1428  	}
  1429  	godotopath := filepath.Join(*flagTmpdir, "go.o")
  1430  	cleanTimeStamps([]string{godotopath})
  1431  	hostObjCopyPaths := ctxt.hostobjCopy()
  1432  	cleanTimeStamps(hostObjCopyPaths)
  1433  
  1434  	argv = append(argv, *flagOutfile)
  1435  	argv = append(argv, godotopath)
  1436  	argv = append(argv, hostObjCopyPaths...)
  1437  
  1438  	if ctxt.Debugvlog != 0 {
  1439  		ctxt.Logf("archive: %s\n", strings.Join(argv, " "))
  1440  	}
  1441  
  1442  	// If supported, use syscall.Exec() to invoke the archive command,
  1443  	// which should be the final remaining step needed for the link.
  1444  	// This will reduce peak RSS for the link (and speed up linking of
  1445  	// large applications), since when the archive command runs we
  1446  	// won't be holding onto all of the linker's live memory.
  1447  	if syscallExecSupported && !ownTmpDir {
  1448  		runAtExitFuncs()
  1449  		ctxt.execArchive(argv)
  1450  		panic("should not get here")
  1451  	}
  1452  
  1453  	// Otherwise invoke 'ar' in the usual way (fork + exec).
  1454  	if out, err := exec.Command(argv[0], argv[1:]...).CombinedOutput(); err != nil {
  1455  		Exitf("running %s failed: %v\n%s", argv[0], err, out)
  1456  	}
  1457  }
  1458  
  1459  func (ctxt *Link) hostlink() {
  1460  	if ctxt.LinkMode != LinkExternal || nerrors > 0 {
  1461  		return
  1462  	}
  1463  	if restrictedBuild() {
  1464  		Exitf("external linking is not allowed when GORESTRICTEDBUILD=1")
  1465  	}
  1466  	if ctxt.BuildMode == BuildModeCArchive {
  1467  		return
  1468  	}
  1469  
  1470  	var argv []string
  1471  	argv = append(argv, ctxt.extld()...)
  1472  	argv = append(argv, hostlinkArchArgs(ctxt.Arch)...)
  1473  
  1474  	if *FlagS || debug_s {
  1475  		if ctxt.HeadType == objabi.Hdarwin {
  1476  			// Recent versions of macOS print
  1477  			//	ld: warning: option -s is obsolete and being ignored
  1478  			// so do not pass any arguments (but we strip symbols below).
  1479  		} else {
  1480  			argv = append(argv, "-s")
  1481  		}
  1482  	} else if *FlagW {
  1483  		if !ctxt.IsAIX() && !ctxt.IsSolaris() { // The AIX and Solaris linkers' -S has different meaning
  1484  			argv = append(argv, "-Wl,-S") // suppress debugging symbols
  1485  		}
  1486  	}
  1487  
  1488  	// On darwin, whether to generate DWARF with dsymutil, and whether to
  1489  	// combine it into the executable.
  1490  	// Only macOS supports unmapped segments such as our __DWARF segment.
  1491  	machoDwarf := ctxt.IsDarwin() && !*FlagW && (*FlagSplitDWARF || machoPlatform == PLATFORM_MACOS)
  1492  	combineDwarf := machoDwarf && !*FlagSplitDWARF
  1493  
  1494  	var isMSVC, isLLD bool // used on Windows
  1495  	wlPrefix := "-Wl,--"
  1496  
  1497  	switch ctxt.HeadType {
  1498  	case objabi.Hdarwin:
  1499  		if combineDwarf {
  1500  			// Leave room for DWARF combining.
  1501  			// -headerpad is incompatible with -fembed-bitcode.
  1502  			argv = append(argv, "-Wl,-headerpad,1144")
  1503  		}
  1504  		if ctxt.DynlinkingGo() && buildcfg.GOOS != "ios" {
  1505  			// -flat_namespace is deprecated on iOS.
  1506  			// It is useful for supporting plugins. We don't support plugins on iOS.
  1507  			// -flat_namespace may cause the dynamic linker to hang at forkExec when
  1508  			// resolving a lazy binding. See issue 38824.
  1509  			// Force eager resolution to work around.
  1510  			argv = append(argv, "-Wl,-flat_namespace", "-Wl,-bind_at_load")
  1511  			if combineDwarf && linkerFlagSupported(ctxt.Arch, ctxt.extld(), "", "-Wl,-no_fixup_chains") {
  1512  				// As of macOS 27, the dynamic linker checks the number of segments
  1513  				// in recorded in LC_DYLD_CHAINED_FIXUPS and reject the shared object
  1514  				// with a mismatch. When combining DWARF, we add a segment but
  1515  				// currently don't fix up the recorded number. Pass -no_fixup_chains to
  1516  				// the C linker as a workaround. See issue 81793.
  1517  				argv = append(argv, "-Wl,-no_fixup_chains")
  1518  			}
  1519  		}
  1520  		if !machoDwarf {
  1521  			argv = append(argv, "-Wl,-S") // suppress STAB (symbolic debugging) symbols
  1522  			if debug_s {
  1523  				// We are generating a binary with symbol table suppressed.
  1524  				// Suppress local symbols. We need to keep dynamically exported
  1525  				// and referenced symbols so the dynamic linker can resolve them.
  1526  				argv = append(argv, "-Wl,-x")
  1527  			}
  1528  		}
  1529  		if *flagRace {
  1530  			// With https://github.com/llvm/llvm-project/pull/182943, the race object
  1531  			// has a weak import of __dyld_get_dyld_header, which is only defined on
  1532  			// newer macOS (26.4+).
  1533  			argv = append(argv, "-Wl,-U,__dyld_get_dyld_header")
  1534  		}
  1535  		if *flagHostBuildid == "none" {
  1536  			argv = append(argv, "-Wl,-no_uuid")
  1537  		}
  1538  	case objabi.Hopenbsd:
  1539  		argv = append(argv, "-pthread")
  1540  		if linkerFlagSupported(ctxt.Arch, ctxt.extld(), "", "-Wl,-z,nobtcfi") {
  1541  			// -Wl,-z,nobtcfi is only supported on OpenBSD 7.4+, remove guard
  1542  			// when OpenBSD 7.5 is released and 7.3 is no longer supported.
  1543  			argv = append(argv, "-Wl,-z,nobtcfi")
  1544  		}
  1545  		if ctxt.Arch.InFamily(sys.ARM64) {
  1546  			// Disable execute-only on openbsd/arm64 - the Go arm64 assembler
  1547  			// currently stores constants in the text section rather than in rodata.
  1548  			// See issue #59615.
  1549  			argv = append(argv, "-Wl,--no-execute-only")
  1550  		}
  1551  	case objabi.Hwindows:
  1552  		isMSVC = ctxt.isMSVC()
  1553  		isLLD = ctxt.isLLD()
  1554  		if isMSVC {
  1555  			// For various options, MSVC lld-link only accepts one dash.
  1556  			// TODO: It seems mingw clang supports one or two dashes,
  1557  			// maybe we can always use one dash,  but I'm not sure about
  1558  			// legacy compilers that currently work.
  1559  			wlPrefix = "-Wl,-"
  1560  		}
  1561  
  1562  		if windowsgui {
  1563  			argv = append(argv, "-mwindows")
  1564  		} else {
  1565  			argv = append(argv, "-mconsole")
  1566  		}
  1567  		// Mark as having awareness of terminal services, to avoid
  1568  		// ancient compatibility hacks.
  1569  
  1570  		argv = append(argv, wlPrefix+"tsaware")
  1571  
  1572  		// Enable DEP
  1573  		argv = append(argv, wlPrefix+"nxcompat")
  1574  
  1575  		if !isMSVC {
  1576  			peMajorVersion := PeMinimumTargetMajorVersion
  1577  			peMinorVersion := PeMinimumTargetMinorVersion
  1578  			if peMajorVersion >= 10 && !isLLD &&
  1579  				!peHasLoadConfigDirectorySupport(ctxt.Arch, ctxt.extld()) {
  1580  				// The external linker doesn't support wiring up
  1581  				// _load_config_used to the PE Load Configuration
  1582  				// Directory. Windows 10+ validates this directory,
  1583  				// so fall back to an older version to avoid
  1584  				// load failures.
  1585  				peMajorVersion = 6
  1586  				peMinorVersion = 1
  1587  			}
  1588  			argv = append(argv, fmt.Sprintf("-Wl,--major-os-version=%d", peMajorVersion))
  1589  			argv = append(argv, fmt.Sprintf("-Wl,--minor-os-version=%d", peMinorVersion))
  1590  			argv = append(argv, fmt.Sprintf("-Wl,--major-subsystem-version=%d", peMajorVersion))
  1591  			argv = append(argv, fmt.Sprintf("-Wl,--minor-subsystem-version=%d", peMinorVersion))
  1592  		}
  1593  	case objabi.Haix:
  1594  		argv = append(argv, "-pthread")
  1595  		// prevent ld to reorder .text functions to keep the same
  1596  		// first/last functions for moduledata.
  1597  		argv = append(argv, "-Wl,-bnoobjreorder")
  1598  		// mcmodel=large is needed for every gcc generated files, but
  1599  		// ld still need -bbigtoc in order to allow larger TOC.
  1600  		argv = append(argv, "-mcmodel=large")
  1601  		argv = append(argv, "-Wl,-bbigtoc")
  1602  	}
  1603  
  1604  	// On PPC64, verify the external toolchain supports Power10. This is needed when
  1605  	// PC relative relocations might be generated by Go. Only targets compiling ELF
  1606  	// binaries might generate these relocations.
  1607  	if ctxt.IsPPC64() && ctxt.IsElf() && buildcfg.GOPPC64 >= 10 {
  1608  		if !linkerFlagSupported(ctxt.Arch, ctxt.extld(), "", "-mcpu=power10") {
  1609  			Exitf("The external toolchain does not support -mcpu=power10. " +
  1610  				" This is required to externally link GOPPC64 >= power10")
  1611  		}
  1612  	}
  1613  
  1614  	// Enable/disable ASLR on Windows.
  1615  	addASLRargs := func(argv []string, val bool) []string {
  1616  		// Old/ancient versions of GCC support "--dynamicbase" and
  1617  		// "--high-entropy-va" but don't enable it by default. In
  1618  		// addition, they don't accept "--disable-dynamicbase" or
  1619  		// "--no-dynamicbase", so the only way to disable ASLR is to
  1620  		// not pass any flags at all.
  1621  		//
  1622  		// More modern versions of GCC (and also clang) enable ASLR
  1623  		// by default. With these compilers, however you can turn it
  1624  		// off if you want using "--disable-dynamicbase" or
  1625  		// "--no-dynamicbase".
  1626  		//
  1627  		// The strategy below is to try using "--disable-dynamicbase";
  1628  		// if this succeeds, then assume we're working with more
  1629  		// modern compilers and act accordingly. If it fails, assume
  1630  		// an ancient compiler with ancient defaults.
  1631  		var dbopt string
  1632  		var heopt string
  1633  		dbon := wlPrefix + "dynamicbase"
  1634  		heon := wlPrefix + "high-entropy-va"
  1635  		dboff := wlPrefix + "disable-dynamicbase"
  1636  		heoff := wlPrefix + "disable-high-entropy-va"
  1637  		if isMSVC {
  1638  			heon = wlPrefix + "highentropyva"
  1639  			heoff = wlPrefix + "highentropyva:no"
  1640  			dboff = wlPrefix + "dynamicbase:no"
  1641  		}
  1642  		if val {
  1643  			dbopt = dbon
  1644  			heopt = heon
  1645  		} else {
  1646  			// Test to see whether "--disable-dynamicbase" works.
  1647  			newer := linkerFlagSupported(ctxt.Arch, ctxt.extld(), "", dboff)
  1648  			if newer {
  1649  				// Newer compiler, which supports both on/off options.
  1650  				dbopt = dboff
  1651  				heopt = heoff
  1652  			} else {
  1653  				// older toolchain: we have to say nothing in order to
  1654  				// get a no-ASLR binary.
  1655  				dbopt = ""
  1656  				heopt = ""
  1657  			}
  1658  		}
  1659  		if dbopt != "" {
  1660  			argv = append(argv, dbopt)
  1661  		}
  1662  		// enable high-entropy ASLR on 64-bit.
  1663  		if ctxt.Arch.PtrSize >= 8 && heopt != "" {
  1664  			argv = append(argv, heopt)
  1665  		}
  1666  		return argv
  1667  	}
  1668  
  1669  	switch ctxt.BuildMode {
  1670  	case BuildModeExe:
  1671  		if ctxt.HeadType == objabi.Hdarwin {
  1672  			if machoPlatform == PLATFORM_MACOS && ctxt.IsAMD64() {
  1673  				argv = append(argv, "-Wl,-no_pie")
  1674  			}
  1675  		}
  1676  		if *flagRace && ctxt.HeadType == objabi.Hwindows {
  1677  			// Current windows/amd64 race detector tsan support
  1678  			// library can't handle PIE mode (see #53539 for more details).
  1679  			// For now, explicitly disable PIE (since some compilers
  1680  			// default to it) if -race is in effect.
  1681  			argv = addASLRargs(argv, false)
  1682  		}
  1683  	case BuildModePIE:
  1684  		switch ctxt.HeadType {
  1685  		case objabi.Hdarwin, objabi.Haix:
  1686  		case objabi.Hwindows:
  1687  			if *flagAslr && *flagRace {
  1688  				// Current windows/amd64 race detector tsan support
  1689  				// library can't handle PIE mode (see #53539 for more details).
  1690  				// Disable alsr if -race in effect.
  1691  				*flagAslr = false
  1692  			}
  1693  			argv = addASLRargs(argv, *flagAslr)
  1694  		default:
  1695  			// ELF.
  1696  			if ctxt.UseRelro() {
  1697  				argv = append(argv, "-Wl,-z,relro")
  1698  			}
  1699  			argv = append(argv, "-pie")
  1700  		}
  1701  	case BuildModeCShared:
  1702  		if ctxt.HeadType == objabi.Hdarwin {
  1703  			argv = append(argv, "-dynamiclib")
  1704  		} else {
  1705  			if ctxt.UseRelro() {
  1706  				argv = append(argv, "-Wl,-z,relro")
  1707  			}
  1708  			argv = append(argv, "-shared")
  1709  			if ctxt.HeadType == objabi.Hwindows {
  1710  				argv = addASLRargs(argv, *flagAslr)
  1711  			} else {
  1712  				// Pass -z nodelete to mark the shared library as
  1713  				// non-closeable: a dlclose will do nothing.
  1714  				argv = append(argv, "-Wl,-z,nodelete")
  1715  				// Only pass Bsymbolic on non-Windows.
  1716  				argv = append(argv, "-Wl,-Bsymbolic")
  1717  			}
  1718  		}
  1719  	case BuildModeShared:
  1720  		if ctxt.UseRelro() {
  1721  			argv = append(argv, "-Wl,-z,relro")
  1722  		}
  1723  		argv = append(argv, "-shared")
  1724  	case BuildModePlugin:
  1725  		if ctxt.HeadType == objabi.Hdarwin {
  1726  			argv = append(argv, "-dynamiclib")
  1727  		} else {
  1728  			if ctxt.UseRelro() {
  1729  				argv = append(argv, "-Wl,-z,relro")
  1730  			}
  1731  			argv = append(argv, "-shared")
  1732  		}
  1733  	}
  1734  
  1735  	var altLinker string
  1736  	if ctxt.IsELF && (ctxt.DynlinkingGo() || *flagBindNow) {
  1737  		// For ELF targets, when producing dynamically linked Go code
  1738  		// or when immediate binding is explicitly requested,
  1739  		// we force all symbol resolution to be done at program startup
  1740  		// because lazy PLT resolution can use large amounts of stack at
  1741  		// times we cannot allow it to do so.
  1742  		argv = append(argv, "-Wl,-z,now")
  1743  	}
  1744  
  1745  	if ctxt.IsELF && ctxt.DynlinkingGo() {
  1746  		// Do not let the host linker generate COPY relocations. These
  1747  		// can move symbols out of sections that rely on stable offsets
  1748  		// from the beginning of the section (like sym.STYPE).
  1749  		argv = append(argv, "-Wl,-z,nocopyreloc")
  1750  
  1751  		if buildcfg.GOOS == "android" {
  1752  			// Use lld to avoid errors from default linker (issue #38838)
  1753  			altLinker = "lld"
  1754  		}
  1755  
  1756  		if ctxt.Arch.InFamily(sys.ARM64) && buildcfg.GOOS == "linux" {
  1757  			// On ARM64, the GNU linker had issues with -znocopyreloc
  1758  			// and COPY relocations. This was fixed in GNU ld 2.36+.
  1759  			// https://sourceware.org/bugzilla/show_bug.cgi?id=19962
  1760  			// https://go.dev/issue/22040
  1761  			// And newer gold is deprecated, may lack new features/flags, or even missing
  1762  
  1763  			// If the default linker is GNU ld 2.35 or older, use gold
  1764  			useGold := false
  1765  			name, args := flagExtld[0], flagExtld[1:]
  1766  			args = append(args, "-Wl,--version")
  1767  			cmd := exec.Command(name, args...)
  1768  			if out, err := cmd.CombinedOutput(); err == nil {
  1769  				// Parse version from output like "GNU ld (GNU Binutils for Distro) 2.36.1"
  1770  				for line := range strings.Lines(string(out)) {
  1771  					if !strings.HasPrefix(line, "GNU ld ") {
  1772  						continue
  1773  					}
  1774  					fields := strings.Fields(line[len("GNU ld "):])
  1775  					var major, minor int
  1776  					if ret, err := fmt.Sscanf(fields[len(fields)-1], "%d.%d", &major, &minor); ret == 2 && err == nil {
  1777  						if major == 2 && minor <= 35 {
  1778  							useGold = true
  1779  						}
  1780  						break
  1781  					}
  1782  				}
  1783  			}
  1784  
  1785  			if useGold {
  1786  				// Use gold for older linkers
  1787  				altLinker = "gold"
  1788  
  1789  				// If gold is not installed, gcc will silently switch
  1790  				// back to ld.bfd. So we parse the version information
  1791  				// and provide a useful error if gold is missing.
  1792  				args = flagExtld[1:]
  1793  				args = append(args, "-fuse-ld=gold", "-Wl,--version")
  1794  				cmd = exec.Command(name, args...)
  1795  				if out, err := cmd.CombinedOutput(); err == nil {
  1796  					if !bytes.Contains(out, []byte("GNU gold")) {
  1797  						log.Fatalf("ARM64 external linker must be ld>=2.36 or gold (issue #15696, 22040), but is not: %s", out)
  1798  					}
  1799  				}
  1800  			}
  1801  		}
  1802  	}
  1803  	if ctxt.Arch.Family == sys.ARM64 && buildcfg.GOOS == "freebsd" {
  1804  		// Switch to ld.bfd on freebsd/arm64.
  1805  		altLinker = "bfd"
  1806  
  1807  		// Provide a useful error if ld.bfd is missing.
  1808  		name, args := flagExtld[0], flagExtld[1:]
  1809  		args = append(args, "-fuse-ld=bfd", "-Wl,--version")
  1810  		cmd := exec.Command(name, args...)
  1811  		if out, err := cmd.CombinedOutput(); err == nil {
  1812  			if !bytes.Contains(out, []byte("GNU ld")) {
  1813  				log.Fatalf("ARM64 external linker must be ld.bfd (issue #35197), please install devel/binutils")
  1814  			}
  1815  		}
  1816  	}
  1817  	if altLinker != "" {
  1818  		argv = append(argv, "-fuse-ld="+altLinker)
  1819  	}
  1820  
  1821  	if ctxt.IsELF && linkerFlagSupported(ctxt.Arch, ctxt.extld(), "", "-Wl,--build-id=0x1234567890abcdef") { // Solaris ld doesn't support --build-id.
  1822  		if len(buildinfo) > 0 {
  1823  			argv = append(argv, fmt.Sprintf("-Wl,--build-id=0x%x", buildinfo))
  1824  		} else if *flagHostBuildid == "none" {
  1825  			argv = append(argv, "-Wl,--build-id=none")
  1826  		}
  1827  	}
  1828  
  1829  	// On Windows, given -o foo, GCC will append ".exe" to produce
  1830  	// "foo.exe".  We have decided that we want to honor the -o
  1831  	// option. To make this work, we append a '.' so that GCC
  1832  	// will decide that the file already has an extension. We
  1833  	// only want to do this when producing a Windows output file
  1834  	// on a Windows host.
  1835  	outopt := *flagOutfile
  1836  	if buildcfg.GOOS == "windows" && runtime.GOOS == "windows" && filepath.Ext(outopt) == "" {
  1837  		outopt += "."
  1838  	}
  1839  	argv = append(argv, "-o")
  1840  	argv = append(argv, outopt)
  1841  
  1842  	if rpath.val != "" {
  1843  		argv = append(argv, fmt.Sprintf("-Wl,-rpath,%s", rpath.val))
  1844  	}
  1845  
  1846  	if *flagInterpreter != "" {
  1847  		if strings.Contains(*flagInterpreter, ",") {
  1848  			Exitf("invalid dynamic linker path %q", *flagInterpreter)
  1849  		}
  1850  		// Many linkers support both -I and the --dynamic-linker flags
  1851  		// to set the ELF interpreter, but lld only supports
  1852  		// --dynamic-linker so prefer that (ld on very old Solaris only
  1853  		// supports -I but that seems less important).
  1854  		argv = append(argv, fmt.Sprintf("-Wl,--dynamic-linker=%s", *flagInterpreter))
  1855  	}
  1856  
  1857  	// Force global symbols to be exported for dlopen, etc.
  1858  	switch {
  1859  	case ctxt.IsELF:
  1860  		if ctxt.DynlinkingGo() || ctxt.BuildMode == BuildModeCShared || !linkerFlagSupported(ctxt.Arch, ctxt.extld(), altLinker, "-Wl,--export-dynamic-symbol=main") {
  1861  			argv = append(argv, "-rdynamic")
  1862  		} else {
  1863  			var exports []string
  1864  			ctxt.loader.ForAllCgoExportDynamic(func(s loader.Sym) {
  1865  				extname := ctxt.loader.SymExtname(s)
  1866  				if strings.Contains(extname, ",") {
  1867  					Exitf("invalid exported symbol name %q", extname)
  1868  				}
  1869  				exports = append(exports, "-Wl,--export-dynamic-symbol="+extname)
  1870  			})
  1871  			sort.Strings(exports)
  1872  			argv = append(argv, exports...)
  1873  		}
  1874  	case ctxt.IsAIX():
  1875  		fileName := xcoffCreateExportFile(ctxt)
  1876  		argv = append(argv, "-Wl,-bE:"+fileName)
  1877  	case ctxt.IsWindows() && !slices.Contains(flagExtldflags, wlPrefix+"export-all-symbols"):
  1878  		fileName := peCreateExportFile(ctxt, filepath.Base(outopt))
  1879  		prefix := ""
  1880  		if isMSVC {
  1881  			prefix = "-Wl,-def:"
  1882  		}
  1883  		argv = append(argv, prefix+fileName)
  1884  	}
  1885  
  1886  	const unusedArguments = "-Qunused-arguments"
  1887  	if linkerFlagSupported(ctxt.Arch, ctxt.extld(), altLinker, unusedArguments) {
  1888  		argv = append(argv, unusedArguments)
  1889  	}
  1890  
  1891  	if ctxt.IsWindows() {
  1892  		// Suppress generation of the PE file header timestamp,
  1893  		// so as to avoid spurious build ID differences between
  1894  		// linked binaries that are otherwise identical other than
  1895  		// the date/time they were linked.
  1896  		const noTimeStamp = "-Wl,--no-insert-timestamp"
  1897  		if linkerFlagSupported(ctxt.Arch, ctxt.extld(), altLinker, noTimeStamp) {
  1898  			argv = append(argv, noTimeStamp)
  1899  		}
  1900  	}
  1901  
  1902  	const compressDWARF = "-Wl,--compress-debug-sections=zlib"
  1903  	if ctxt.compressDWARF && linkerFlagSupported(ctxt.Arch, ctxt.extld(), altLinker, compressDWARF) {
  1904  		argv = append(argv, compressDWARF)
  1905  	}
  1906  
  1907  	hostObjCopyPaths := ctxt.hostobjCopy()
  1908  	cleanTimeStamps(hostObjCopyPaths)
  1909  	godotopath := filepath.Join(*flagTmpdir, "go.o")
  1910  	cleanTimeStamps([]string{godotopath})
  1911  
  1912  	argv = append(argv, godotopath)
  1913  	argv = append(argv, hostObjCopyPaths...)
  1914  	if ctxt.HeadType == objabi.Haix {
  1915  		// We want to have C files after Go files to remove
  1916  		// trampolines csects made by ld.
  1917  		argv = append(argv, "-nostartfiles")
  1918  
  1919  		extld := ctxt.extld()
  1920  		name, args := extld[0], extld[1:]
  1921  		// Get starting files.
  1922  		getPathFile := func(file string) string {
  1923  			args := append(args, "-maix64", "--print-file-name="+file)
  1924  			out, err := exec.Command(name, args...).CombinedOutput()
  1925  			if err != nil {
  1926  				if buildcfg.Experiment.RuntimeCgoPurego && iscgo && len(hostobj) == 0 {
  1927  					Exitf("cgo on %s/%s requires an external linker (C toolchain); set CC or use CGO_ENABLED=0: running %s failed: %v\n%s", buildcfg.GOOS, buildcfg.GOARCH, name, err, out)
  1928  				}
  1929  				log.Fatalf("running %s failed: %v\n%s", extld, err, out)
  1930  			}
  1931  			return strings.Trim(string(out), "\n")
  1932  		}
  1933  		argv = append(argv, getPathFile("crt0_64.o"))
  1934  		// Since GCC version 11, the 64-bit version of GCC starting files
  1935  		// are now suffixed by "_64". Even under "-maix64" multilib directory
  1936  		// "crtcxa.o" is 32-bit.
  1937  		crtcxa := getPathFile("crtcxa_64.o")
  1938  		if !filepath.IsAbs(crtcxa) {
  1939  			crtcxa = getPathFile("crtcxa.o")
  1940  		}
  1941  		crtdbase := getPathFile("crtdbase_64.o")
  1942  		if !filepath.IsAbs(crtdbase) {
  1943  			crtdbase = getPathFile("crtdbase.o")
  1944  		}
  1945  		argv = append(argv, crtcxa)
  1946  		argv = append(argv, crtdbase)
  1947  	}
  1948  
  1949  	if ctxt.linkShared {
  1950  		seenDirs := make(map[string]bool)
  1951  		seenLibs := make(map[string]bool)
  1952  		addshlib := func(path string) {
  1953  			dir, base := filepath.Split(path)
  1954  			if !seenDirs[dir] {
  1955  				argv = append(argv, "-L"+dir)
  1956  				if !rpath.set {
  1957  					argv = append(argv, "-Wl,-rpath="+dir)
  1958  				}
  1959  				seenDirs[dir] = true
  1960  			}
  1961  			base = strings.TrimSuffix(base, ".so")
  1962  			base = strings.TrimPrefix(base, "lib")
  1963  			if !seenLibs[base] {
  1964  				argv = append(argv, "-l"+base)
  1965  				seenLibs[base] = true
  1966  			}
  1967  		}
  1968  		for _, shlib := range ctxt.Shlibs {
  1969  			addshlib(shlib.Path)
  1970  			for _, dep := range shlib.Deps {
  1971  				if dep == "" {
  1972  					continue
  1973  				}
  1974  				libpath := findshlib(ctxt, dep)
  1975  				if libpath != "" {
  1976  					addshlib(libpath)
  1977  				}
  1978  			}
  1979  		}
  1980  	}
  1981  
  1982  	// clang, unlike GCC, passes -rdynamic to the linker
  1983  	// even when linking with -static, causing a linker
  1984  	// error when using GNU ld. So take out -rdynamic if
  1985  	// we added it. We do it in this order, rather than
  1986  	// only adding -rdynamic later, so that -extldflags
  1987  	// can override -rdynamic without using -static.
  1988  	// Similarly for -Wl,--dynamic-linker.
  1989  	checkStatic := func(arg string) {
  1990  		if ctxt.IsELF && arg == "-static" {
  1991  			for i := range argv {
  1992  				if argv[i] == "-rdynamic" || strings.HasPrefix(argv[i], "-Wl,--dynamic-linker=") {
  1993  					argv[i] = "-static"
  1994  				}
  1995  			}
  1996  		}
  1997  	}
  1998  
  1999  	for _, p := range ldflag {
  2000  		argv = append(argv, p)
  2001  		checkStatic(p)
  2002  	}
  2003  
  2004  	// When building a program with the default -buildmode=exe the
  2005  	// gc compiler generates code requires DT_TEXTREL in a
  2006  	// position independent executable (PIE). On systems where the
  2007  	// toolchain creates PIEs by default, and where DT_TEXTREL
  2008  	// does not work, the resulting programs will not run. See
  2009  	// issue #17847. To avoid this problem pass -no-pie to the
  2010  	// toolchain if it is supported.
  2011  	if ctxt.BuildMode == BuildModeExe && !ctxt.linkShared && !(ctxt.IsDarwin() && ctxt.IsARM64()) {
  2012  		// GCC uses -no-pie, clang uses -nopie.
  2013  		for _, nopie := range []string{"-no-pie", "-nopie"} {
  2014  			if linkerFlagSupported(ctxt.Arch, ctxt.extld(), altLinker, nopie) {
  2015  				argv = append(argv, nopie)
  2016  				break
  2017  			}
  2018  		}
  2019  	}
  2020  
  2021  	for _, p := range flagExtldflags {
  2022  		argv = append(argv, p)
  2023  		checkStatic(p)
  2024  	}
  2025  	if ctxt.HeadType == objabi.Hwindows {
  2026  		// use gcc linker script to work around gcc bug
  2027  		// (see https://golang.org/issue/20183 for details).
  2028  		if !isLLD {
  2029  			p := writeGDBLinkerScript()
  2030  			argv = append(argv, "-Wl,-T,"+p)
  2031  		}
  2032  		if *flagRace {
  2033  			// Apparently --print-file-name doesn't work with -msvc clang.
  2034  			// (The library name is synchronization.lib, but even with that
  2035  			// name it still doesn't print the full path.) Assume it always
  2036  			// it.
  2037  			if isMSVC || ctxt.findLibPath("libsynchronization.a") != "libsynchronization.a" {
  2038  				argv = append(argv, "-lsynchronization")
  2039  			}
  2040  		}
  2041  		if !isMSVC {
  2042  			// libmingw32 and libmingwex have some inter-dependencies,
  2043  			// so must use linker groups.
  2044  			argv = append(argv, "-Wl,--start-group", "-lmingwex", "-lmingw32", "-Wl,--end-group")
  2045  		}
  2046  		argv = append(argv, peimporteddlls()...)
  2047  	}
  2048  
  2049  	argv = ctxt.passLongArgsInResponseFile(argv, altLinker)
  2050  
  2051  	if ctxt.Debugvlog != 0 {
  2052  		ctxt.Logf("host link:")
  2053  		for _, v := range argv {
  2054  			ctxt.Logf(" %q", v)
  2055  		}
  2056  		ctxt.Logf("\n")
  2057  	}
  2058  
  2059  	cmd := exec.Command(argv[0], argv[1:]...)
  2060  	out, err := cmd.CombinedOutput()
  2061  	if err != nil {
  2062  		if buildcfg.Experiment.RuntimeCgoPurego && iscgo && len(hostobj) == 0 && (platform.MustLinkExternalWithoutHostObj(buildcfg.GOOS, buildcfg.GOARCH) || buildcfg.GOOS == "ios") {
  2063  			Exitf("cgo on %s/%s requires an external linker (C toolchain); set CC or use CGO_ENABLED=0: running %s failed: %v\n%s\n%s", buildcfg.GOOS, buildcfg.GOARCH, argv[0], err, cmd, out)
  2064  		}
  2065  		Exitf("running %s failed: %v\n%s\n%s", argv[0], err, cmd, out)
  2066  	}
  2067  
  2068  	// Filter out useless linker warnings caused by bugs outside Go.
  2069  	// See also cmd/go/internal/work/exec.go's gccld method.
  2070  	var save [][]byte
  2071  	var skipLines int
  2072  	for _, line := range bytes.SplitAfter(out, []byte("\n")) {
  2073  		// golang.org/issue/26073 - Apple Xcode bug
  2074  		if bytes.Contains(line, []byte("ld: warning: text-based stub file")) {
  2075  			continue
  2076  		}
  2077  
  2078  		if skipLines > 0 {
  2079  			skipLines--
  2080  			continue
  2081  		}
  2082  
  2083  		// Remove TOC overflow warning on AIX.
  2084  		if bytes.Contains(line, []byte("ld: 0711-783")) {
  2085  			skipLines = 2
  2086  			continue
  2087  		}
  2088  
  2089  		save = append(save, line)
  2090  	}
  2091  	out = bytes.Join(save, nil)
  2092  
  2093  	if len(out) > 0 {
  2094  		// always print external output even if the command is successful, so that we don't
  2095  		// swallow linker warnings (see https://golang.org/issue/17935).
  2096  		if ctxt.IsDarwin() && ctxt.IsAMD64() {
  2097  			const noPieWarning = "ld: warning: -no_pie is deprecated when targeting new OS versions\n"
  2098  			if i := bytes.Index(out, []byte(noPieWarning)); i >= 0 {
  2099  				// swallow -no_pie deprecation warning, issue 54482
  2100  				out = append(out[:i], out[i+len(noPieWarning):]...)
  2101  			}
  2102  		}
  2103  		if ctxt.IsDarwin() {
  2104  			const bindAtLoadWarning = "ld: warning: -bind_at_load is deprecated on macOS\n"
  2105  			if i := bytes.Index(out, []byte(bindAtLoadWarning)); i >= 0 {
  2106  				// -bind_at_load is deprecated with ld-prime, but needed for
  2107  				// correctness with older versions of ld64. Swallow the warning.
  2108  				// TODO: maybe pass -bind_at_load conditionally based on C
  2109  				// linker version.
  2110  				out = append(out[:i], out[i+len(bindAtLoadWarning):]...)
  2111  			}
  2112  		}
  2113  		ctxt.Logf("%s", out)
  2114  	}
  2115  
  2116  	// Helper for updating a Macho binary in some way (shared between
  2117  	// dwarf combining and UUID update).
  2118  	updateMachoOutFile := func(op string, updateFunc machoUpdateFunc) {
  2119  		// For os.Rename to work reliably, must be in same directory as outfile.
  2120  		rewrittenOutput := *flagOutfile + "~"
  2121  		exef, err := os.Open(*flagOutfile)
  2122  		if err != nil {
  2123  			Exitf("%s: %s failed: %v", os.Args[0], op, err)
  2124  		}
  2125  		defer exef.Close()
  2126  		exem, err := macho.NewFile(exef)
  2127  		if err != nil {
  2128  			Exitf("%s: parsing Mach-O header failed: %v", os.Args[0], err)
  2129  		}
  2130  		if err := updateFunc(ctxt, exef, exem, rewrittenOutput); err != nil {
  2131  			Exitf("%s: %s failed: %v", os.Args[0], op, err)
  2132  		}
  2133  		os.Remove(*flagOutfile)
  2134  		if err := os.Rename(rewrittenOutput, *flagOutfile); err != nil {
  2135  			Exitf("%s: %v", os.Args[0], err)
  2136  		}
  2137  	}
  2138  
  2139  	if ctxt.IsDarwin() && !combineDwarf && len(buildinfo) > 0 {
  2140  		// If we're not combining DWARF, update UUID now.
  2141  		// Otherwise the code below takes care of it when combining DWARF.
  2142  		updateMachoOutFile("rewriting uuid",
  2143  			func(ctxt *Link, exef *os.File, exem *macho.File, outexe string) error {
  2144  				return machoRewriteUuid(ctxt, exef, exem, outexe)
  2145  			})
  2146  	}
  2147  	if machoDwarf {
  2148  		// Find "dsymutils" and "strip" tools using CC --print-prog-name.
  2149  		dsymutilCmd := ctxt.findExtLinkTool("dsymutil")
  2150  		stripCmd := ctxt.findExtLinkTool("strip")
  2151  
  2152  		dsym := filepath.Join(*flagTmpdir, "go.dwarf")
  2153  		if *FlagSplitDWARF {
  2154  			dsym = filepath.Join(*flagOutfile+".dSYM", "Contents", "Resources", "DWARF", filepath.Base(*flagOutfile))
  2155  			if err := os.MkdirAll(filepath.Dir(dsym), 0777); err != nil {
  2156  				Exitf("fail to create dSYM dir: %v", err)
  2157  			}
  2158  		}
  2159  		cmd := exec.Command(dsymutilCmd, "-f", *flagOutfile, "-o", dsym)
  2160  		// dsymutil may not clean up its temp directory at exit.
  2161  		// Set DSYMUTIL_REPRODUCER_PATH to work around. see issue 59026.
  2162  		// dsymutil (Apple LLVM version 16.0.0) deletes the directory
  2163  		// even if it is not empty. We still need our tmpdir, so give a
  2164  		// subdirectory to dsymutil.
  2165  		dsymDir := filepath.Join(*flagTmpdir, "dsymutil")
  2166  		err := os.MkdirAll(dsymDir, 0777)
  2167  		if err != nil {
  2168  			Exitf("fail to create temp dir: %v", err)
  2169  		}
  2170  		cmd.Env = append(os.Environ(), "DSYMUTIL_REPRODUCER_PATH="+dsymDir)
  2171  		if ctxt.Debugvlog != 0 {
  2172  			ctxt.Logf("host link dsymutil:")
  2173  			for _, v := range cmd.Args {
  2174  				ctxt.Logf(" %q", v)
  2175  			}
  2176  			ctxt.Logf("\n")
  2177  		}
  2178  		if out, err := cmd.CombinedOutput(); err != nil {
  2179  			Exitf("%s: running dsymutil failed: %v\n%s\n%s", os.Args[0], err, cmd, out)
  2180  		}
  2181  		// Remove STAB (symbolic debugging) symbols after we are done with them (by dsymutil).
  2182  		// They contain temporary file paths and make the build not reproducible.
  2183  		var stripArgs = []string{"-S"}
  2184  		if debug_s {
  2185  			// We are generating a binary with symbol table suppressed.
  2186  			// Suppress local symbols. We need to keep dynamically exported
  2187  			// and referenced symbols so the dynamic linker can resolve them.
  2188  			stripArgs = append(stripArgs, "-x")
  2189  		}
  2190  		stripArgs = append(stripArgs, *flagOutfile)
  2191  		if ctxt.Debugvlog != 0 {
  2192  			ctxt.Logf("host link strip: %q", stripCmd)
  2193  			for _, v := range stripArgs {
  2194  				ctxt.Logf(" %q", v)
  2195  			}
  2196  			ctxt.Logf("\n")
  2197  		}
  2198  		cmd = exec.Command(stripCmd, stripArgs...)
  2199  		if out, err := cmd.CombinedOutput(); err != nil {
  2200  			Exitf("%s: running strip failed: %v\n%s\n%s", os.Args[0], err, cmd, out)
  2201  		}
  2202  		if combineDwarf {
  2203  			// Skip combining if `dsymutil` didn't generate a file. See #11994.
  2204  			if _, err := os.Stat(dsym); err == nil {
  2205  				updateMachoOutFile("combining dwarf",
  2206  					func(ctxt *Link, exef *os.File, exem *macho.File, outexe string) error {
  2207  						return machoCombineDwarf(ctxt, exef, exem, dsym, outexe)
  2208  					})
  2209  			} else if len(buildinfo) > 0 {
  2210  				updateMachoOutFile("rewriting uuid",
  2211  					func(ctxt *Link, exef *os.File, exem *macho.File, outexe string) error {
  2212  						return machoRewriteUuid(ctxt, exef, exem, outexe)
  2213  					})
  2214  			}
  2215  		} else {
  2216  			// Remove dSYM directory if dsymutil didn't generate a file. See #11994.
  2217  			if _, err := os.Stat(dsym); err != nil {
  2218  				os.RemoveAll(*flagOutfile + ".dSYM")
  2219  			}
  2220  		}
  2221  	}
  2222  	hostlinkfips(ctxt, *flagOutfile, *flagFipso)
  2223  	if ctxt.NeedCodeSign() {
  2224  		err := machoCodeSign(ctxt, *flagOutfile)
  2225  		if err != nil {
  2226  			Exitf("%s: code signing failed: %v", os.Args[0], err)
  2227  		}
  2228  	}
  2229  }
  2230  
  2231  // passLongArgsInResponseFile writes the arguments into a file if they
  2232  // are very long.
  2233  func (ctxt *Link) passLongArgsInResponseFile(argv []string, altLinker string) []string {
  2234  	c := 0
  2235  	for _, arg := range argv {
  2236  		c += len(arg)
  2237  	}
  2238  
  2239  	if c < sys.ExecArgLengthLimit {
  2240  		return argv
  2241  	}
  2242  
  2243  	// Only use response files if they are supported.
  2244  	response := filepath.Join(*flagTmpdir, "response")
  2245  	if err := os.WriteFile(response, nil, 0644); err != nil {
  2246  		log.Fatalf("failed while testing response file: %v", err)
  2247  	}
  2248  	if !linkerFlagSupported(ctxt.Arch, ctxt.extld(), altLinker, "@"+response) {
  2249  		if ctxt.Debugvlog != 0 {
  2250  			ctxt.Logf("not using response file because linker does not support one")
  2251  		}
  2252  		return argv
  2253  	}
  2254  
  2255  	// argv starts with the external linker command, which may carry
  2256  	// arguments of its own (for example CC="ccache gcc"). Keep those on the
  2257  	// command line: they are consumed by the program named by argv[0], which
  2258  	// need not know how to expand a response file. See issue 81164.
  2259  	nextld := len(ctxt.extld())
  2260  
  2261  	var buf bytes.Buffer
  2262  	for _, arg := range argv[nextld:] {
  2263  		// The external linker response file supports quoted strings.
  2264  		fmt.Fprintf(&buf, "%q\n", arg)
  2265  	}
  2266  	if err := os.WriteFile(response, buf.Bytes(), 0644); err != nil {
  2267  		log.Fatalf("failed while writing response file: %v", err)
  2268  	}
  2269  	if ctxt.Debugvlog != 0 {
  2270  		ctxt.Logf("response file %s contents:\n%s", response, buf.Bytes())
  2271  	}
  2272  	return append(slices.Clone(argv[:nextld]), "@"+response)
  2273  }
  2274  
  2275  var createTrivialCOnce sync.Once
  2276  
  2277  // linkerFlagSupported reports whether the external linker command linker
  2278  // (an argv slice, as returned by [Link.extld]) accepts the flag flag.
  2279  func linkerFlagSupported(arch *sys.Arch, linker []string, altLinker, flag string) bool {
  2280  	if restrictedBuild() {
  2281  		Exitf("external linker invocation is not allowed when GORESTRICTEDBUILD=1")
  2282  	}
  2283  	createTrivialCOnce.Do(func() {
  2284  		src := filepath.Join(*flagTmpdir, "trivial.c")
  2285  		if err := os.WriteFile(src, []byte("int main() { return 0; }"), 0666); err != nil {
  2286  			Errorf("WriteFile trivial.c failed: %v", err)
  2287  		}
  2288  	})
  2289  
  2290  	// The linker command may carry arguments of its own (for example
  2291  	// CC="ccache gcc"); they must be passed along, or the probe may fail
  2292  	// for reasons that have nothing to do with flag. See issue 81164.
  2293  	flags := slices.Concat(linker[1:], hostlinkArchArgs(arch))
  2294  
  2295  	moreFlags := trimLinkerArgv(append(ldflag, flagExtldflags...))
  2296  	flags = append(flags, moreFlags...)
  2297  
  2298  	if altLinker != "" {
  2299  		flags = append(flags, "-fuse-ld="+altLinker)
  2300  	}
  2301  	trivialPath := filepath.Join(*flagTmpdir, "trivial.c")
  2302  	outPath := filepath.Join(*flagTmpdir, "a.out")
  2303  	flags = append(flags, "-o", outPath, flag, trivialPath)
  2304  
  2305  	cmd := exec.Command(linker[0], flags...)
  2306  	cmd.Env = append([]string{"LC_ALL=C"}, os.Environ()...)
  2307  	out, err := cmd.CombinedOutput()
  2308  	// GCC says "unrecognized command line option ‘-no-pie’"
  2309  	// clang says "unknown argument: '-no-pie'"
  2310  	return err == nil && !bytes.Contains(out, []byte("unrecognized")) && !bytes.Contains(out, []byte("unknown"))
  2311  }
  2312  
  2313  // peHasLoadConfigDirectorySupport checks whether the external linker
  2314  // populates the PE Load Configuration Directory data directory entry
  2315  // when it encounters a _load_config_used symbol.
  2316  //
  2317  // GNU ld gained this support in binutils 2.45. MSVC link.exe and
  2318  // LLVM lld-link have always supported it.
  2319  func peHasLoadConfigDirectorySupport(arch *sys.Arch, linker []string) bool {
  2320  	if restrictedBuild() {
  2321  		return false
  2322  	}
  2323  	src := filepath.Join(*flagTmpdir, "loadcfg_test.c")
  2324  	if err := os.WriteFile(src, []byte(`
  2325  #ifdef _WIN64
  2326  typedef unsigned long long uintptr;
  2327  #else
  2328  typedef unsigned long uintptr;
  2329  #endif
  2330  const uintptr _load_config_used[2] = { sizeof(_load_config_used), 0 };
  2331  int main() { return 0; }
  2332  `), 0666); err != nil {
  2333  		return false
  2334  	}
  2335  
  2336  	outPath := filepath.Join(*flagTmpdir, "loadcfg_test.exe")
  2337  	flags := slices.Concat(linker[1:], hostlinkArchArgs(arch))
  2338  	flags = append(flags, "-o", outPath, src)
  2339  	cmd := exec.Command(linker[0], flags...)
  2340  	cmd.Env = append([]string{"LC_ALL=C"}, os.Environ()...)
  2341  	if err := cmd.Run(); err != nil {
  2342  		return false
  2343  	}
  2344  
  2345  	f, err := pe.Open(outPath)
  2346  	if err != nil {
  2347  		return false
  2348  	}
  2349  	defer f.Close()
  2350  
  2351  	switch oh := f.OptionalHeader.(type) {
  2352  	case *pe.OptionalHeader64:
  2353  		if int(pe.IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG) < len(oh.DataDirectory) {
  2354  			return oh.DataDirectory[pe.IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress != 0
  2355  		}
  2356  	case *pe.OptionalHeader32:
  2357  		if int(pe.IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG) < len(oh.DataDirectory) {
  2358  			return oh.DataDirectory[pe.IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress != 0
  2359  		}
  2360  	}
  2361  	return false
  2362  }
  2363  
  2364  // trimLinkerArgv returns a new copy of argv that does not include flags
  2365  // that are not relevant for testing whether some linker option works.
  2366  func trimLinkerArgv(argv []string) []string {
  2367  	flagsWithNextArgSkip := []string{
  2368  		"-F",
  2369  		"-l",
  2370  		"-framework",
  2371  		"-Wl,-framework",
  2372  		"-Wl,-rpath",
  2373  		"-Wl,-undefined",
  2374  	}
  2375  	flagsWithNextArgKeep := []string{
  2376  		"-B",
  2377  		"-L",
  2378  		"-arch",
  2379  		"-isysroot",
  2380  		"--sysroot",
  2381  		"-target",
  2382  		"--target",
  2383  		"-resource-dir",
  2384  		"-rtlib",
  2385  		"--rtlib",
  2386  		"-stdlib",
  2387  		"--stdlib",
  2388  		"-unwindlib",
  2389  		"--unwindlib",
  2390  	}
  2391  	prefixesToKeep := []string{
  2392  		"-B",
  2393  		"-L",
  2394  		"-f",
  2395  		"-m",
  2396  		"-p",
  2397  		"-Wl,",
  2398  		"-arch",
  2399  		"-isysroot",
  2400  		"--sysroot",
  2401  		"-target",
  2402  		"--target",
  2403  		"-resource-dir",
  2404  		"-rtlib",
  2405  		"--rtlib",
  2406  		"-stdlib",
  2407  		"--stdlib",
  2408  		"-unwindlib",
  2409  		"--unwindlib",
  2410  		"-nostdlib++",
  2411  		"-nostdlib",
  2412  		"-nodefaultlibs",
  2413  		"-nostartfiles",
  2414  		"-nostdinc++",
  2415  		"-nostdinc",
  2416  		"-nobuiltininc",
  2417  	}
  2418  
  2419  	var flags []string
  2420  	keep := false
  2421  	skip := false
  2422  	for _, f := range argv {
  2423  		if keep {
  2424  			flags = append(flags, f)
  2425  			keep = false
  2426  		} else if skip {
  2427  			skip = false
  2428  		} else if f == "" || f[0] != '-' {
  2429  		} else if slices.Contains(flagsWithNextArgSkip, f) {
  2430  			skip = true
  2431  		} else if slices.Contains(flagsWithNextArgKeep, f) {
  2432  			flags = append(flags, f)
  2433  			keep = true
  2434  		} else {
  2435  			for _, p := range prefixesToKeep {
  2436  				if strings.HasPrefix(f, p) {
  2437  					flags = append(flags, f)
  2438  					break
  2439  				}
  2440  			}
  2441  		}
  2442  	}
  2443  	return flags
  2444  }
  2445  
  2446  // hostlinkArchArgs returns arguments to pass to the external linker
  2447  // based on the architecture.
  2448  func hostlinkArchArgs(arch *sys.Arch) []string {
  2449  	switch arch.Family {
  2450  	case sys.I386:
  2451  		return []string{"-m32"}
  2452  	case sys.AMD64:
  2453  		if buildcfg.GOOS == "darwin" {
  2454  			return []string{"-arch", "x86_64", "-m64"}
  2455  		}
  2456  		return []string{"-m64"}
  2457  	case sys.S390X:
  2458  		return []string{"-m64"}
  2459  	case sys.ARM:
  2460  		return []string{"-marm"}
  2461  	case sys.ARM64:
  2462  		if buildcfg.GOOS == "darwin" {
  2463  			return []string{"-arch", "arm64"}
  2464  		}
  2465  	case sys.Loong64:
  2466  		return []string{"-mabi=lp64d"}
  2467  	case sys.MIPS64:
  2468  		return []string{"-mabi=64"}
  2469  	case sys.MIPS:
  2470  		return []string{"-mabi=32"}
  2471  	case sys.PPC64:
  2472  		if buildcfg.GOOS == "aix" {
  2473  			return []string{"-maix64"}
  2474  		} else {
  2475  			return []string{"-m64"}
  2476  		}
  2477  
  2478  	}
  2479  	return nil
  2480  }
  2481  
  2482  var wantHdr = objabi.HeaderString()
  2483  
  2484  // ldobj loads an input object. If it is a host object (an object
  2485  // compiled by a non-Go compiler) it returns the Hostobj pointer. If
  2486  // it is a Go object, it returns nil.
  2487  func ldobj(ctxt *Link, f *bio.Reader, lib *sym.Library, length int64, pn string, file string) *Hostobj {
  2488  	pkg := objabi.PathToPrefix(lib.Pkg)
  2489  
  2490  	eof := f.Offset() + length
  2491  	start := f.Offset()
  2492  	c1 := bgetc(f)
  2493  	c2 := bgetc(f)
  2494  	c3 := bgetc(f)
  2495  	c4 := bgetc(f)
  2496  	f.MustSeek(start, 0)
  2497  
  2498  	unit := &sym.CompilationUnit{Lib: lib}
  2499  	lib.Units = append(lib.Units, unit)
  2500  
  2501  	magic := uint32(c1)<<24 | uint32(c2)<<16 | uint32(c3)<<8 | uint32(c4)
  2502  	if magic == 0x7f454c46 { // \x7F E L F
  2503  		ldelf := func(ctxt *Link, f *bio.Reader, pkg string, length int64, pn string) {
  2504  			textp, flags, err := loadelf.Load(ctxt.loader, ctxt.Arch, ctxt.IncVersion(), f, pkg, length, pn, ehdr.Flags)
  2505  			if err != nil {
  2506  				Errorf("%v", err)
  2507  				return
  2508  			}
  2509  			ehdr.Flags = flags
  2510  			ctxt.Textp = append(ctxt.Textp, textp...)
  2511  		}
  2512  		return ldhostobj(ldelf, ctxt.HeadType, f, pkg, length, pn, file)
  2513  	}
  2514  
  2515  	if magic&^1 == 0xfeedface || magic&^0x01000000 == 0xcefaedfe {
  2516  		ldmacho := func(ctxt *Link, f *bio.Reader, pkg string, length int64, pn string) {
  2517  			textp, err := loadmacho.Load(ctxt.loader, ctxt.Arch, ctxt.IncVersion(), f, pkg, length, pn)
  2518  			if err != nil {
  2519  				Errorf("%v", err)
  2520  				return
  2521  			}
  2522  			ctxt.Textp = append(ctxt.Textp, textp...)
  2523  		}
  2524  		return ldhostobj(ldmacho, ctxt.HeadType, f, pkg, length, pn, file)
  2525  	}
  2526  
  2527  	switch c1<<8 | c2 {
  2528  	case 0x4c01, // 386
  2529  		0x6486, // amd64
  2530  		0xc401, // arm
  2531  		0x64aa: // arm64
  2532  		ldpe := func(ctxt *Link, f *bio.Reader, pkg string, length int64, pn string) {
  2533  			ls, err := loadpe.Load(ctxt.loader, ctxt.Arch, ctxt.IncVersion(), f, pkg, length, pn)
  2534  			if err != nil {
  2535  				Errorf("%v", err)
  2536  				return
  2537  			}
  2538  			if len(ls.Resources) != 0 {
  2539  				setpersrc(ctxt, ls.Resources)
  2540  			}
  2541  			sehp.pdata = append(sehp.pdata, ls.PData...)
  2542  			if ls.XData != 0 {
  2543  				sehp.xdata = append(sehp.xdata, ls.XData)
  2544  			}
  2545  			ctxt.Textp = append(ctxt.Textp, ls.Textp...)
  2546  		}
  2547  		return ldhostobj(ldpe, ctxt.HeadType, f, pkg, length, pn, file)
  2548  	}
  2549  
  2550  	if c1 == 0x01 && (c2 == 0xD7 || c2 == 0xF7) {
  2551  		ldxcoff := func(ctxt *Link, f *bio.Reader, pkg string, length int64, pn string) {
  2552  			textp, err := loadxcoff.Load(ctxt.loader, ctxt.Arch, ctxt.IncVersion(), f, pkg, length, pn)
  2553  			if err != nil {
  2554  				Errorf("%v", err)
  2555  				return
  2556  			}
  2557  			ctxt.Textp = append(ctxt.Textp, textp...)
  2558  		}
  2559  		return ldhostobj(ldxcoff, ctxt.HeadType, f, pkg, length, pn, file)
  2560  	}
  2561  
  2562  	// .syso files are copied directly into package archives without being
  2563  	// compiled. Reject .syso files that do not match a recognized host
  2564  	// object format above so they cannot be parsed below as Go object files
  2565  	// (which could inject untrusted cgo directives) or fall through to
  2566  	// unknownObjFormat (which would force external linking).
  2567  	if strings.HasSuffix(file, ".syso") || strings.HasSuffix(pn, ".syso") || strings.HasSuffix(pn, ".syso)") {
  2568  		Errorf("%s: unsupported object format in .syso file", pn)
  2569  		return nil
  2570  	}
  2571  
  2572  	if c1 != 'g' || c2 != 'o' || c3 != ' ' || c4 != 'o' {
  2573  		// An unrecognized object is just passed to the external linker.
  2574  		// If we try to read symbols from this object, we will
  2575  		// report an error at that time.
  2576  		unknownObjFormat = true
  2577  		return ldhostobj(nil, ctxt.HeadType, f, pkg, length, pn, file)
  2578  	}
  2579  
  2580  	/* check the header */
  2581  	line, err := f.ReadString('\n')
  2582  	if err != nil {
  2583  		Errorf("truncated object file: %s: %v", pn, err)
  2584  		return nil
  2585  	}
  2586  
  2587  	if !strings.HasPrefix(line, "go object ") {
  2588  		if strings.HasSuffix(pn, ".go") {
  2589  			Exitf("%s: uncompiled .go source file", pn)
  2590  			return nil
  2591  		}
  2592  
  2593  		if line == ctxt.Arch.Name {
  2594  			// old header format: just $GOOS
  2595  			Errorf("%s: stale object file", pn)
  2596  			return nil
  2597  		}
  2598  
  2599  		Errorf("%s: not an object file: @%d %q", pn, start, line)
  2600  		return nil
  2601  	}
  2602  
  2603  	// First, check that the basic GOOS, GOARCH, and Version match.
  2604  	if line != wantHdr && !*flagF {
  2605  		Errorf("%s: linked object header mismatch:\nhave %q\nwant %q\n", pn, line, wantHdr)
  2606  	}
  2607  
  2608  	// Skip over exports and other info -- ends with \n!\n.
  2609  	//
  2610  	// Note: It's possible for "\n!\n" to appear within the binary
  2611  	// package export data format. To avoid truncating the package
  2612  	// definition prematurely (issue 21703), we keep track of
  2613  	// how many "$$" delimiters we've seen.
  2614  
  2615  	import0 := f.Offset()
  2616  
  2617  	c1 = '\n' // the last line ended in \n
  2618  	c2 = bgetc(f)
  2619  	c3 = bgetc(f)
  2620  	markers := 0
  2621  	for {
  2622  		if c1 == '\n' {
  2623  			if markers%2 == 0 && c2 == '!' && c3 == '\n' {
  2624  				break
  2625  			}
  2626  			if c2 == '$' && c3 == '$' {
  2627  				markers++
  2628  			}
  2629  		}
  2630  
  2631  		c1 = c2
  2632  		c2 = c3
  2633  		c3 = bgetc(f)
  2634  		if c3 == -1 {
  2635  			Errorf("truncated object file: %s", pn)
  2636  			return nil
  2637  		}
  2638  	}
  2639  
  2640  	import1 := f.Offset()
  2641  
  2642  	f.MustSeek(import0, 0)
  2643  	ldpkg(ctxt, f, lib, import1-import0-2, pn) // -2 for !\n
  2644  	f.MustSeek(import1, 0)
  2645  
  2646  	fingerprint := ctxt.loader.Preload(ctxt.IncVersion(), f, lib, unit, eof-f.Offset())
  2647  	if !fingerprint.IsZero() { // Assembly objects don't have fingerprints. Ignore them.
  2648  		// Check fingerprint, to ensure the importing and imported packages
  2649  		// have consistent view of symbol indices.
  2650  		// Normally the go command should ensure this. But in case something
  2651  		// goes wrong, it could lead to obscure bugs like run-time crash.
  2652  		// Check it here to be sure.
  2653  		if lib.Fingerprint.IsZero() { // Not yet imported. Update its fingerprint.
  2654  			lib.Fingerprint = fingerprint
  2655  		}
  2656  		checkFingerprint(lib, fingerprint, lib.Srcref, lib.Fingerprint)
  2657  	}
  2658  
  2659  	addImports(ctxt, lib, pn)
  2660  	return nil
  2661  }
  2662  
  2663  // symbolsAreUnresolved scans through the loader's list of unresolved
  2664  // symbols and checks to see whether any of them match the names of the
  2665  // symbols in 'want'. Return value is a list of bools, with list[K] set
  2666  // to true if there is an unresolved reference to the symbol in want[K].
  2667  func symbolsAreUnresolved(ctxt *Link, want []string) []bool {
  2668  	returnAllUndefs := -1
  2669  	undefs, _ := ctxt.loader.UndefinedRelocTargets(returnAllUndefs)
  2670  	seen := make(map[loader.Sym]struct{})
  2671  	rval := make([]bool, len(want))
  2672  	wantm := make(map[string]int)
  2673  	for k, w := range want {
  2674  		wantm[w] = k
  2675  	}
  2676  	count := 0
  2677  	for _, s := range undefs {
  2678  		if _, ok := seen[s]; ok {
  2679  			continue
  2680  		}
  2681  		seen[s] = struct{}{}
  2682  		if k, ok := wantm[ctxt.loader.SymName(s)]; ok {
  2683  			rval[k] = true
  2684  			count++
  2685  			if count == len(want) {
  2686  				return rval
  2687  			}
  2688  		}
  2689  	}
  2690  	return rval
  2691  }
  2692  
  2693  // hostObject reads a single host object file (compare to "hostArchive").
  2694  // This is used as part of internal linking when we need to pull in
  2695  // files such as "crt?.o".
  2696  func hostObject(ctxt *Link, objname string, path string) {
  2697  	if ctxt.Debugvlog > 1 {
  2698  		ctxt.Logf("hostObject(%s)\n", path)
  2699  	}
  2700  	objlib := sym.Library{
  2701  		Pkg: objname,
  2702  	}
  2703  	f, err := bio.Open(path)
  2704  	if err != nil {
  2705  		Exitf("cannot open host object %q file %s: %v", objname, path, err)
  2706  	}
  2707  	defer f.Close()
  2708  	h := ldobj(ctxt, f, &objlib, 0, path, path)
  2709  	if h.ld == nil {
  2710  		Exitf("unrecognized object file format in %s", path)
  2711  	}
  2712  	h.file = path
  2713  	h.length = f.MustSeek(0, 2)
  2714  	f.MustSeek(h.off, 0)
  2715  	h.ld(ctxt, f, h.pkg, h.length, h.pn)
  2716  	if *flagCaptureHostObjs != "" {
  2717  		captureHostObj(h)
  2718  	}
  2719  }
  2720  
  2721  func checkFingerprint(lib *sym.Library, libfp goobj.FingerprintType, src string, srcfp goobj.FingerprintType) {
  2722  	if libfp != srcfp {
  2723  		Exitf("fingerprint mismatch: %s has %x, import from %s expecting %x", lib, libfp, src, srcfp)
  2724  	}
  2725  }
  2726  
  2727  func readelfsymboldata(ctxt *Link, f *elf.File, sym *elf.Symbol) []byte {
  2728  	data := make([]byte, sym.Size)
  2729  	sect := f.Sections[sym.Section]
  2730  	if sect.Type != elf.SHT_PROGBITS && sect.Type != elf.SHT_NOTE {
  2731  		Errorf("reading %s from non-data section", sym.Name)
  2732  	}
  2733  	n, err := sect.ReadAt(data, int64(sym.Value-sect.Addr))
  2734  	if uint64(n) != sym.Size {
  2735  		Errorf("reading contents of %s: %v", sym.Name, err)
  2736  	}
  2737  	return data
  2738  }
  2739  
  2740  func readwithpad(r io.Reader, sz int32) ([]byte, error) {
  2741  	data := make([]byte, Rnd(int64(sz), 4))
  2742  	_, err := io.ReadFull(r, data)
  2743  	if err != nil {
  2744  		return nil, err
  2745  	}
  2746  	data = data[:sz]
  2747  	return data, nil
  2748  }
  2749  
  2750  func readnote(f *elf.File, name []byte, typ int32) ([]byte, error) {
  2751  	for _, sect := range f.Sections {
  2752  		if sect.Type != elf.SHT_NOTE {
  2753  			continue
  2754  		}
  2755  		r := sect.Open()
  2756  		for {
  2757  			var namesize, descsize, noteType int32
  2758  			err := binary.Read(r, f.ByteOrder, &namesize)
  2759  			if err != nil {
  2760  				if err == io.EOF {
  2761  					break
  2762  				}
  2763  				return nil, fmt.Errorf("read namesize failed: %v", err)
  2764  			}
  2765  			err = binary.Read(r, f.ByteOrder, &descsize)
  2766  			if err != nil {
  2767  				return nil, fmt.Errorf("read descsize failed: %v", err)
  2768  			}
  2769  			err = binary.Read(r, f.ByteOrder, &noteType)
  2770  			if err != nil {
  2771  				return nil, fmt.Errorf("read type failed: %v", err)
  2772  			}
  2773  			noteName, err := readwithpad(r, namesize)
  2774  			if err != nil {
  2775  				return nil, fmt.Errorf("read name failed: %v", err)
  2776  			}
  2777  			desc, err := readwithpad(r, descsize)
  2778  			if err != nil {
  2779  				return nil, fmt.Errorf("read desc failed: %v", err)
  2780  			}
  2781  			if string(name) == string(noteName) && typ == noteType {
  2782  				return desc, nil
  2783  			}
  2784  		}
  2785  	}
  2786  	return nil, nil
  2787  }
  2788  
  2789  func findshlib(ctxt *Link, shlib string) string {
  2790  	if filepath.IsAbs(shlib) {
  2791  		return shlib
  2792  	}
  2793  	for _, libdir := range ctxt.Libdir {
  2794  		libpath := filepath.Join(libdir, shlib)
  2795  		if _, err := os.Stat(libpath); err == nil {
  2796  			return libpath
  2797  		}
  2798  	}
  2799  	Errorf("cannot find shared library: %s", shlib)
  2800  	return ""
  2801  }
  2802  
  2803  func ldshlibsyms(ctxt *Link, shlib string) {
  2804  	var libpath string
  2805  	if filepath.IsAbs(shlib) {
  2806  		libpath = shlib
  2807  		shlib = filepath.Base(shlib)
  2808  	} else {
  2809  		libpath = findshlib(ctxt, shlib)
  2810  		if libpath == "" {
  2811  			return
  2812  		}
  2813  	}
  2814  	for _, processedlib := range ctxt.Shlibs {
  2815  		if processedlib.Path == libpath {
  2816  			return
  2817  		}
  2818  	}
  2819  	if ctxt.Debugvlog > 1 {
  2820  		ctxt.Logf("ldshlibsyms: found library with name %s at %s\n", shlib, libpath)
  2821  	}
  2822  
  2823  	f, err := elf.Open(libpath)
  2824  	if err != nil {
  2825  		Errorf("cannot open shared library: %s", libpath)
  2826  		return
  2827  	}
  2828  	// Keep the file open as decodetypeGcprog needs to read from it.
  2829  	// TODO: fix. Maybe mmap the file.
  2830  	//defer f.Close()
  2831  
  2832  	hash, err := readnote(f, ELF_NOTE_GO_NAME, ELF_NOTE_GOABIHASH_TAG)
  2833  	if err != nil {
  2834  		Errorf("cannot read ABI hash from shared library %s: %v", libpath, err)
  2835  		return
  2836  	}
  2837  
  2838  	depsbytes, err := readnote(f, ELF_NOTE_GO_NAME, ELF_NOTE_GODEPS_TAG)
  2839  	if err != nil {
  2840  		Errorf("cannot read dep list from shared library %s: %v", libpath, err)
  2841  		return
  2842  	}
  2843  	var deps []string
  2844  	for _, dep := range strings.Split(string(depsbytes), "\n") {
  2845  		if dep == "" {
  2846  			continue
  2847  		}
  2848  		if !filepath.IsAbs(dep) {
  2849  			// If the dep can be interpreted as a path relative to the shlib
  2850  			// in which it was found, do that. Otherwise, we will leave it
  2851  			// to be resolved by libdir lookup.
  2852  			abs := filepath.Join(filepath.Dir(libpath), dep)
  2853  			if _, err := os.Stat(abs); err == nil {
  2854  				dep = abs
  2855  			}
  2856  		}
  2857  		deps = append(deps, dep)
  2858  	}
  2859  
  2860  	syms, err := f.DynamicSymbols()
  2861  	if err != nil {
  2862  		Errorf("cannot read symbols from shared library: %s", libpath)
  2863  		return
  2864  	}
  2865  
  2866  	symAddr := map[string]uint64{}
  2867  	for _, elfsym := range syms {
  2868  		if elf.ST_TYPE(elfsym.Info) == elf.STT_NOTYPE || elf.ST_TYPE(elfsym.Info) == elf.STT_SECTION {
  2869  			continue
  2870  		}
  2871  
  2872  		// Symbols whose names start with "type:" are compiler generated,
  2873  		// so make functions with that prefix internal.
  2874  		ver := 0
  2875  		symname := elfsym.Name // (unmangled) symbol name
  2876  		if elf.ST_TYPE(elfsym.Info) == elf.STT_FUNC && strings.HasPrefix(elfsym.Name, "type:") {
  2877  			ver = abiInternalVer
  2878  		} else if buildcfg.Experiment.RegabiWrappers && elf.ST_TYPE(elfsym.Info) == elf.STT_FUNC {
  2879  			// Demangle the ABI name. Keep in sync with symtab.go:mangleABIName.
  2880  			if strings.HasSuffix(elfsym.Name, ".abiinternal") {
  2881  				ver = sym.SymVerABIInternal
  2882  				symname = strings.TrimSuffix(elfsym.Name, ".abiinternal")
  2883  			} else if strings.HasSuffix(elfsym.Name, ".abi0") {
  2884  				ver = 0
  2885  				symname = strings.TrimSuffix(elfsym.Name, ".abi0")
  2886  			}
  2887  		}
  2888  
  2889  		l := ctxt.loader
  2890  		s := l.LookupOrCreateSym(symname, ver)
  2891  
  2892  		// Because loadlib above loads all .a files before loading
  2893  		// any shared libraries, any non-dynimport symbols we find
  2894  		// that duplicate symbols already loaded should be ignored
  2895  		// (the symbols from the .a files "win").
  2896  		if l.SymType(s) != 0 && l.SymType(s) != sym.SDYNIMPORT {
  2897  			continue
  2898  		}
  2899  		su := l.MakeSymbolUpdater(s)
  2900  		su.SetType(sym.SDYNIMPORT)
  2901  		l.SetSymElfType(s, elf.ST_TYPE(elfsym.Info))
  2902  		su.SetSize(int64(elfsym.Size))
  2903  		if elfsym.Section != elf.SHN_UNDEF {
  2904  			// Set .File for the library that actually defines the symbol.
  2905  			l.SetSymPkg(s, libpath)
  2906  
  2907  			// The decodetype_* functions in decodetype.go need access to
  2908  			// the type data.
  2909  			sname := l.SymName(s)
  2910  			if strings.HasPrefix(sname, "type:") && !strings.HasPrefix(sname, "type:.") {
  2911  				su.SetData(readelfsymboldata(ctxt, f, &elfsym))
  2912  			}
  2913  		}
  2914  
  2915  		if symname != elfsym.Name {
  2916  			l.SetSymExtname(s, elfsym.Name)
  2917  		}
  2918  		symAddr[elfsym.Name] = elfsym.Value
  2919  	}
  2920  
  2921  	// Load relocations.
  2922  	// We only really need these for grokking the links between type descriptors
  2923  	// when dynamic linking.
  2924  	relocTarget := map[uint64]string{}
  2925  	addends := false
  2926  	sect := f.SectionByType(elf.SHT_REL)
  2927  	if sect == nil {
  2928  		sect = f.SectionByType(elf.SHT_RELA)
  2929  		if sect == nil {
  2930  			log.Fatalf("can't find SHT_REL or SHT_RELA section of %s", shlib)
  2931  		}
  2932  		addends = true
  2933  	}
  2934  	// TODO: Multiple SHT_RELA/SHT_REL sections?
  2935  	data, err := sect.Data()
  2936  	if err != nil {
  2937  		log.Fatalf("can't read relocation section of %s: %v", shlib, err)
  2938  	}
  2939  	bo := f.ByteOrder
  2940  	for len(data) > 0 {
  2941  		var off, idx uint64
  2942  		var addend int64
  2943  		switch f.Class {
  2944  		case elf.ELFCLASS64:
  2945  			off = bo.Uint64(data)
  2946  			info := bo.Uint64(data[8:])
  2947  			data = data[16:]
  2948  			if addends {
  2949  				addend = int64(bo.Uint64(data))
  2950  				data = data[8:]
  2951  			}
  2952  
  2953  			idx = info >> 32
  2954  			typ := info & 0xffff
  2955  			// buildmode=shared is only supported for amd64,arm64,loong64,s390x,ppc64le.
  2956  			// (List found by looking at the translation of R_ADDR by ../$ARCH/asm.go:elfreloc1)
  2957  			switch typ {
  2958  			case uint64(elf.R_X86_64_64):
  2959  			case uint64(elf.R_AARCH64_ABS64):
  2960  			case uint64(elf.R_LARCH_64):
  2961  			case uint64(elf.R_390_64):
  2962  			case uint64(elf.R_PPC64_ADDR64):
  2963  			default:
  2964  				continue
  2965  			}
  2966  		case elf.ELFCLASS32:
  2967  			off = uint64(bo.Uint32(data))
  2968  			info := bo.Uint32(data[4:])
  2969  			data = data[8:]
  2970  			if addends {
  2971  				addend = int64(int32(bo.Uint32(data)))
  2972  				data = data[4:]
  2973  			}
  2974  
  2975  			idx = uint64(info >> 8)
  2976  			typ := info & 0xff
  2977  			// buildmode=shared is only supported for 386,arm.
  2978  			switch typ {
  2979  			case uint32(elf.R_386_32):
  2980  			case uint32(elf.R_ARM_ABS32):
  2981  			default:
  2982  				continue
  2983  			}
  2984  		default:
  2985  			log.Fatalf("unknown bit size %s", f.Class)
  2986  		}
  2987  		if addend != 0 {
  2988  			continue
  2989  		}
  2990  		relocTarget[off] = syms[idx-1].Name
  2991  	}
  2992  
  2993  	ctxt.Shlibs = append(ctxt.Shlibs, Shlib{Path: libpath, Hash: hash, Deps: deps, File: f, symAddr: symAddr, relocTarget: relocTarget})
  2994  }
  2995  
  2996  func addsection(ldr *loader.Loader, arch *sys.Arch, seg *sym.Segment, name string, rwx int) *sym.Section {
  2997  	sect := ldr.NewSection()
  2998  	sect.Rwx = uint8(rwx)
  2999  	sect.Name = name
  3000  	sect.Seg = seg
  3001  	sect.Align = int32(arch.PtrSize) // everything is at least pointer-aligned
  3002  	seg.Sections = append(seg.Sections, sect)
  3003  	return sect
  3004  }
  3005  
  3006  func usage() {
  3007  	fmt.Fprintf(os.Stderr, "usage: link [options] main.o\n")
  3008  	objabi.Flagprint(os.Stderr)
  3009  	Exit(2)
  3010  }
  3011  
  3012  type SymbolType int8 // TODO: after genasmsym is gone, maybe rename to plan9typeChar or something
  3013  
  3014  const (
  3015  	// see also https://9p.io/magic/man2html/1/nm
  3016  	TextSym      SymbolType = 'T'
  3017  	DataSym      SymbolType = 'D'
  3018  	BSSSym       SymbolType = 'B'
  3019  	UndefinedSym SymbolType = 'U'
  3020  	TLSSym       SymbolType = 't'
  3021  	FrameSym     SymbolType = 'm'
  3022  	ParamSym     SymbolType = 'p'
  3023  	AutoSym      SymbolType = 'a'
  3024  
  3025  	// Deleted auto (not a real sym, just placeholder for type)
  3026  	DeletedAutoSym = 'x'
  3027  )
  3028  
  3029  // defineInternal defines a symbol used internally by the go runtime.
  3030  func (ctxt *Link) defineInternal(p string, t sym.SymKind) loader.Sym {
  3031  	s := ctxt.loader.CreateSymForUpdate(p, 0)
  3032  	s.SetType(t)
  3033  	s.SetSpecial(true)
  3034  	s.SetLocal(true)
  3035  	return s.Sym()
  3036  }
  3037  
  3038  func (ctxt *Link) xdefine(p string, t sym.SymKind, v int64) loader.Sym {
  3039  	s := ctxt.defineInternal(p, t)
  3040  	ctxt.loader.SetSymValue(s, v)
  3041  	return s
  3042  }
  3043  
  3044  func datoff(ldr *loader.Loader, s loader.Sym, addr int64) int64 {
  3045  	if uint64(addr) >= Segdata.Vaddr {
  3046  		return int64(uint64(addr) - Segdata.Vaddr + Segdata.Fileoff)
  3047  	}
  3048  	if uint64(addr) >= Segtext.Vaddr {
  3049  		return int64(uint64(addr) - Segtext.Vaddr + Segtext.Fileoff)
  3050  	}
  3051  	ldr.Errorf(s, "invalid datoff %#x", addr)
  3052  	return 0
  3053  }
  3054  
  3055  func Entryvalue(ctxt *Link) int64 {
  3056  	a := *flagEntrySymbol
  3057  	if a[0] >= '0' && a[0] <= '9' {
  3058  		return atolwhex(a)
  3059  	}
  3060  	ldr := ctxt.loader
  3061  	s := ldr.Lookup(a, 0)
  3062  	if s == 0 {
  3063  		Errorf("missing entry symbol %q", a)
  3064  		return 0
  3065  	}
  3066  	st := ldr.SymType(s)
  3067  	if st == 0 {
  3068  		return *FlagTextAddr
  3069  	}
  3070  	if !ctxt.IsAIX() && !st.IsText() {
  3071  		ldr.Errorf(s, "entry not text")
  3072  	}
  3073  	return ldr.SymValue(s)
  3074  }
  3075  
  3076  func (ctxt *Link) callgraph() {
  3077  	if !*FlagC {
  3078  		return
  3079  	}
  3080  
  3081  	ldr := ctxt.loader
  3082  	for _, s := range ctxt.Textp {
  3083  		relocs := ldr.Relocs(s)
  3084  		for i := 0; i < relocs.Count(); i++ {
  3085  			r := relocs.At(i)
  3086  			rs := r.Sym()
  3087  			if rs == 0 {
  3088  				continue
  3089  			}
  3090  			if r.Type().IsDirectCall() && ldr.SymType(rs).IsText() {
  3091  				ctxt.Logf("%s calls %s\n", ldr.SymName(s), ldr.SymName(rs))
  3092  			}
  3093  		}
  3094  	}
  3095  }
  3096  
  3097  func Rnd(v int64, r int64) int64 {
  3098  	if r <= 0 {
  3099  		return v
  3100  	}
  3101  	v += r - 1
  3102  	c := v % r
  3103  	if c < 0 {
  3104  		c += r
  3105  	}
  3106  	v -= c
  3107  	return v
  3108  }
  3109  
  3110  func bgetc(r *bio.Reader) int {
  3111  	c, err := r.ReadByte()
  3112  	if err != nil {
  3113  		if err != io.EOF {
  3114  			log.Fatalf("reading input: %v", err)
  3115  		}
  3116  		return -1
  3117  	}
  3118  	return int(c)
  3119  }
  3120  
  3121  type markKind uint8 // for postorder traversal
  3122  const (
  3123  	_ markKind = iota
  3124  	visiting
  3125  	visited
  3126  )
  3127  
  3128  func postorder(libs []*sym.Library) []*sym.Library {
  3129  	order := make([]*sym.Library, 0, len(libs)) // hold the result
  3130  	mark := make(map[*sym.Library]markKind, len(libs))
  3131  	for _, lib := range libs {
  3132  		dfs(lib, mark, &order)
  3133  	}
  3134  	return order
  3135  }
  3136  
  3137  func dfs(lib *sym.Library, mark map[*sym.Library]markKind, order *[]*sym.Library) {
  3138  	if mark[lib] == visited {
  3139  		return
  3140  	}
  3141  	if mark[lib] == visiting {
  3142  		panic("found import cycle while visiting " + lib.Pkg)
  3143  	}
  3144  	mark[lib] = visiting
  3145  	for _, i := range lib.Imports {
  3146  		dfs(i, mark, order)
  3147  	}
  3148  	mark[lib] = visited
  3149  	*order = append(*order, lib)
  3150  }
  3151  
  3152  func ElfSymForReloc(ctxt *Link, s loader.Sym) int32 {
  3153  	// If putelfsym created a local version of this symbol, use that in all
  3154  	// relocations.
  3155  	les := ctxt.loader.SymLocalElfSym(s)
  3156  	if les != 0 {
  3157  		return les
  3158  	} else {
  3159  		return ctxt.loader.SymElfSym(s)
  3160  	}
  3161  }
  3162  
  3163  func AddGotSym(target *Target, ldr *loader.Loader, syms *ArchSyms, s loader.Sym, elfRelocTyp uint32) {
  3164  	if ldr.SymGot(s) >= 0 {
  3165  		return
  3166  	}
  3167  
  3168  	Adddynsym(ldr, target, syms, s)
  3169  	got := ldr.MakeSymbolUpdater(syms.GOT)
  3170  	ldr.SetGot(s, int32(got.Size()))
  3171  	got.AddUint(target.Arch, 0)
  3172  
  3173  	if target.IsElf() {
  3174  		if target.Arch.PtrSize == 8 {
  3175  			rela := ldr.MakeSymbolUpdater(syms.Rela)
  3176  			rela.AddAddrPlus(target.Arch, got.Sym(), int64(ldr.SymGot(s)))
  3177  			rela.AddUint64(target.Arch, elf.R_INFO(uint32(ldr.SymDynid(s)), elfRelocTyp))
  3178  			rela.AddUint64(target.Arch, 0)
  3179  		} else {
  3180  			rel := ldr.MakeSymbolUpdater(syms.Rel)
  3181  			rel.AddAddrPlus(target.Arch, got.Sym(), int64(ldr.SymGot(s)))
  3182  			rel.AddUint32(target.Arch, elf.R_INFO32(uint32(ldr.SymDynid(s)), elfRelocTyp))
  3183  		}
  3184  	} else if target.IsDarwin() {
  3185  		leg := ldr.MakeSymbolUpdater(syms.LinkEditGOT)
  3186  		leg.AddUint32(target.Arch, uint32(ldr.SymDynid(s)))
  3187  		if target.IsPIE() && target.IsInternal() {
  3188  			// Mach-O relocations are a royal pain to lay out.
  3189  			// They use a compact stateful bytecode representation.
  3190  			// Here we record what are needed and encode them later.
  3191  			MachoAddBind(syms.GOT, int64(ldr.SymGot(s)), s)
  3192  		}
  3193  	} else {
  3194  		ldr.Errorf(s, "addgotsym: unsupported binary format")
  3195  	}
  3196  }
  3197  
  3198  // ElfAddDynAddrReloc emits an 8-byte ELF dynamic data relocation in .rela for r
  3199  // at s+r.Off(): absReloc against targ when targ is SDYNIMPORT, or relReloc
  3200  // (base-relative) otherwise.
  3201  //
  3202  // Symbol addresses have not been assigned yet when this is called (from
  3203  // adddynrel during dodata), so the r_offset and, for relReloc, r_addend
  3204  // fields are written with AddAddrPlus, which creates new R_ADDR relocations
  3205  // that are resolved in the 'reloc' phase. For a relReloc, r is not marked
  3206  // done, so it is still applied statically and the file contents hold the
  3207  // right offset to the relocation target (e.g. for go version).
  3208  func ElfAddDynAddrReloc(target *Target, ldr *loader.Loader, syms *ArchSyms, s loader.Sym, r loader.Reloc, rIdx int, absReloc, relReloc uint32) {
  3209  	targ := r.Sym()
  3210  	rela := ldr.MakeSymbolUpdater(syms.Rela)
  3211  	rela.AddAddrPlus(target.Arch, s, int64(r.Off()))
  3212  	if r.Siz() != 8 {
  3213  		ldr.Errorf(s, "unexpected relocation for dynamic symbol %s", ldr.SymName(targ))
  3214  	}
  3215  	if ldr.SymType(targ) == sym.SDYNIMPORT {
  3216  		Adddynsym(ldr, target, syms, targ)
  3217  		rela.AddUint64(target.Arch, elf.R_INFO(uint32(ldr.SymDynid(targ)), absReloc))
  3218  		rela.AddUint64(target.Arch, uint64(r.Add()))
  3219  		su := ldr.MakeSymbolUpdater(s)
  3220  		su.SetRelocType(rIdx, objabi.ElfRelocOffset)
  3221  		return
  3222  	}
  3223  	rela.AddUint64(target.Arch, elf.R_INFO(0, relReloc))
  3224  	rela.AddAddrPlus(target.Arch, targ, r.Add())
  3225  }
  3226  
  3227  var hostobjcounter int
  3228  
  3229  // captureHostObj writes out the content of a host object (pulled from
  3230  // an archive or loaded from a *.o file directly) to a directory
  3231  // specified via the linker's "-capturehostobjs" debugging flag. This
  3232  // is intended to make it easier for a developer to inspect the actual
  3233  // object feeding into "CGO internal" link step.
  3234  func captureHostObj(h *Hostobj) {
  3235  	// Form paths for info file and obj file.
  3236  	ofile := fmt.Sprintf("captured-obj-%d.o", hostobjcounter)
  3237  	ifile := fmt.Sprintf("captured-obj-%d.txt", hostobjcounter)
  3238  	hostobjcounter++
  3239  	opath := filepath.Join(*flagCaptureHostObjs, ofile)
  3240  	ipath := filepath.Join(*flagCaptureHostObjs, ifile)
  3241  
  3242  	// Write the info file.
  3243  	info := fmt.Sprintf("pkg: %s\npn: %s\nfile: %s\noff: %d\nlen: %d\n",
  3244  		h.pkg, h.pn, h.file, h.off, h.length)
  3245  	if err := os.WriteFile(ipath, []byte(info), 0666); err != nil {
  3246  		log.Fatalf("error writing captured host obj info %s: %v", ipath, err)
  3247  	}
  3248  
  3249  	readObjData := func() []byte {
  3250  		inf, err := os.Open(h.file)
  3251  		if err != nil {
  3252  			log.Fatalf("capturing host obj: open failed on %s: %v", h.pn, err)
  3253  		}
  3254  		defer inf.Close()
  3255  		res := make([]byte, h.length)
  3256  		if n, err := inf.ReadAt(res, h.off); err != nil || n != int(h.length) {
  3257  			log.Fatalf("capturing host obj: readat failed on %s: %v", h.pn, err)
  3258  		}
  3259  		return res
  3260  	}
  3261  
  3262  	// Write the object file.
  3263  	if err := os.WriteFile(opath, readObjData(), 0666); err != nil {
  3264  		log.Fatalf("error writing captured host object %s: %v", opath, err)
  3265  	}
  3266  
  3267  	fmt.Fprintf(os.Stderr, "link: info: captured host object %s to %s\n",
  3268  		h.file, opath)
  3269  }
  3270  
  3271  // findExtLinkTool invokes the external linker CC with --print-prog-name
  3272  // passing the name of the tool we're interested in, such as "strip",
  3273  // "ar", or "dsymutil", and returns the path passed back from the command.
  3274  func (ctxt *Link) findExtLinkTool(toolname string) string {
  3275  	if restrictedBuild() {
  3276  		Exitf("external linker tool %s is not allowed when GORESTRICTEDBUILD=1", toolname)
  3277  	}
  3278  	var cc []string
  3279  	cc = append(cc, ctxt.extld()...)
  3280  	cc = append(cc, hostlinkArchArgs(ctxt.Arch)...)
  3281  	cc = append(cc, "--print-prog-name", toolname)
  3282  	out, err := exec.Command(cc[0], cc[1:]...).CombinedOutput()
  3283  	if err != nil {
  3284  		Exitf("%s: finding %s failed: %v\n%s", os.Args[0], toolname, err, out)
  3285  	}
  3286  	cmdpath := strings.TrimRight(string(out), "\r\n")
  3287  	return cmdpath
  3288  }
  3289  
  3290  // isMSVC reports whether the C toolchain is clang with a -msvc target,
  3291  // e.g. the clang bundled in MSVC.
  3292  func (ctxt *Link) isMSVC() bool {
  3293  	if restrictedBuild() {
  3294  		return false
  3295  	}
  3296  	extld := ctxt.extld()
  3297  	name, args := extld[0], extld[1:]
  3298  	args = append(args, trimLinkerArgv(flagExtldflags)...)
  3299  	args = append(args, "--version")
  3300  	cmd := exec.Command(name, args...)
  3301  	if out, err := cmd.CombinedOutput(); err == nil {
  3302  		if bytes.Contains(out, []byte("-msvc\n")) || bytes.Contains(out, []byte("-msvc\r")) {
  3303  			return true
  3304  		}
  3305  	}
  3306  	return false
  3307  }
  3308  
  3309  // isLLD reports whether the C toolchain is using LLD as the linker.
  3310  func (ctxt *Link) isLLD() bool {
  3311  	if restrictedBuild() {
  3312  		return false
  3313  	}
  3314  	extld := ctxt.extld()
  3315  	name, args := extld[0], extld[1:]
  3316  	args = append(args, trimLinkerArgv(flagExtldflags)...)
  3317  	args = append(args, "-Wl,--version")
  3318  	cmd := exec.Command(name, args...)
  3319  	if out, err := cmd.CombinedOutput(); err == nil {
  3320  		if bytes.Contains(out, []byte("LLD ")) {
  3321  			return true
  3322  		}
  3323  	}
  3324  	return false
  3325  }
  3326  

View as plain text