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

View as plain text