Source file src/cmd/go/internal/work/exec.go

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Action graph execution.
     6  
     7  package work
     8  
     9  import (
    10  	"bytes"
    11  	"cmd/internal/cov/covcmd"
    12  	"cmd/internal/pathcache"
    13  	"context"
    14  	"crypto/sha256"
    15  	"encoding/json"
    16  	"errors"
    17  	"fmt"
    18  	"go/token"
    19  	"internal/lazyregexp"
    20  	"io"
    21  	"io/fs"
    22  	"log"
    23  	"math/rand"
    24  	"os"
    25  	"os/exec"
    26  	"path/filepath"
    27  	"regexp"
    28  	"runtime"
    29  	"slices"
    30  	"sort"
    31  	"strconv"
    32  	"strings"
    33  	"sync"
    34  	"time"
    35  
    36  	"cmd/go/internal/base"
    37  	"cmd/go/internal/cache"
    38  	"cmd/go/internal/cfg"
    39  	"cmd/go/internal/fsys"
    40  	"cmd/go/internal/gover"
    41  	"cmd/go/internal/load"
    42  	"cmd/go/internal/modload"
    43  	"cmd/go/internal/str"
    44  	"cmd/go/internal/trace"
    45  	"cmd/internal/buildid"
    46  	"cmd/internal/quoted"
    47  	"cmd/internal/sys"
    48  )
    49  
    50  const DefaultCFlags = "-O2 -g"
    51  
    52  // actionList returns the list of actions in the dag rooted at root
    53  // as visited in a depth-first post-order traversal.
    54  func actionList(root *Action) []*Action {
    55  	seen := map[*Action]bool{}
    56  	all := []*Action{}
    57  	var walk func(*Action)
    58  	walk = func(a *Action) {
    59  		if seen[a] {
    60  			return
    61  		}
    62  		seen[a] = true
    63  		for _, a1 := range a.Deps {
    64  			walk(a1)
    65  		}
    66  		all = append(all, a)
    67  	}
    68  	walk(root)
    69  	return all
    70  }
    71  
    72  // Do runs the action graph rooted at root.
    73  func (b *Builder) Do(ctx context.Context, root *Action) {
    74  	ctx, span := trace.StartSpan(ctx, "exec.Builder.Do ("+root.Mode+" "+root.Target+")")
    75  	defer span.Done()
    76  
    77  	if !b.IsCmdList {
    78  		// If we're doing real work, take time at the end to trim the cache.
    79  		c := cache.Default()
    80  		defer func() {
    81  			if err := c.Close(); err != nil {
    82  				base.Fatalf("go: failed to trim cache: %v", err)
    83  			}
    84  		}()
    85  	}
    86  
    87  	// Build list of all actions, assigning depth-first post-order priority.
    88  	// The original implementation here was a true queue
    89  	// (using a channel) but it had the effect of getting
    90  	// distracted by low-level leaf actions to the detriment
    91  	// of completing higher-level actions. The order of
    92  	// work does not matter much to overall execution time,
    93  	// but when running "go test std" it is nice to see each test
    94  	// results as soon as possible. The priorities assigned
    95  	// ensure that, all else being equal, the execution prefers
    96  	// to do what it would have done first in a simple depth-first
    97  	// dependency order traversal.
    98  	all := actionList(root)
    99  	for i, a := range all {
   100  		a.priority = i
   101  	}
   102  
   103  	// Write action graph, without timing information, in case we fail and exit early.
   104  	writeActionGraph := func() {
   105  		if file := cfg.DebugActiongraph; file != "" {
   106  			if strings.HasSuffix(file, ".go") {
   107  				// Do not overwrite Go source code in:
   108  				//	go build -debug-actiongraph x.go
   109  				base.Fatalf("go: refusing to write action graph to %v\n", file)
   110  			}
   111  			js := actionGraphJSON(root)
   112  			if err := os.WriteFile(file, []byte(js), 0666); err != nil {
   113  				fmt.Fprintf(os.Stderr, "go: writing action graph: %v\n", err)
   114  				base.SetExitStatus(1)
   115  			}
   116  		}
   117  	}
   118  	writeActionGraph()
   119  
   120  	b.readySema = make(chan bool, len(all))
   121  
   122  	// Initialize per-action execution state.
   123  	for _, a := range all {
   124  		for _, a1 := range a.Deps {
   125  			a1.triggers = append(a1.triggers, a)
   126  		}
   127  		a.pending = len(a.Deps)
   128  		if a.pending == 0 {
   129  			b.ready.push(a)
   130  			b.readySema <- true
   131  		}
   132  	}
   133  
   134  	// Handle runs a single action and takes care of triggering
   135  	// any actions that are runnable as a result.
   136  	handle := func(ctx context.Context, a *Action) {
   137  		if a.json != nil {
   138  			a.json.TimeStart = time.Now()
   139  		}
   140  		var err error
   141  		if a.Actor != nil && (!a.Failed || a.IgnoreFail) {
   142  			// TODO(matloob): Better action descriptions
   143  			desc := "Executing action (" + a.Mode
   144  			if a.Package != nil {
   145  				desc += " " + a.Package.Desc()
   146  			}
   147  			desc += ")"
   148  			ctx, span := trace.StartSpan(ctx, desc)
   149  			a.traceSpan = span
   150  			for _, d := range a.Deps {
   151  				trace.Flow(ctx, d.traceSpan, a.traceSpan)
   152  			}
   153  			err = a.Actor.Act(b, ctx, a)
   154  			span.Done()
   155  		}
   156  		if a.json != nil {
   157  			a.json.TimeDone = time.Now()
   158  		}
   159  
   160  		// The actions run in parallel but all the updates to the
   161  		// shared work state are serialized through b.exec.
   162  		b.exec.Lock()
   163  		defer b.exec.Unlock()
   164  
   165  		if err != nil {
   166  			if b.AllowErrors && a.Package != nil {
   167  				if a.Package.Error == nil {
   168  					a.Package.Error = &load.PackageError{Err: err}
   169  					a.Package.Incomplete = true
   170  				}
   171  			} else {
   172  				var ipe load.ImportPathError
   173  				if a.Package != nil && (!errors.As(err, &ipe) || ipe.ImportPath() != a.Package.ImportPath) {
   174  					err = fmt.Errorf("%s: %v", a.Package.ImportPath, err)
   175  				}
   176  				base.Errorf("%s", err)
   177  			}
   178  			a.Failed = true
   179  		}
   180  
   181  		for _, a0 := range a.triggers {
   182  			if a.Failed {
   183  				a0.Failed = true
   184  			}
   185  			if a0.pending--; a0.pending == 0 {
   186  				b.ready.push(a0)
   187  				b.readySema <- true
   188  			}
   189  		}
   190  
   191  		if a == root {
   192  			close(b.readySema)
   193  		}
   194  	}
   195  
   196  	var wg sync.WaitGroup
   197  
   198  	// Kick off goroutines according to parallelism.
   199  	// If we are using the -n flag (just printing commands)
   200  	// drop the parallelism to 1, both to make the output
   201  	// deterministic and because there is no real work anyway.
   202  	par := cfg.BuildP
   203  	if cfg.BuildN {
   204  		par = 1
   205  	}
   206  	for i := 0; i < par; i++ {
   207  		wg.Add(1)
   208  		go func() {
   209  			ctx := trace.StartGoroutine(ctx)
   210  			defer wg.Done()
   211  			for {
   212  				select {
   213  				case _, ok := <-b.readySema:
   214  					if !ok {
   215  						return
   216  					}
   217  					// Receiving a value from b.readySema entitles
   218  					// us to take from the ready queue.
   219  					b.exec.Lock()
   220  					a := b.ready.pop()
   221  					b.exec.Unlock()
   222  					handle(ctx, a)
   223  				case <-base.Interrupted:
   224  					base.SetExitStatus(1)
   225  					return
   226  				}
   227  			}
   228  		}()
   229  	}
   230  
   231  	wg.Wait()
   232  
   233  	// Write action graph again, this time with timing information.
   234  	writeActionGraph()
   235  }
   236  
   237  // buildActionID computes the action ID for a build action.
   238  func (b *Builder) buildActionID(a *Action) cache.ActionID {
   239  	p := a.Package
   240  	h := cache.NewHash("build " + p.ImportPath)
   241  
   242  	// Configuration independent of compiler toolchain.
   243  	// Note: buildmode has already been accounted for in buildGcflags
   244  	// and should not be inserted explicitly. Most buildmodes use the
   245  	// same compiler settings and can reuse each other's results.
   246  	// If not, the reason is already recorded in buildGcflags.
   247  	fmt.Fprintf(h, "compile\n")
   248  
   249  	// Include information about the origin of the package that
   250  	// may be embedded in the debug info for the object file.
   251  	if cfg.BuildTrimpath {
   252  		// When -trimpath is used with a package built from the module cache,
   253  		// its debug information refers to the module path and version
   254  		// instead of the directory.
   255  		if p.Module != nil {
   256  			fmt.Fprintf(h, "module %s@%s\n", p.Module.Path, p.Module.Version)
   257  		}
   258  	} else if p.Goroot {
   259  		// The Go compiler always hides the exact value of $GOROOT
   260  		// when building things in GOROOT.
   261  		//
   262  		// The C compiler does not, but for packages in GOROOT we rewrite the path
   263  		// as though -trimpath were set. This used to be so that we did not invalidate
   264  		// the build cache (and especially precompiled archive files) when changing
   265  		// GOROOT_FINAL, but we no longer ship precompiled archive files as of Go 1.20
   266  		// (https://go.dev/issue/47257) and no longer support GOROOT_FINAL
   267  		// (https://go.dev/issue/62047).
   268  		// TODO(bcmills): Figure out whether this behavior is still useful.
   269  		//
   270  		// b.WorkDir is always either trimmed or rewritten to
   271  		// the literal string "/tmp/go-build".
   272  	} else if !strings.HasPrefix(p.Dir, b.WorkDir) {
   273  		// -trimpath is not set and no other rewrite rules apply,
   274  		// so the object file may refer to the absolute directory
   275  		// containing the package.
   276  		fmt.Fprintf(h, "dir %s\n", p.Dir)
   277  	}
   278  
   279  	if p.Module != nil {
   280  		fmt.Fprintf(h, "go %s\n", p.Module.GoVersion)
   281  	}
   282  	fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
   283  	fmt.Fprintf(h, "import %q\n", p.ImportPath)
   284  	fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix)
   285  	if cfg.BuildTrimpath {
   286  		fmt.Fprintln(h, "trimpath")
   287  	}
   288  	if p.Internal.ForceLibrary {
   289  		fmt.Fprintf(h, "forcelibrary\n")
   290  	}
   291  	if len(p.CgoFiles)+len(p.SwigFiles)+len(p.SwigCXXFiles) > 0 {
   292  		fmt.Fprintf(h, "cgo %q\n", b.toolID("cgo"))
   293  		cppflags, cflags, cxxflags, fflags, ldflags, _ := b.CFlags(p)
   294  
   295  		ccExe := b.ccExe()
   296  		fmt.Fprintf(h, "CC=%q %q %q %q\n", ccExe, cppflags, cflags, ldflags)
   297  		// Include the C compiler tool ID so that if the C
   298  		// compiler changes we rebuild the package.
   299  		if ccID, _, err := b.gccToolID(ccExe[0], "c"); err == nil {
   300  			fmt.Fprintf(h, "CC ID=%q\n", ccID)
   301  		}
   302  		if len(p.CXXFiles)+len(p.SwigCXXFiles) > 0 {
   303  			cxxExe := b.cxxExe()
   304  			fmt.Fprintf(h, "CXX=%q %q\n", cxxExe, cxxflags)
   305  			if cxxID, _, err := b.gccToolID(cxxExe[0], "c++"); err == nil {
   306  				fmt.Fprintf(h, "CXX ID=%q\n", cxxID)
   307  			}
   308  		}
   309  		if len(p.FFiles) > 0 {
   310  			fcExe := b.fcExe()
   311  			fmt.Fprintf(h, "FC=%q %q\n", fcExe, fflags)
   312  			if fcID, _, err := b.gccToolID(fcExe[0], "f95"); err == nil {
   313  				fmt.Fprintf(h, "FC ID=%q\n", fcID)
   314  			}
   315  		}
   316  		// TODO(rsc): Should we include the SWIG version?
   317  	}
   318  	if p.Internal.Cover.Mode != "" {
   319  		fmt.Fprintf(h, "cover %q %q\n", p.Internal.Cover.Mode, b.toolID("cover"))
   320  	}
   321  	if p.Internal.FuzzInstrument {
   322  		if fuzzFlags := fuzzInstrumentFlags(); fuzzFlags != nil {
   323  			fmt.Fprintf(h, "fuzz %q\n", fuzzFlags)
   324  		}
   325  	}
   326  	if p.Internal.BuildInfo != nil {
   327  		fmt.Fprintf(h, "modinfo %q\n", p.Internal.BuildInfo.String())
   328  	}
   329  
   330  	// Configuration specific to compiler toolchain.
   331  	switch cfg.BuildToolchainName {
   332  	default:
   333  		base.Fatalf("buildActionID: unknown build toolchain %q", cfg.BuildToolchainName)
   334  	case "gc":
   335  		fmt.Fprintf(h, "compile %s %q %q\n", b.toolID("compile"), forcedGcflags, p.Internal.Gcflags)
   336  		if len(p.SFiles) > 0 {
   337  			fmt.Fprintf(h, "asm %q %q %q\n", b.toolID("asm"), forcedAsmflags, p.Internal.Asmflags)
   338  		}
   339  
   340  		// GOARM, GOMIPS, etc.
   341  		key, val, _ := cfg.GetArchEnv()
   342  		fmt.Fprintf(h, "%s=%s\n", key, val)
   343  
   344  		if cfg.CleanGOEXPERIMENT != "" {
   345  			fmt.Fprintf(h, "GOEXPERIMENT=%q\n", cfg.CleanGOEXPERIMENT)
   346  		}
   347  
   348  		// TODO(rsc): Convince compiler team not to add more magic environment variables,
   349  		// or perhaps restrict the environment variables passed to subprocesses.
   350  		// Because these are clumsy, undocumented special-case hacks
   351  		// for debugging the compiler, they are not settable using 'go env -w',
   352  		// and so here we use os.Getenv, not cfg.Getenv.
   353  		magic := []string{
   354  			"GOCLOBBERDEADHASH",
   355  			"GOSSAFUNC",
   356  			"GOSSADIR",
   357  			"GOCOMPILEDEBUG",
   358  		}
   359  		for _, env := range magic {
   360  			if x := os.Getenv(env); x != "" {
   361  				fmt.Fprintf(h, "magic %s=%s\n", env, x)
   362  			}
   363  		}
   364  
   365  	case "gccgo":
   366  		id, _, err := b.gccToolID(BuildToolchain.compiler(), "go")
   367  		if err != nil {
   368  			base.Fatalf("%v", err)
   369  		}
   370  		fmt.Fprintf(h, "compile %s %q %q\n", id, forcedGccgoflags, p.Internal.Gccgoflags)
   371  		fmt.Fprintf(h, "pkgpath %s\n", gccgoPkgpath(p))
   372  		fmt.Fprintf(h, "ar %q\n", BuildToolchain.(gccgoToolchain).ar())
   373  		if len(p.SFiles) > 0 {
   374  			id, _, _ = b.gccToolID(BuildToolchain.compiler(), "assembler-with-cpp")
   375  			// Ignore error; different assembler versions
   376  			// are unlikely to make any difference anyhow.
   377  			fmt.Fprintf(h, "asm %q\n", id)
   378  		}
   379  	}
   380  
   381  	// Input files.
   382  	inputFiles := str.StringList(
   383  		p.GoFiles,
   384  		p.CgoFiles,
   385  		p.CFiles,
   386  		p.CXXFiles,
   387  		p.FFiles,
   388  		p.MFiles,
   389  		p.HFiles,
   390  		p.SFiles,
   391  		p.SysoFiles,
   392  		p.SwigFiles,
   393  		p.SwigCXXFiles,
   394  		p.EmbedFiles,
   395  	)
   396  	for _, file := range inputFiles {
   397  		fmt.Fprintf(h, "file %s %s\n", file, b.fileHash(filepath.Join(p.Dir, file)))
   398  	}
   399  	for _, a1 := range a.Deps {
   400  		p1 := a1.Package
   401  		if p1 != nil {
   402  			fmt.Fprintf(h, "import %s %s\n", p1.ImportPath, contentID(a1.buildID))
   403  		}
   404  		if a1.Mode == "preprocess PGO profile" {
   405  			fmt.Fprintf(h, "pgofile %s\n", b.fileHash(a1.built))
   406  		}
   407  	}
   408  
   409  	return h.Sum()
   410  }
   411  
   412  // needCgoHdr reports whether the actions triggered by this one
   413  // expect to be able to access the cgo-generated header file.
   414  func (b *Builder) needCgoHdr(a *Action) bool {
   415  	// If this build triggers a header install, run cgo to get the header.
   416  	if !b.IsCmdList && (a.Package.UsesCgo() || a.Package.UsesSwig()) && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") {
   417  		for _, t1 := range a.triggers {
   418  			if t1.Mode == "install header" {
   419  				return true
   420  			}
   421  		}
   422  		for _, t1 := range a.triggers {
   423  			for _, t2 := range t1.triggers {
   424  				if t2.Mode == "install header" {
   425  					return true
   426  				}
   427  			}
   428  		}
   429  	}
   430  	return false
   431  }
   432  
   433  // allowedVersion reports whether the version v is an allowed version of go
   434  // (one that we can compile).
   435  // v is known to be of the form "1.23".
   436  func allowedVersion(v string) bool {
   437  	// Special case: no requirement.
   438  	if v == "" {
   439  		return true
   440  	}
   441  	return gover.Compare(gover.Local(), v) >= 0
   442  }
   443  
   444  const (
   445  	needBuild uint32 = 1 << iota
   446  	needCgoHdr
   447  	needVet
   448  	needCompiledGoFiles
   449  	needCovMetaFile
   450  	needStale
   451  )
   452  
   453  // build is the action for building a single package.
   454  // Note that any new influence on this logic must be reported in b.buildActionID above as well.
   455  func (b *Builder) build(ctx context.Context, a *Action) (err error) {
   456  	p := a.Package
   457  	sh := b.Shell(a)
   458  
   459  	bit := func(x uint32, b bool) uint32 {
   460  		if b {
   461  			return x
   462  		}
   463  		return 0
   464  	}
   465  
   466  	cachedBuild := false
   467  	needCovMeta := p.Internal.Cover.GenMeta
   468  	need := bit(needBuild, !b.IsCmdList && a.needBuild || b.NeedExport) |
   469  		bit(needCgoHdr, b.needCgoHdr(a)) |
   470  		bit(needVet, a.needVet) |
   471  		bit(needCovMetaFile, needCovMeta) |
   472  		bit(needCompiledGoFiles, b.NeedCompiledGoFiles)
   473  
   474  	if !p.BinaryOnly {
   475  		if b.useCache(a, b.buildActionID(a), p.Target, need&needBuild != 0) {
   476  			// We found the main output in the cache.
   477  			// If we don't need any other outputs, we can stop.
   478  			// Otherwise, we need to write files to a.Objdir (needVet, needCgoHdr).
   479  			// Remember that we might have them in cache
   480  			// and check again after we create a.Objdir.
   481  			cachedBuild = true
   482  			a.output = []byte{} // start saving output in case we miss any cache results
   483  			need &^= needBuild
   484  			if b.NeedExport {
   485  				p.Export = a.built
   486  				p.BuildID = a.buildID
   487  			}
   488  			if need&needCompiledGoFiles != 0 {
   489  				if err := b.loadCachedCompiledGoFiles(a); err == nil {
   490  					need &^= needCompiledGoFiles
   491  				}
   492  			}
   493  		}
   494  
   495  		// Source files might be cached, even if the full action is not
   496  		// (e.g., go list -compiled -find).
   497  		if !cachedBuild && need&needCompiledGoFiles != 0 {
   498  			if err := b.loadCachedCompiledGoFiles(a); err == nil {
   499  				need &^= needCompiledGoFiles
   500  			}
   501  		}
   502  
   503  		if need == 0 {
   504  			return nil
   505  		}
   506  		defer b.flushOutput(a)
   507  	}
   508  
   509  	defer func() {
   510  		if err != nil && b.IsCmdList && b.NeedError && p.Error == nil {
   511  			p.Error = &load.PackageError{Err: err}
   512  		}
   513  	}()
   514  	if cfg.BuildN {
   515  		// In -n mode, print a banner between packages.
   516  		// The banner is five lines so that when changes to
   517  		// different sections of the bootstrap script have to
   518  		// be merged, the banners give patch something
   519  		// to use to find its context.
   520  		sh.Print("\n#\n# " + p.ImportPath + "\n#\n\n")
   521  	}
   522  
   523  	if cfg.BuildV {
   524  		sh.Print(p.ImportPath + "\n")
   525  	}
   526  
   527  	if p.Error != nil {
   528  		// Don't try to build anything for packages with errors. There may be a
   529  		// problem with the inputs that makes the package unsafe to build.
   530  		return p.Error
   531  	}
   532  
   533  	if p.BinaryOnly {
   534  		p.Stale = true
   535  		p.StaleReason = "binary-only packages are no longer supported"
   536  		if b.IsCmdList {
   537  			return nil
   538  		}
   539  		return errors.New("binary-only packages are no longer supported")
   540  	}
   541  
   542  	if p.Module != nil && !allowedVersion(p.Module.GoVersion) {
   543  		return errors.New("module requires Go " + p.Module.GoVersion + " or later")
   544  	}
   545  
   546  	if err := b.checkDirectives(a); err != nil {
   547  		return err
   548  	}
   549  
   550  	if err := sh.Mkdir(a.Objdir); err != nil {
   551  		return err
   552  	}
   553  	objdir := a.Objdir
   554  
   555  	// Load cached cgo header, but only if we're skipping the main build (cachedBuild==true).
   556  	if cachedBuild && need&needCgoHdr != 0 {
   557  		if err := b.loadCachedCgoHdr(a); err == nil {
   558  			need &^= needCgoHdr
   559  		}
   560  	}
   561  
   562  	// Load cached coverage meta-data file fragment, but only if we're
   563  	// skipping the main build (cachedBuild==true).
   564  	if cachedBuild && need&needCovMetaFile != 0 {
   565  		bact := a.Actor.(*buildActor)
   566  		if err := b.loadCachedObjdirFile(a, cache.Default(), bact.covMetaFileName); err == nil {
   567  			need &^= needCovMetaFile
   568  		}
   569  	}
   570  
   571  	// Load cached vet config, but only if that's all we have left
   572  	// (need == needVet, not testing just the one bit).
   573  	// If we are going to do a full build anyway,
   574  	// we're going to regenerate the files below anyway.
   575  	if need == needVet {
   576  		if err := b.loadCachedVet(a); err == nil {
   577  			need &^= needVet
   578  		}
   579  	}
   580  	if need == 0 {
   581  		return nil
   582  	}
   583  
   584  	if err := AllowInstall(a); err != nil {
   585  		return err
   586  	}
   587  
   588  	// make target directory
   589  	dir, _ := filepath.Split(a.Target)
   590  	if dir != "" {
   591  		if err := sh.Mkdir(dir); err != nil {
   592  			return err
   593  		}
   594  	}
   595  
   596  	gofiles := str.StringList(p.GoFiles)
   597  	cgofiles := str.StringList(p.CgoFiles)
   598  	cfiles := str.StringList(p.CFiles)
   599  	sfiles := str.StringList(p.SFiles)
   600  	cxxfiles := str.StringList(p.CXXFiles)
   601  	var objects, cgoObjects, pcCFLAGS, pcLDFLAGS []string
   602  
   603  	if p.UsesCgo() || p.UsesSwig() {
   604  		if pcCFLAGS, pcLDFLAGS, err = b.getPkgConfigFlags(a); err != nil {
   605  			return
   606  		}
   607  	}
   608  
   609  	// Compute overlays for .c/.cc/.h/etc. and if there are any overlays
   610  	// put correct contents of all those files in the objdir, to ensure
   611  	// the correct headers are included. nonGoOverlay is the overlay that
   612  	// points from nongo files to the copied files in objdir.
   613  	nonGoFileLists := [][]string{p.CFiles, p.SFiles, p.CXXFiles, p.HFiles, p.FFiles}
   614  OverlayLoop:
   615  	for _, fs := range nonGoFileLists {
   616  		for _, f := range fs {
   617  			if _, ok := fsys.OverlayPath(mkAbs(p.Dir, f)); ok {
   618  				a.nonGoOverlay = make(map[string]string)
   619  				break OverlayLoop
   620  			}
   621  		}
   622  	}
   623  	if a.nonGoOverlay != nil {
   624  		for _, fs := range nonGoFileLists {
   625  			for i := range fs {
   626  				from := mkAbs(p.Dir, fs[i])
   627  				opath, _ := fsys.OverlayPath(from)
   628  				dst := objdir + filepath.Base(fs[i])
   629  				if err := sh.CopyFile(dst, opath, 0666, false); err != nil {
   630  					return err
   631  				}
   632  				a.nonGoOverlay[from] = dst
   633  			}
   634  		}
   635  	}
   636  
   637  	// If we're doing coverage, preprocess the .go files and put them in the work directory
   638  	if p.Internal.Cover.Mode != "" {
   639  		outfiles := []string{}
   640  		infiles := []string{}
   641  		for i, file := range str.StringList(gofiles, cgofiles) {
   642  			if base.IsTestFile(file) {
   643  				continue // Not covering this file.
   644  			}
   645  
   646  			var sourceFile string
   647  			var coverFile string
   648  			var key string
   649  			if base, found := strings.CutSuffix(file, ".cgo1.go"); found {
   650  				// cgo files have absolute paths
   651  				base = filepath.Base(base)
   652  				sourceFile = file
   653  				coverFile = objdir + base + ".cgo1.go"
   654  				key = base + ".go"
   655  			} else {
   656  				sourceFile = filepath.Join(p.Dir, file)
   657  				coverFile = objdir + file
   658  				key = file
   659  			}
   660  			coverFile = strings.TrimSuffix(coverFile, ".go") + ".cover.go"
   661  			if cfg.Experiment.CoverageRedesign {
   662  				infiles = append(infiles, sourceFile)
   663  				outfiles = append(outfiles, coverFile)
   664  			} else {
   665  				cover := p.Internal.CoverVars[key]
   666  				if cover == nil {
   667  					continue // Not covering this file.
   668  				}
   669  				if err := b.cover(a, coverFile, sourceFile, cover.Var); err != nil {
   670  					return err
   671  				}
   672  			}
   673  			if i < len(gofiles) {
   674  				gofiles[i] = coverFile
   675  			} else {
   676  				cgofiles[i-len(gofiles)] = coverFile
   677  			}
   678  		}
   679  
   680  		if cfg.Experiment.CoverageRedesign {
   681  			if len(infiles) != 0 {
   682  				// Coverage instrumentation creates new top level
   683  				// variables in the target package for things like
   684  				// meta-data containers, counter vars, etc. To avoid
   685  				// collisions with user variables, suffix the var name
   686  				// with 12 hex digits from the SHA-256 hash of the
   687  				// import path. Choice of 12 digits is historical/arbitrary,
   688  				// we just need enough of the hash to avoid accidents,
   689  				// as opposed to precluding determined attempts by
   690  				// users to break things.
   691  				sum := sha256.Sum256([]byte(a.Package.ImportPath))
   692  				coverVar := fmt.Sprintf("goCover_%x_", sum[:6])
   693  				mode := a.Package.Internal.Cover.Mode
   694  				if mode == "" {
   695  					panic("covermode should be set at this point")
   696  				}
   697  				if newoutfiles, err := b.cover2(a, infiles, outfiles, coverVar, mode); err != nil {
   698  					return err
   699  				} else {
   700  					outfiles = newoutfiles
   701  					gofiles = append([]string{newoutfiles[0]}, gofiles...)
   702  				}
   703  			} else {
   704  				// If there are no input files passed to cmd/cover,
   705  				// then we don't want to pass -covercfg when building
   706  				// the package with the compiler, so set covermode to
   707  				// the empty string so as to signal that we need to do
   708  				// that.
   709  				p.Internal.Cover.Mode = ""
   710  			}
   711  			if ba, ok := a.Actor.(*buildActor); ok && ba.covMetaFileName != "" {
   712  				b.cacheObjdirFile(a, cache.Default(), ba.covMetaFileName)
   713  			}
   714  		}
   715  	}
   716  
   717  	// Run SWIG on each .swig and .swigcxx file.
   718  	// Each run will generate two files, a .go file and a .c or .cxx file.
   719  	// The .go file will use import "C" and is to be processed by cgo.
   720  	// For -cover test or build runs, this needs to happen after the cover
   721  	// tool is run; we don't want to instrument swig-generated Go files,
   722  	// see issue #64661.
   723  	if p.UsesSwig() {
   724  		outGo, outC, outCXX, err := b.swig(a, objdir, pcCFLAGS)
   725  		if err != nil {
   726  			return err
   727  		}
   728  		cgofiles = append(cgofiles, outGo...)
   729  		cfiles = append(cfiles, outC...)
   730  		cxxfiles = append(cxxfiles, outCXX...)
   731  	}
   732  
   733  	// Run cgo.
   734  	if p.UsesCgo() || p.UsesSwig() {
   735  		// In a package using cgo, cgo compiles the C, C++ and assembly files with gcc.
   736  		// There is one exception: runtime/cgo's job is to bridge the
   737  		// cgo and non-cgo worlds, so it necessarily has files in both.
   738  		// In that case gcc only gets the gcc_* files.
   739  		var gccfiles []string
   740  		gccfiles = append(gccfiles, cfiles...)
   741  		cfiles = nil
   742  		if p.Standard && p.ImportPath == "runtime/cgo" {
   743  			filter := func(files, nongcc, gcc []string) ([]string, []string) {
   744  				for _, f := range files {
   745  					if strings.HasPrefix(f, "gcc_") {
   746  						gcc = append(gcc, f)
   747  					} else {
   748  						nongcc = append(nongcc, f)
   749  					}
   750  				}
   751  				return nongcc, gcc
   752  			}
   753  			sfiles, gccfiles = filter(sfiles, sfiles[:0], gccfiles)
   754  		} else {
   755  			for _, sfile := range sfiles {
   756  				data, err := os.ReadFile(filepath.Join(p.Dir, sfile))
   757  				if err == nil {
   758  					if bytes.HasPrefix(data, []byte("TEXT")) || bytes.Contains(data, []byte("\nTEXT")) ||
   759  						bytes.HasPrefix(data, []byte("DATA")) || bytes.Contains(data, []byte("\nDATA")) ||
   760  						bytes.HasPrefix(data, []byte("GLOBL")) || bytes.Contains(data, []byte("\nGLOBL")) {
   761  						return fmt.Errorf("package using cgo has Go assembly file %s", sfile)
   762  					}
   763  				}
   764  			}
   765  			gccfiles = append(gccfiles, sfiles...)
   766  			sfiles = nil
   767  		}
   768  
   769  		outGo, outObj, err := b.cgo(a, base.Tool("cgo"), objdir, pcCFLAGS, pcLDFLAGS, mkAbsFiles(p.Dir, cgofiles), gccfiles, cxxfiles, p.MFiles, p.FFiles)
   770  
   771  		// The files in cxxfiles have now been handled by b.cgo.
   772  		cxxfiles = nil
   773  
   774  		if err != nil {
   775  			return err
   776  		}
   777  		if cfg.BuildToolchainName == "gccgo" {
   778  			cgoObjects = append(cgoObjects, a.Objdir+"_cgo_flags")
   779  		}
   780  		cgoObjects = append(cgoObjects, outObj...)
   781  		gofiles = append(gofiles, outGo...)
   782  
   783  		switch cfg.BuildBuildmode {
   784  		case "c-archive", "c-shared":
   785  			b.cacheCgoHdr(a)
   786  		}
   787  	}
   788  
   789  	var srcfiles []string // .go and non-.go
   790  	srcfiles = append(srcfiles, gofiles...)
   791  	srcfiles = append(srcfiles, sfiles...)
   792  	srcfiles = append(srcfiles, cfiles...)
   793  	srcfiles = append(srcfiles, cxxfiles...)
   794  	b.cacheSrcFiles(a, srcfiles)
   795  
   796  	// Running cgo generated the cgo header.
   797  	need &^= needCgoHdr
   798  
   799  	// Sanity check only, since Package.load already checked as well.
   800  	if len(gofiles) == 0 {
   801  		return &load.NoGoError{Package: p}
   802  	}
   803  
   804  	// Prepare Go vet config if needed.
   805  	if need&needVet != 0 {
   806  		buildVetConfig(a, srcfiles)
   807  		need &^= needVet
   808  	}
   809  	if need&needCompiledGoFiles != 0 {
   810  		if err := b.loadCachedCompiledGoFiles(a); err != nil {
   811  			return fmt.Errorf("loading compiled Go files from cache: %w", err)
   812  		}
   813  		need &^= needCompiledGoFiles
   814  	}
   815  	if need == 0 {
   816  		// Nothing left to do.
   817  		return nil
   818  	}
   819  
   820  	// Collect symbol ABI requirements from assembly.
   821  	symabis, err := BuildToolchain.symabis(b, a, sfiles)
   822  	if err != nil {
   823  		return err
   824  	}
   825  
   826  	// Prepare Go import config.
   827  	// We start it off with a comment so it can't be empty, so icfg.Bytes() below is never nil.
   828  	// It should never be empty anyway, but there have been bugs in the past that resulted
   829  	// in empty configs, which then unfortunately turn into "no config passed to compiler",
   830  	// and the compiler falls back to looking in pkg itself, which mostly works,
   831  	// except when it doesn't.
   832  	var icfg bytes.Buffer
   833  	fmt.Fprintf(&icfg, "# import config\n")
   834  	for i, raw := range p.Internal.RawImports {
   835  		final := p.Imports[i]
   836  		if final != raw {
   837  			fmt.Fprintf(&icfg, "importmap %s=%s\n", raw, final)
   838  		}
   839  	}
   840  	for _, a1 := range a.Deps {
   841  		p1 := a1.Package
   842  		if p1 == nil || p1.ImportPath == "" || a1.built == "" {
   843  			continue
   844  		}
   845  		fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built)
   846  	}
   847  
   848  	// Prepare Go embed config if needed.
   849  	// Unlike the import config, it's okay for the embed config to be empty.
   850  	var embedcfg []byte
   851  	if len(p.Internal.Embed) > 0 {
   852  		var embed struct {
   853  			Patterns map[string][]string
   854  			Files    map[string]string
   855  		}
   856  		embed.Patterns = p.Internal.Embed
   857  		embed.Files = make(map[string]string)
   858  		for _, file := range p.EmbedFiles {
   859  			embed.Files[file] = filepath.Join(p.Dir, file)
   860  		}
   861  		js, err := json.MarshalIndent(&embed, "", "\t")
   862  		if err != nil {
   863  			return fmt.Errorf("marshal embedcfg: %v", err)
   864  		}
   865  		embedcfg = js
   866  	}
   867  
   868  	// Find PGO profile if needed.
   869  	var pgoProfile string
   870  	for _, a1 := range a.Deps {
   871  		if a1.Mode != "preprocess PGO profile" {
   872  			continue
   873  		}
   874  		if pgoProfile != "" {
   875  			return fmt.Errorf("action contains multiple PGO profile dependencies")
   876  		}
   877  		pgoProfile = a1.built
   878  	}
   879  
   880  	if p.Internal.BuildInfo != nil && cfg.ModulesEnabled {
   881  		prog := modload.ModInfoProg(p.Internal.BuildInfo.String(), cfg.BuildToolchainName == "gccgo")
   882  		if len(prog) > 0 {
   883  			if err := sh.writeFile(objdir+"_gomod_.go", prog); err != nil {
   884  				return err
   885  			}
   886  			gofiles = append(gofiles, objdir+"_gomod_.go")
   887  		}
   888  	}
   889  
   890  	// Compile Go.
   891  	objpkg := objdir + "_pkg_.a"
   892  	ofile, out, err := BuildToolchain.gc(b, a, objpkg, icfg.Bytes(), embedcfg, symabis, len(sfiles) > 0, pgoProfile, gofiles)
   893  	if err := sh.reportCmd("", "", out, err); err != nil {
   894  		return err
   895  	}
   896  	if ofile != objpkg {
   897  		objects = append(objects, ofile)
   898  	}
   899  
   900  	// Copy .h files named for goos or goarch or goos_goarch
   901  	// to names using GOOS and GOARCH.
   902  	// For example, defs_linux_amd64.h becomes defs_GOOS_GOARCH.h.
   903  	_goos_goarch := "_" + cfg.Goos + "_" + cfg.Goarch
   904  	_goos := "_" + cfg.Goos
   905  	_goarch := "_" + cfg.Goarch
   906  	for _, file := range p.HFiles {
   907  		name, ext := fileExtSplit(file)
   908  		switch {
   909  		case strings.HasSuffix(name, _goos_goarch):
   910  			targ := file[:len(name)-len(_goos_goarch)] + "_GOOS_GOARCH." + ext
   911  			if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil {
   912  				return err
   913  			}
   914  		case strings.HasSuffix(name, _goarch):
   915  			targ := file[:len(name)-len(_goarch)] + "_GOARCH." + ext
   916  			if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil {
   917  				return err
   918  			}
   919  		case strings.HasSuffix(name, _goos):
   920  			targ := file[:len(name)-len(_goos)] + "_GOOS." + ext
   921  			if err := sh.CopyFile(objdir+targ, filepath.Join(p.Dir, file), 0666, true); err != nil {
   922  				return err
   923  			}
   924  		}
   925  	}
   926  
   927  	for _, file := range cfiles {
   928  		out := file[:len(file)-len(".c")] + ".o"
   929  		if err := BuildToolchain.cc(b, a, objdir+out, file); err != nil {
   930  			return err
   931  		}
   932  		objects = append(objects, out)
   933  	}
   934  
   935  	// Assemble .s files.
   936  	if len(sfiles) > 0 {
   937  		ofiles, err := BuildToolchain.asm(b, a, sfiles)
   938  		if err != nil {
   939  			return err
   940  		}
   941  		objects = append(objects, ofiles...)
   942  	}
   943  
   944  	// For gccgo on ELF systems, we write the build ID as an assembler file.
   945  	// This lets us set the SHF_EXCLUDE flag.
   946  	// This is read by readGccgoArchive in cmd/internal/buildid/buildid.go.
   947  	if a.buildID != "" && cfg.BuildToolchainName == "gccgo" {
   948  		switch cfg.Goos {
   949  		case "aix", "android", "dragonfly", "freebsd", "illumos", "linux", "netbsd", "openbsd", "solaris":
   950  			asmfile, err := b.gccgoBuildIDFile(a)
   951  			if err != nil {
   952  				return err
   953  			}
   954  			ofiles, err := BuildToolchain.asm(b, a, []string{asmfile})
   955  			if err != nil {
   956  				return err
   957  			}
   958  			objects = append(objects, ofiles...)
   959  		}
   960  	}
   961  
   962  	// NOTE(rsc): On Windows, it is critically important that the
   963  	// gcc-compiled objects (cgoObjects) be listed after the ordinary
   964  	// objects in the archive. I do not know why this is.
   965  	// https://golang.org/issue/2601
   966  	objects = append(objects, cgoObjects...)
   967  
   968  	// Add system object files.
   969  	for _, syso := range p.SysoFiles {
   970  		objects = append(objects, filepath.Join(p.Dir, syso))
   971  	}
   972  
   973  	// Pack into archive in objdir directory.
   974  	// If the Go compiler wrote an archive, we only need to add the
   975  	// object files for non-Go sources to the archive.
   976  	// If the Go compiler wrote an archive and the package is entirely
   977  	// Go sources, there is no pack to execute at all.
   978  	if len(objects) > 0 {
   979  		if err := BuildToolchain.pack(b, a, objpkg, objects); err != nil {
   980  			return err
   981  		}
   982  	}
   983  
   984  	if err := b.updateBuildID(a, objpkg, true); err != nil {
   985  		return err
   986  	}
   987  
   988  	a.built = objpkg
   989  	return nil
   990  }
   991  
   992  func (b *Builder) checkDirectives(a *Action) error {
   993  	var msg []byte
   994  	p := a.Package
   995  	var seen map[string]token.Position
   996  	for _, d := range p.Internal.Build.Directives {
   997  		if strings.HasPrefix(d.Text, "//go:debug") {
   998  			key, _, err := load.ParseGoDebug(d.Text)
   999  			if err != nil && err != load.ErrNotGoDebug {
  1000  				msg = fmt.Appendf(msg, "%s: invalid //go:debug: %v\n", d.Pos, err)
  1001  				continue
  1002  			}
  1003  			if pos, ok := seen[key]; ok {
  1004  				msg = fmt.Appendf(msg, "%s: repeated //go:debug for %v\n\t%s: previous //go:debug\n", d.Pos, key, pos)
  1005  				continue
  1006  			}
  1007  			if seen == nil {
  1008  				seen = make(map[string]token.Position)
  1009  			}
  1010  			seen[key] = d.Pos
  1011  		}
  1012  	}
  1013  	if len(msg) > 0 {
  1014  		// We pass a non-nil error to reportCmd to trigger the failure reporting
  1015  		// path, but the content of the error doesn't matter because msg is
  1016  		// non-empty.
  1017  		err := errors.New("invalid directive")
  1018  		return b.Shell(a).reportCmd("", "", msg, err)
  1019  	}
  1020  	return nil
  1021  }
  1022  
  1023  func (b *Builder) cacheObjdirFile(a *Action, c cache.Cache, name string) error {
  1024  	f, err := os.Open(a.Objdir + name)
  1025  	if err != nil {
  1026  		return err
  1027  	}
  1028  	defer f.Close()
  1029  	_, _, err = c.Put(cache.Subkey(a.actionID, name), f)
  1030  	return err
  1031  }
  1032  
  1033  func (b *Builder) findCachedObjdirFile(a *Action, c cache.Cache, name string) (string, error) {
  1034  	file, _, err := cache.GetFile(c, cache.Subkey(a.actionID, name))
  1035  	if err != nil {
  1036  		return "", fmt.Errorf("loading cached file %s: %w", name, err)
  1037  	}
  1038  	return file, nil
  1039  }
  1040  
  1041  func (b *Builder) loadCachedObjdirFile(a *Action, c cache.Cache, name string) error {
  1042  	cached, err := b.findCachedObjdirFile(a, c, name)
  1043  	if err != nil {
  1044  		return err
  1045  	}
  1046  	return b.Shell(a).CopyFile(a.Objdir+name, cached, 0666, true)
  1047  }
  1048  
  1049  func (b *Builder) cacheCgoHdr(a *Action) {
  1050  	c := cache.Default()
  1051  	b.cacheObjdirFile(a, c, "_cgo_install.h")
  1052  }
  1053  
  1054  func (b *Builder) loadCachedCgoHdr(a *Action) error {
  1055  	c := cache.Default()
  1056  	return b.loadCachedObjdirFile(a, c, "_cgo_install.h")
  1057  }
  1058  
  1059  func (b *Builder) cacheSrcFiles(a *Action, srcfiles []string) {
  1060  	c := cache.Default()
  1061  	var buf bytes.Buffer
  1062  	for _, file := range srcfiles {
  1063  		if !strings.HasPrefix(file, a.Objdir) {
  1064  			// not generated
  1065  			buf.WriteString("./")
  1066  			buf.WriteString(file)
  1067  			buf.WriteString("\n")
  1068  			continue
  1069  		}
  1070  		name := file[len(a.Objdir):]
  1071  		buf.WriteString(name)
  1072  		buf.WriteString("\n")
  1073  		if err := b.cacheObjdirFile(a, c, name); err != nil {
  1074  			return
  1075  		}
  1076  	}
  1077  	cache.PutBytes(c, cache.Subkey(a.actionID, "srcfiles"), buf.Bytes())
  1078  }
  1079  
  1080  func (b *Builder) loadCachedVet(a *Action) error {
  1081  	c := cache.Default()
  1082  	list, _, err := cache.GetBytes(c, cache.Subkey(a.actionID, "srcfiles"))
  1083  	if err != nil {
  1084  		return fmt.Errorf("reading srcfiles list: %w", err)
  1085  	}
  1086  	var srcfiles []string
  1087  	for _, name := range strings.Split(string(list), "\n") {
  1088  		if name == "" { // end of list
  1089  			continue
  1090  		}
  1091  		if strings.HasPrefix(name, "./") {
  1092  			srcfiles = append(srcfiles, name[2:])
  1093  			continue
  1094  		}
  1095  		if err := b.loadCachedObjdirFile(a, c, name); err != nil {
  1096  			return err
  1097  		}
  1098  		srcfiles = append(srcfiles, a.Objdir+name)
  1099  	}
  1100  	buildVetConfig(a, srcfiles)
  1101  	return nil
  1102  }
  1103  
  1104  func (b *Builder) loadCachedCompiledGoFiles(a *Action) error {
  1105  	c := cache.Default()
  1106  	list, _, err := cache.GetBytes(c, cache.Subkey(a.actionID, "srcfiles"))
  1107  	if err != nil {
  1108  		return fmt.Errorf("reading srcfiles list: %w", err)
  1109  	}
  1110  	var gofiles []string
  1111  	for _, name := range strings.Split(string(list), "\n") {
  1112  		if name == "" { // end of list
  1113  			continue
  1114  		} else if !strings.HasSuffix(name, ".go") {
  1115  			continue
  1116  		}
  1117  		if strings.HasPrefix(name, "./") {
  1118  			gofiles = append(gofiles, name[len("./"):])
  1119  			continue
  1120  		}
  1121  		file, err := b.findCachedObjdirFile(a, c, name)
  1122  		if err != nil {
  1123  			return fmt.Errorf("finding %s: %w", name, err)
  1124  		}
  1125  		gofiles = append(gofiles, file)
  1126  	}
  1127  	a.Package.CompiledGoFiles = gofiles
  1128  	return nil
  1129  }
  1130  
  1131  // vetConfig is the configuration passed to vet describing a single package.
  1132  type vetConfig struct {
  1133  	ID           string   // package ID (example: "fmt [fmt.test]")
  1134  	Compiler     string   // compiler name (gc, gccgo)
  1135  	Dir          string   // directory containing package
  1136  	ImportPath   string   // canonical import path ("package path")
  1137  	GoFiles      []string // absolute paths to package source files
  1138  	NonGoFiles   []string // absolute paths to package non-Go files
  1139  	IgnoredFiles []string // absolute paths to ignored source files
  1140  
  1141  	ModulePath    string            // module path (may be "" on module error)
  1142  	ModuleVersion string            // module version (may be "" on main module or module error)
  1143  	ImportMap     map[string]string // map import path in source code to package path
  1144  	PackageFile   map[string]string // map package path to .a file with export data
  1145  	Standard      map[string]bool   // map package path to whether it's in the standard library
  1146  	PackageVetx   map[string]string // map package path to vetx data from earlier vet run
  1147  	VetxOnly      bool              // only compute vetx data; don't report detected problems
  1148  	VetxOutput    string            // write vetx data to this output file
  1149  	GoVersion     string            // Go version for package
  1150  
  1151  	SucceedOnTypecheckFailure bool // awful hack; see #18395 and below
  1152  }
  1153  
  1154  func buildVetConfig(a *Action, srcfiles []string) {
  1155  	// Classify files based on .go extension.
  1156  	// srcfiles does not include raw cgo files.
  1157  	var gofiles, nongofiles []string
  1158  	for _, name := range srcfiles {
  1159  		if strings.HasSuffix(name, ".go") {
  1160  			gofiles = append(gofiles, name)
  1161  		} else {
  1162  			nongofiles = append(nongofiles, name)
  1163  		}
  1164  	}
  1165  
  1166  	ignored := str.StringList(a.Package.IgnoredGoFiles, a.Package.IgnoredOtherFiles)
  1167  
  1168  	// Pass list of absolute paths to vet,
  1169  	// so that vet's error messages will use absolute paths,
  1170  	// so that we can reformat them relative to the directory
  1171  	// in which the go command is invoked.
  1172  	vcfg := &vetConfig{
  1173  		ID:           a.Package.ImportPath,
  1174  		Compiler:     cfg.BuildToolchainName,
  1175  		Dir:          a.Package.Dir,
  1176  		GoFiles:      mkAbsFiles(a.Package.Dir, gofiles),
  1177  		NonGoFiles:   mkAbsFiles(a.Package.Dir, nongofiles),
  1178  		IgnoredFiles: mkAbsFiles(a.Package.Dir, ignored),
  1179  		ImportPath:   a.Package.ImportPath,
  1180  		ImportMap:    make(map[string]string),
  1181  		PackageFile:  make(map[string]string),
  1182  		Standard:     make(map[string]bool),
  1183  	}
  1184  	vcfg.GoVersion = "go" + gover.Local()
  1185  	if a.Package.Module != nil {
  1186  		v := a.Package.Module.GoVersion
  1187  		if v == "" {
  1188  			v = gover.DefaultGoModVersion
  1189  		}
  1190  		vcfg.GoVersion = "go" + v
  1191  
  1192  		if a.Package.Module.Error == nil {
  1193  			vcfg.ModulePath = a.Package.Module.Path
  1194  			vcfg.ModuleVersion = a.Package.Module.Version
  1195  		}
  1196  	}
  1197  	a.vetCfg = vcfg
  1198  	for i, raw := range a.Package.Internal.RawImports {
  1199  		final := a.Package.Imports[i]
  1200  		vcfg.ImportMap[raw] = final
  1201  	}
  1202  
  1203  	// Compute the list of mapped imports in the vet config
  1204  	// so that we can add any missing mappings below.
  1205  	vcfgMapped := make(map[string]bool)
  1206  	for _, p := range vcfg.ImportMap {
  1207  		vcfgMapped[p] = true
  1208  	}
  1209  
  1210  	for _, a1 := range a.Deps {
  1211  		p1 := a1.Package
  1212  		if p1 == nil || p1.ImportPath == "" {
  1213  			continue
  1214  		}
  1215  		// Add import mapping if needed
  1216  		// (for imports like "runtime/cgo" that appear only in generated code).
  1217  		if !vcfgMapped[p1.ImportPath] {
  1218  			vcfg.ImportMap[p1.ImportPath] = p1.ImportPath
  1219  		}
  1220  		if a1.built != "" {
  1221  			vcfg.PackageFile[p1.ImportPath] = a1.built
  1222  		}
  1223  		if p1.Standard {
  1224  			vcfg.Standard[p1.ImportPath] = true
  1225  		}
  1226  	}
  1227  }
  1228  
  1229  // VetTool is the path to an alternate vet tool binary.
  1230  // The caller is expected to set it (if needed) before executing any vet actions.
  1231  var VetTool string
  1232  
  1233  // VetFlags are the default flags to pass to vet.
  1234  // The caller is expected to set them before executing any vet actions.
  1235  var VetFlags []string
  1236  
  1237  // VetExplicit records whether the vet flags were set explicitly on the command line.
  1238  var VetExplicit bool
  1239  
  1240  func (b *Builder) vet(ctx context.Context, a *Action) error {
  1241  	// a.Deps[0] is the build of the package being vetted.
  1242  	// a.Deps[1] is the build of the "fmt" package.
  1243  
  1244  	a.Failed = false // vet of dependency may have failed but we can still succeed
  1245  
  1246  	if a.Deps[0].Failed {
  1247  		// The build of the package has failed. Skip vet check.
  1248  		// Vet could return export data for non-typecheck errors,
  1249  		// but we ignore it because the package cannot be compiled.
  1250  		return nil
  1251  	}
  1252  
  1253  	vcfg := a.Deps[0].vetCfg
  1254  	if vcfg == nil {
  1255  		// Vet config should only be missing if the build failed.
  1256  		return fmt.Errorf("vet config not found")
  1257  	}
  1258  
  1259  	sh := b.Shell(a)
  1260  
  1261  	vcfg.VetxOnly = a.VetxOnly
  1262  	vcfg.VetxOutput = a.Objdir + "vet.out"
  1263  	vcfg.PackageVetx = make(map[string]string)
  1264  
  1265  	h := cache.NewHash("vet " + a.Package.ImportPath)
  1266  	fmt.Fprintf(h, "vet %q\n", b.toolID("vet"))
  1267  
  1268  	vetFlags := VetFlags
  1269  
  1270  	// In GOROOT, we enable all the vet tests during 'go test',
  1271  	// not just the high-confidence subset. This gets us extra
  1272  	// checking for the standard library (at some compliance cost)
  1273  	// and helps us gain experience about how well the checks
  1274  	// work, to help decide which should be turned on by default.
  1275  	// The command-line still wins.
  1276  	//
  1277  	// Note that this flag change applies even when running vet as
  1278  	// a dependency of vetting a package outside std.
  1279  	// (Otherwise we'd have to introduce a whole separate
  1280  	// space of "vet fmt as a dependency of a std top-level vet"
  1281  	// versus "vet fmt as a dependency of a non-std top-level vet".)
  1282  	// This is OK as long as the packages that are farther down the
  1283  	// dependency tree turn on *more* analysis, as here.
  1284  	// (The unsafeptr check does not write any facts for use by
  1285  	// later vet runs, nor does unreachable.)
  1286  	if a.Package.Goroot && !VetExplicit && VetTool == "" {
  1287  		// Turn off -unsafeptr checks.
  1288  		// There's too much unsafe.Pointer code
  1289  		// that vet doesn't like in low-level packages
  1290  		// like runtime, sync, and reflect.
  1291  		// Note that $GOROOT/src/buildall.bash
  1292  		// does the same
  1293  		// and should be updated if these flags are
  1294  		// changed here.
  1295  		vetFlags = []string{"-unsafeptr=false"}
  1296  
  1297  		// Also turn off -unreachable checks during go test.
  1298  		// During testing it is very common to make changes
  1299  		// like hard-coded forced returns or panics that make
  1300  		// code unreachable. It's unreasonable to insist on files
  1301  		// not having any unreachable code during "go test".
  1302  		// (buildall.bash still has -unreachable enabled
  1303  		// for the overall whole-tree scan.)
  1304  		if cfg.CmdName == "test" {
  1305  			vetFlags = append(vetFlags, "-unreachable=false")
  1306  		}
  1307  	}
  1308  
  1309  	// Note: We could decide that vet should compute export data for
  1310  	// all analyses, in which case we don't need to include the flags here.
  1311  	// But that would mean that if an analysis causes problems like
  1312  	// unexpected crashes there would be no way to turn it off.
  1313  	// It seems better to let the flags disable export analysis too.
  1314  	fmt.Fprintf(h, "vetflags %q\n", vetFlags)
  1315  
  1316  	fmt.Fprintf(h, "pkg %q\n", a.Deps[0].actionID)
  1317  	for _, a1 := range a.Deps {
  1318  		if a1.Mode == "vet" && a1.built != "" {
  1319  			fmt.Fprintf(h, "vetout %q %s\n", a1.Package.ImportPath, b.fileHash(a1.built))
  1320  			vcfg.PackageVetx[a1.Package.ImportPath] = a1.built
  1321  		}
  1322  	}
  1323  	key := cache.ActionID(h.Sum())
  1324  
  1325  	if vcfg.VetxOnly && !cfg.BuildA {
  1326  		c := cache.Default()
  1327  		if file, _, err := cache.GetFile(c, key); err == nil {
  1328  			a.built = file
  1329  			return nil
  1330  		}
  1331  	}
  1332  
  1333  	js, err := json.MarshalIndent(vcfg, "", "\t")
  1334  	if err != nil {
  1335  		return fmt.Errorf("internal error marshaling vet config: %v", err)
  1336  	}
  1337  	js = append(js, '\n')
  1338  	if err := sh.writeFile(a.Objdir+"vet.cfg", js); err != nil {
  1339  		return err
  1340  	}
  1341  
  1342  	// TODO(rsc): Why do we pass $GCCGO to go vet?
  1343  	env := b.cCompilerEnv()
  1344  	if cfg.BuildToolchainName == "gccgo" {
  1345  		env = append(env, "GCCGO="+BuildToolchain.compiler())
  1346  	}
  1347  
  1348  	p := a.Package
  1349  	tool := VetTool
  1350  	if tool == "" {
  1351  		tool = base.Tool("vet")
  1352  	}
  1353  	runErr := sh.run(p.Dir, p.ImportPath, env, cfg.BuildToolexec, tool, vetFlags, a.Objdir+"vet.cfg")
  1354  
  1355  	// If vet wrote export data, save it for input to future vets.
  1356  	if f, err := os.Open(vcfg.VetxOutput); err == nil {
  1357  		a.built = vcfg.VetxOutput
  1358  		cache.Default().Put(key, f)
  1359  		f.Close()
  1360  	}
  1361  
  1362  	return runErr
  1363  }
  1364  
  1365  // linkActionID computes the action ID for a link action.
  1366  func (b *Builder) linkActionID(a *Action) cache.ActionID {
  1367  	p := a.Package
  1368  	h := cache.NewHash("link " + p.ImportPath)
  1369  
  1370  	// Toolchain-independent configuration.
  1371  	fmt.Fprintf(h, "link\n")
  1372  	fmt.Fprintf(h, "buildmode %s goos %s goarch %s\n", cfg.BuildBuildmode, cfg.Goos, cfg.Goarch)
  1373  	fmt.Fprintf(h, "import %q\n", p.ImportPath)
  1374  	fmt.Fprintf(h, "omitdebug %v standard %v local %v prefix %q\n", p.Internal.OmitDebug, p.Standard, p.Internal.Local, p.Internal.LocalPrefix)
  1375  	if cfg.BuildTrimpath {
  1376  		fmt.Fprintln(h, "trimpath")
  1377  	}
  1378  
  1379  	// Toolchain-dependent configuration, shared with b.linkSharedActionID.
  1380  	b.printLinkerConfig(h, p)
  1381  
  1382  	// Input files.
  1383  	for _, a1 := range a.Deps {
  1384  		p1 := a1.Package
  1385  		if p1 != nil {
  1386  			if a1.built != "" || a1.buildID != "" {
  1387  				buildID := a1.buildID
  1388  				if buildID == "" {
  1389  					buildID = b.buildID(a1.built)
  1390  				}
  1391  				fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(buildID))
  1392  			}
  1393  			// Because we put package main's full action ID into the binary's build ID,
  1394  			// we must also put the full action ID into the binary's action ID hash.
  1395  			if p1.Name == "main" {
  1396  				fmt.Fprintf(h, "packagemain %s\n", a1.buildID)
  1397  			}
  1398  			if p1.Shlib != "" {
  1399  				fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib)))
  1400  			}
  1401  		}
  1402  	}
  1403  
  1404  	return h.Sum()
  1405  }
  1406  
  1407  // printLinkerConfig prints the linker config into the hash h,
  1408  // as part of the computation of a linker-related action ID.
  1409  func (b *Builder) printLinkerConfig(h io.Writer, p *load.Package) {
  1410  	switch cfg.BuildToolchainName {
  1411  	default:
  1412  		base.Fatalf("linkActionID: unknown toolchain %q", cfg.BuildToolchainName)
  1413  
  1414  	case "gc":
  1415  		fmt.Fprintf(h, "link %s %q %s\n", b.toolID("link"), forcedLdflags, ldBuildmode)
  1416  		if p != nil {
  1417  			fmt.Fprintf(h, "linkflags %q\n", p.Internal.Ldflags)
  1418  		}
  1419  
  1420  		// GOARM, GOMIPS, etc.
  1421  		key, val, _ := cfg.GetArchEnv()
  1422  		fmt.Fprintf(h, "%s=%s\n", key, val)
  1423  
  1424  		if cfg.CleanGOEXPERIMENT != "" {
  1425  			fmt.Fprintf(h, "GOEXPERIMENT=%q\n", cfg.CleanGOEXPERIMENT)
  1426  		}
  1427  
  1428  		// The linker writes source file paths that refer to GOROOT,
  1429  		// but only if -trimpath is not specified (see [gctoolchain.ld] in gc.go).
  1430  		gorootFinal := cfg.GOROOT
  1431  		if cfg.BuildTrimpath {
  1432  			gorootFinal = ""
  1433  		}
  1434  		fmt.Fprintf(h, "GOROOT=%s\n", gorootFinal)
  1435  
  1436  		// GO_EXTLINK_ENABLED controls whether the external linker is used.
  1437  		fmt.Fprintf(h, "GO_EXTLINK_ENABLED=%s\n", cfg.Getenv("GO_EXTLINK_ENABLED"))
  1438  
  1439  		// TODO(rsc): Do cgo settings and flags need to be included?
  1440  		// Or external linker settings and flags?
  1441  
  1442  	case "gccgo":
  1443  		id, _, err := b.gccToolID(BuildToolchain.linker(), "go")
  1444  		if err != nil {
  1445  			base.Fatalf("%v", err)
  1446  		}
  1447  		fmt.Fprintf(h, "link %s %s\n", id, ldBuildmode)
  1448  		// TODO(iant): Should probably include cgo flags here.
  1449  	}
  1450  }
  1451  
  1452  // link is the action for linking a single command.
  1453  // Note that any new influence on this logic must be reported in b.linkActionID above as well.
  1454  func (b *Builder) link(ctx context.Context, a *Action) (err error) {
  1455  	if b.useCache(a, b.linkActionID(a), a.Package.Target, !b.IsCmdList) || b.IsCmdList {
  1456  		return nil
  1457  	}
  1458  	defer b.flushOutput(a)
  1459  
  1460  	sh := b.Shell(a)
  1461  	if err := sh.Mkdir(a.Objdir); err != nil {
  1462  		return err
  1463  	}
  1464  
  1465  	importcfg := a.Objdir + "importcfg.link"
  1466  	if err := b.writeLinkImportcfg(a, importcfg); err != nil {
  1467  		return err
  1468  	}
  1469  
  1470  	if err := AllowInstall(a); err != nil {
  1471  		return err
  1472  	}
  1473  
  1474  	// make target directory
  1475  	dir, _ := filepath.Split(a.Target)
  1476  	if dir != "" {
  1477  		if err := sh.Mkdir(dir); err != nil {
  1478  			return err
  1479  		}
  1480  	}
  1481  
  1482  	if err := BuildToolchain.ld(b, a, a.Target, importcfg, a.Deps[0].built); err != nil {
  1483  		return err
  1484  	}
  1485  
  1486  	// Update the binary with the final build ID.
  1487  	// But if OmitDebug is set, don't rewrite the binary, because we set OmitDebug
  1488  	// on binaries that we are going to run and then delete.
  1489  	// There's no point in doing work on such a binary.
  1490  	// Worse, opening the binary for write here makes it
  1491  	// essentially impossible to safely fork+exec due to a fundamental
  1492  	// incompatibility between ETXTBSY and threads on modern Unix systems.
  1493  	// See golang.org/issue/22220.
  1494  	// We still call updateBuildID to update a.buildID, which is important
  1495  	// for test result caching, but passing rewrite=false (final arg)
  1496  	// means we don't actually rewrite the binary, nor store the
  1497  	// result into the cache. That's probably a net win:
  1498  	// less cache space wasted on large binaries we are not likely to
  1499  	// need again. (On the other hand it does make repeated go test slower.)
  1500  	// It also makes repeated go run slower, which is a win in itself:
  1501  	// we don't want people to treat go run like a scripting environment.
  1502  	if err := b.updateBuildID(a, a.Target, !a.Package.Internal.OmitDebug); err != nil {
  1503  		return err
  1504  	}
  1505  
  1506  	a.built = a.Target
  1507  	return nil
  1508  }
  1509  
  1510  func (b *Builder) writeLinkImportcfg(a *Action, file string) error {
  1511  	// Prepare Go import cfg.
  1512  	var icfg bytes.Buffer
  1513  	for _, a1 := range a.Deps {
  1514  		p1 := a1.Package
  1515  		if p1 == nil {
  1516  			continue
  1517  		}
  1518  		fmt.Fprintf(&icfg, "packagefile %s=%s\n", p1.ImportPath, a1.built)
  1519  		if p1.Shlib != "" {
  1520  			fmt.Fprintf(&icfg, "packageshlib %s=%s\n", p1.ImportPath, p1.Shlib)
  1521  		}
  1522  	}
  1523  	info := ""
  1524  	if a.Package.Internal.BuildInfo != nil {
  1525  		info = a.Package.Internal.BuildInfo.String()
  1526  	}
  1527  	fmt.Fprintf(&icfg, "modinfo %q\n", modload.ModInfoData(info))
  1528  	return b.Shell(a).writeFile(file, icfg.Bytes())
  1529  }
  1530  
  1531  // PkgconfigCmd returns a pkg-config binary name
  1532  // defaultPkgConfig is defined in zdefaultcc.go, written by cmd/dist.
  1533  func (b *Builder) PkgconfigCmd() string {
  1534  	return envList("PKG_CONFIG", cfg.DefaultPkgConfig)[0]
  1535  }
  1536  
  1537  // splitPkgConfigOutput parses the pkg-config output into a slice of flags.
  1538  // This implements the shell quoting semantics described in
  1539  // https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02,
  1540  // except that it does not support parameter or arithmetic expansion or command
  1541  // substitution and hard-codes the <blank> delimiters instead of reading them
  1542  // from LC_LOCALE.
  1543  func splitPkgConfigOutput(out []byte) ([]string, error) {
  1544  	if len(out) == 0 {
  1545  		return nil, nil
  1546  	}
  1547  	var flags []string
  1548  	flag := make([]byte, 0, len(out))
  1549  	didQuote := false // was the current flag parsed from a quoted string?
  1550  	escaped := false  // did we just read `\` in a non-single-quoted context?
  1551  	quote := byte(0)  // what is the quote character around the current string?
  1552  
  1553  	for _, c := range out {
  1554  		if escaped {
  1555  			if quote == '"' {
  1556  				// “The <backslash> shall retain its special meaning as an escape
  1557  				// character … only when followed by one of the following characters
  1558  				// when considered special:”
  1559  				switch c {
  1560  				case '$', '`', '"', '\\', '\n':
  1561  					// Handle the escaped character normally.
  1562  				default:
  1563  					// Not an escape character after all.
  1564  					flag = append(flag, '\\', c)
  1565  					escaped = false
  1566  					continue
  1567  				}
  1568  			}
  1569  
  1570  			if c == '\n' {
  1571  				// “If a <newline> follows the <backslash>, the shell shall interpret
  1572  				// this as line continuation.”
  1573  			} else {
  1574  				flag = append(flag, c)
  1575  			}
  1576  			escaped = false
  1577  			continue
  1578  		}
  1579  
  1580  		if quote != 0 && c == quote {
  1581  			quote = 0
  1582  			continue
  1583  		}
  1584  		switch quote {
  1585  		case '\'':
  1586  			// “preserve the literal value of each character”
  1587  			flag = append(flag, c)
  1588  			continue
  1589  		case '"':
  1590  			// “preserve the literal value of all characters within the double-quotes,
  1591  			// with the exception of …”
  1592  			switch c {
  1593  			case '`', '$', '\\':
  1594  			default:
  1595  				flag = append(flag, c)
  1596  				continue
  1597  			}
  1598  		}
  1599  
  1600  		// “The application shall quote the following characters if they are to
  1601  		// represent themselves:”
  1602  		switch c {
  1603  		case '|', '&', ';', '<', '>', '(', ')', '$', '`':
  1604  			return nil, fmt.Errorf("unexpected shell character %q in pkgconf output", c)
  1605  
  1606  		case '\\':
  1607  			// “A <backslash> that is not quoted shall preserve the literal value of
  1608  			// the following character, with the exception of a <newline>.”
  1609  			escaped = true
  1610  			continue
  1611  
  1612  		case '"', '\'':
  1613  			quote = c
  1614  			didQuote = true
  1615  			continue
  1616  
  1617  		case ' ', '\t', '\n':
  1618  			if len(flag) > 0 || didQuote {
  1619  				flags = append(flags, string(flag))
  1620  			}
  1621  			flag, didQuote = flag[:0], false
  1622  			continue
  1623  		}
  1624  
  1625  		flag = append(flag, c)
  1626  	}
  1627  
  1628  	// Prefer to report a missing quote instead of a missing escape. If the string
  1629  	// is something like `"foo\`, it's ambiguous as to whether the trailing
  1630  	// backslash is really an escape at all.
  1631  	if quote != 0 {
  1632  		return nil, errors.New("unterminated quoted string in pkgconf output")
  1633  	}
  1634  	if escaped {
  1635  		return nil, errors.New("broken character escaping in pkgconf output")
  1636  	}
  1637  
  1638  	if len(flag) > 0 || didQuote {
  1639  		flags = append(flags, string(flag))
  1640  	}
  1641  	return flags, nil
  1642  }
  1643  
  1644  // Calls pkg-config if needed and returns the cflags/ldflags needed to build a's package.
  1645  func (b *Builder) getPkgConfigFlags(a *Action) (cflags, ldflags []string, err error) {
  1646  	p := a.Package
  1647  	sh := b.Shell(a)
  1648  	if pcargs := p.CgoPkgConfig; len(pcargs) > 0 {
  1649  		// pkg-config permits arguments to appear anywhere in
  1650  		// the command line. Move them all to the front, before --.
  1651  		var pcflags []string
  1652  		var pkgs []string
  1653  		for _, pcarg := range pcargs {
  1654  			if pcarg == "--" {
  1655  				// We're going to add our own "--" argument.
  1656  			} else if strings.HasPrefix(pcarg, "--") {
  1657  				pcflags = append(pcflags, pcarg)
  1658  			} else {
  1659  				pkgs = append(pkgs, pcarg)
  1660  			}
  1661  		}
  1662  		for _, pkg := range pkgs {
  1663  			if !load.SafeArg(pkg) {
  1664  				return nil, nil, fmt.Errorf("invalid pkg-config package name: %s", pkg)
  1665  			}
  1666  		}
  1667  		var out []byte
  1668  		out, err = sh.runOut(p.Dir, nil, b.PkgconfigCmd(), "--cflags", pcflags, "--", pkgs)
  1669  		if err != nil {
  1670  			desc := b.PkgconfigCmd() + " --cflags " + strings.Join(pcflags, " ") + " -- " + strings.Join(pkgs, " ")
  1671  			return nil, nil, sh.reportCmd(desc, "", out, err)
  1672  		}
  1673  		if len(out) > 0 {
  1674  			cflags, err = splitPkgConfigOutput(bytes.TrimSpace(out))
  1675  			if err != nil {
  1676  				return nil, nil, err
  1677  			}
  1678  			if err := checkCompilerFlags("CFLAGS", "pkg-config --cflags", cflags); err != nil {
  1679  				return nil, nil, err
  1680  			}
  1681  		}
  1682  		out, err = sh.runOut(p.Dir, nil, b.PkgconfigCmd(), "--libs", pcflags, "--", pkgs)
  1683  		if err != nil {
  1684  			desc := b.PkgconfigCmd() + " --libs " + strings.Join(pcflags, " ") + " -- " + strings.Join(pkgs, " ")
  1685  			return nil, nil, sh.reportCmd(desc, "", out, err)
  1686  		}
  1687  		if len(out) > 0 {
  1688  			// We need to handle path with spaces so that C:/Program\ Files can pass
  1689  			// checkLinkerFlags. Use splitPkgConfigOutput here just like we treat cflags.
  1690  			ldflags, err = splitPkgConfigOutput(bytes.TrimSpace(out))
  1691  			if err != nil {
  1692  				return nil, nil, err
  1693  			}
  1694  			if err := checkLinkerFlags("LDFLAGS", "pkg-config --libs", ldflags); err != nil {
  1695  				return nil, nil, err
  1696  			}
  1697  		}
  1698  	}
  1699  
  1700  	return
  1701  }
  1702  
  1703  func (b *Builder) installShlibname(ctx context.Context, a *Action) error {
  1704  	if err := AllowInstall(a); err != nil {
  1705  		return err
  1706  	}
  1707  
  1708  	sh := b.Shell(a)
  1709  	a1 := a.Deps[0]
  1710  	if !cfg.BuildN {
  1711  		if err := sh.Mkdir(filepath.Dir(a.Target)); err != nil {
  1712  			return err
  1713  		}
  1714  	}
  1715  	return sh.writeFile(a.Target, []byte(filepath.Base(a1.Target)+"\n"))
  1716  }
  1717  
  1718  func (b *Builder) linkSharedActionID(a *Action) cache.ActionID {
  1719  	h := cache.NewHash("linkShared")
  1720  
  1721  	// Toolchain-independent configuration.
  1722  	fmt.Fprintf(h, "linkShared\n")
  1723  	fmt.Fprintf(h, "goos %s goarch %s\n", cfg.Goos, cfg.Goarch)
  1724  
  1725  	// Toolchain-dependent configuration, shared with b.linkActionID.
  1726  	b.printLinkerConfig(h, nil)
  1727  
  1728  	// Input files.
  1729  	for _, a1 := range a.Deps {
  1730  		p1 := a1.Package
  1731  		if a1.built == "" {
  1732  			continue
  1733  		}
  1734  		if p1 != nil {
  1735  			fmt.Fprintf(h, "packagefile %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built)))
  1736  			if p1.Shlib != "" {
  1737  				fmt.Fprintf(h, "packageshlib %s=%s\n", p1.ImportPath, contentID(b.buildID(p1.Shlib)))
  1738  			}
  1739  		}
  1740  	}
  1741  	// Files named on command line are special.
  1742  	for _, a1 := range a.Deps[0].Deps {
  1743  		p1 := a1.Package
  1744  		fmt.Fprintf(h, "top %s=%s\n", p1.ImportPath, contentID(b.buildID(a1.built)))
  1745  	}
  1746  
  1747  	return h.Sum()
  1748  }
  1749  
  1750  func (b *Builder) linkShared(ctx context.Context, a *Action) (err error) {
  1751  	if b.useCache(a, b.linkSharedActionID(a), a.Target, !b.IsCmdList) || b.IsCmdList {
  1752  		return nil
  1753  	}
  1754  	defer b.flushOutput(a)
  1755  
  1756  	if err := AllowInstall(a); err != nil {
  1757  		return err
  1758  	}
  1759  
  1760  	if err := b.Shell(a).Mkdir(a.Objdir); err != nil {
  1761  		return err
  1762  	}
  1763  
  1764  	importcfg := a.Objdir + "importcfg.link"
  1765  	if err := b.writeLinkImportcfg(a, importcfg); err != nil {
  1766  		return err
  1767  	}
  1768  
  1769  	// TODO(rsc): There is a missing updateBuildID here,
  1770  	// but we have to decide where to store the build ID in these files.
  1771  	a.built = a.Target
  1772  	return BuildToolchain.ldShared(b, a, a.Deps[0].Deps, a.Target, importcfg, a.Deps)
  1773  }
  1774  
  1775  // BuildInstallFunc is the action for installing a single package or executable.
  1776  func BuildInstallFunc(b *Builder, ctx context.Context, a *Action) (err error) {
  1777  	defer func() {
  1778  		if err != nil {
  1779  			// a.Package == nil is possible for the go install -buildmode=shared
  1780  			// action that installs libmangledname.so, which corresponds to
  1781  			// a list of packages, not just one.
  1782  			sep, path := "", ""
  1783  			if a.Package != nil {
  1784  				sep, path = " ", a.Package.ImportPath
  1785  			}
  1786  			err = fmt.Errorf("go %s%s%s: %v", cfg.CmdName, sep, path, err)
  1787  		}
  1788  	}()
  1789  	sh := b.Shell(a)
  1790  
  1791  	a1 := a.Deps[0]
  1792  	a.buildID = a1.buildID
  1793  	if a.json != nil {
  1794  		a.json.BuildID = a.buildID
  1795  	}
  1796  
  1797  	// If we are using the eventual install target as an up-to-date
  1798  	// cached copy of the thing we built, then there's no need to
  1799  	// copy it into itself (and that would probably fail anyway).
  1800  	// In this case a1.built == a.Target because a1.built == p.Target,
  1801  	// so the built target is not in the a1.Objdir tree that b.cleanup(a1) removes.
  1802  	if a1.built == a.Target {
  1803  		a.built = a.Target
  1804  		if !a.buggyInstall {
  1805  			b.cleanup(a1)
  1806  		}
  1807  		// Whether we're smart enough to avoid a complete rebuild
  1808  		// depends on exactly what the staleness and rebuild algorithms
  1809  		// are, as well as potentially the state of the Go build cache.
  1810  		// We don't really want users to be able to infer (or worse start depending on)
  1811  		// those details from whether the modification time changes during
  1812  		// "go install", so do a best-effort update of the file times to make it
  1813  		// look like we rewrote a.Target even if we did not. Updating the mtime
  1814  		// may also help other mtime-based systems that depend on our
  1815  		// previous mtime updates that happened more often.
  1816  		// This is still not perfect - we ignore the error result, and if the file was
  1817  		// unwritable for some reason then pretending to have written it is also
  1818  		// confusing - but it's probably better than not doing the mtime update.
  1819  		//
  1820  		// But don't do that for the special case where building an executable
  1821  		// with -linkshared implicitly installs all its dependent libraries.
  1822  		// We want to hide that awful detail as much as possible, so don't
  1823  		// advertise it by touching the mtimes (usually the libraries are up
  1824  		// to date).
  1825  		if !a.buggyInstall && !b.IsCmdList {
  1826  			if cfg.BuildN {
  1827  				sh.ShowCmd("", "touch %s", a.Target)
  1828  			} else if err := AllowInstall(a); err == nil {
  1829  				now := time.Now()
  1830  				os.Chtimes(a.Target, now, now)
  1831  			}
  1832  		}
  1833  		return nil
  1834  	}
  1835  
  1836  	// If we're building for go list -export,
  1837  	// never install anything; just keep the cache reference.
  1838  	if b.IsCmdList {
  1839  		a.built = a1.built
  1840  		return nil
  1841  	}
  1842  	if err := AllowInstall(a); err != nil {
  1843  		return err
  1844  	}
  1845  
  1846  	if err := sh.Mkdir(a.Objdir); err != nil {
  1847  		return err
  1848  	}
  1849  
  1850  	perm := fs.FileMode(0666)
  1851  	if a1.Mode == "link" {
  1852  		switch cfg.BuildBuildmode {
  1853  		case "c-archive", "c-shared", "plugin":
  1854  		default:
  1855  			perm = 0777
  1856  		}
  1857  	}
  1858  
  1859  	// make target directory
  1860  	dir, _ := filepath.Split(a.Target)
  1861  	if dir != "" {
  1862  		if err := sh.Mkdir(dir); err != nil {
  1863  			return err
  1864  		}
  1865  	}
  1866  
  1867  	if !a.buggyInstall {
  1868  		defer b.cleanup(a1)
  1869  	}
  1870  
  1871  	return sh.moveOrCopyFile(a.Target, a1.built, perm, false)
  1872  }
  1873  
  1874  // AllowInstall returns a non-nil error if this invocation of the go command is
  1875  // allowed to install a.Target.
  1876  //
  1877  // The build of cmd/go running under its own test is forbidden from installing
  1878  // to its original GOROOT. The var is exported so it can be set by TestMain.
  1879  var AllowInstall = func(*Action) error { return nil }
  1880  
  1881  // cleanup removes a's object dir to keep the amount of
  1882  // on-disk garbage down in a large build. On an operating system
  1883  // with aggressive buffering, cleaning incrementally like
  1884  // this keeps the intermediate objects from hitting the disk.
  1885  func (b *Builder) cleanup(a *Action) {
  1886  	if !cfg.BuildWork {
  1887  		b.Shell(a).RemoveAll(a.Objdir)
  1888  	}
  1889  }
  1890  
  1891  // Install the cgo export header file, if there is one.
  1892  func (b *Builder) installHeader(ctx context.Context, a *Action) error {
  1893  	sh := b.Shell(a)
  1894  
  1895  	src := a.Objdir + "_cgo_install.h"
  1896  	if _, err := os.Stat(src); os.IsNotExist(err) {
  1897  		// If the file does not exist, there are no exported
  1898  		// functions, and we do not install anything.
  1899  		// TODO(rsc): Once we know that caching is rebuilding
  1900  		// at the right times (not missing rebuilds), here we should
  1901  		// probably delete the installed header, if any.
  1902  		if cfg.BuildX {
  1903  			sh.ShowCmd("", "# %s not created", src)
  1904  		}
  1905  		return nil
  1906  	}
  1907  
  1908  	if err := AllowInstall(a); err != nil {
  1909  		return err
  1910  	}
  1911  
  1912  	dir, _ := filepath.Split(a.Target)
  1913  	if dir != "" {
  1914  		if err := sh.Mkdir(dir); err != nil {
  1915  			return err
  1916  		}
  1917  	}
  1918  
  1919  	return sh.moveOrCopyFile(a.Target, src, 0666, true)
  1920  }
  1921  
  1922  // cover runs, in effect,
  1923  //
  1924  //	go tool cover -mode=b.coverMode -var="varName" -o dst.go src.go
  1925  func (b *Builder) cover(a *Action, dst, src string, varName string) error {
  1926  	return b.Shell(a).run(a.Objdir, "", nil,
  1927  		cfg.BuildToolexec,
  1928  		base.Tool("cover"),
  1929  		"-mode", a.Package.Internal.Cover.Mode,
  1930  		"-var", varName,
  1931  		"-o", dst,
  1932  		src)
  1933  }
  1934  
  1935  // cover2 runs, in effect,
  1936  //
  1937  //	go tool cover -pkgcfg=<config file> -mode=b.coverMode -var="varName" -o <outfiles> <infiles>
  1938  //
  1939  // Return value is an updated output files list; in addition to the
  1940  // regular outputs (instrumented source files) the cover tool also
  1941  // writes a separate file (appearing first in the list of outputs)
  1942  // that will contain coverage counters and meta-data.
  1943  func (b *Builder) cover2(a *Action, infiles, outfiles []string, varName string, mode string) ([]string, error) {
  1944  	pkgcfg := a.Objdir + "pkgcfg.txt"
  1945  	covoutputs := a.Objdir + "coveroutfiles.txt"
  1946  	odir := filepath.Dir(outfiles[0])
  1947  	cv := filepath.Join(odir, "covervars.go")
  1948  	outfiles = append([]string{cv}, outfiles...)
  1949  	if err := b.writeCoverPkgInputs(a, pkgcfg, covoutputs, outfiles); err != nil {
  1950  		return nil, err
  1951  	}
  1952  	args := []string{base.Tool("cover"),
  1953  		"-pkgcfg", pkgcfg,
  1954  		"-mode", mode,
  1955  		"-var", varName,
  1956  		"-outfilelist", covoutputs,
  1957  	}
  1958  	args = append(args, infiles...)
  1959  	if err := b.Shell(a).run(a.Objdir, "", nil,
  1960  		cfg.BuildToolexec, args); err != nil {
  1961  		return nil, err
  1962  	}
  1963  	return outfiles, nil
  1964  }
  1965  
  1966  func (b *Builder) writeCoverPkgInputs(a *Action, pconfigfile string, covoutputsfile string, outfiles []string) error {
  1967  	sh := b.Shell(a)
  1968  	p := a.Package
  1969  	p.Internal.Cover.Cfg = a.Objdir + "coveragecfg"
  1970  	pcfg := covcmd.CoverPkgConfig{
  1971  		PkgPath: p.ImportPath,
  1972  		PkgName: p.Name,
  1973  		// Note: coverage granularity is currently hard-wired to
  1974  		// 'perblock'; there isn't a way using "go build -cover" or "go
  1975  		// test -cover" to select it. This may change in the future
  1976  		// depending on user demand.
  1977  		Granularity: "perblock",
  1978  		OutConfig:   p.Internal.Cover.Cfg,
  1979  		Local:       p.Internal.Local,
  1980  	}
  1981  	if ba, ok := a.Actor.(*buildActor); ok && ba.covMetaFileName != "" {
  1982  		pcfg.EmitMetaFile = a.Objdir + ba.covMetaFileName
  1983  	}
  1984  	if a.Package.Module != nil {
  1985  		pcfg.ModulePath = a.Package.Module.Path
  1986  	}
  1987  	data, err := json.Marshal(pcfg)
  1988  	if err != nil {
  1989  		return err
  1990  	}
  1991  	data = append(data, '\n')
  1992  	if err := sh.writeFile(pconfigfile, data); err != nil {
  1993  		return err
  1994  	}
  1995  	var sb strings.Builder
  1996  	for i := range outfiles {
  1997  		fmt.Fprintf(&sb, "%s\n", outfiles[i])
  1998  	}
  1999  	return sh.writeFile(covoutputsfile, []byte(sb.String()))
  2000  }
  2001  
  2002  var objectMagic = [][]byte{
  2003  	{'!', '<', 'a', 'r', 'c', 'h', '>', '\n'}, // Package archive
  2004  	{'<', 'b', 'i', 'g', 'a', 'f', '>', '\n'}, // Package AIX big archive
  2005  	{'\x7F', 'E', 'L', 'F'},                   // ELF
  2006  	{0xFE, 0xED, 0xFA, 0xCE},                  // Mach-O big-endian 32-bit
  2007  	{0xFE, 0xED, 0xFA, 0xCF},                  // Mach-O big-endian 64-bit
  2008  	{0xCE, 0xFA, 0xED, 0xFE},                  // Mach-O little-endian 32-bit
  2009  	{0xCF, 0xFA, 0xED, 0xFE},                  // Mach-O little-endian 64-bit
  2010  	{0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00},      // PE (Windows) as generated by 6l/8l and gcc
  2011  	{0x4d, 0x5a, 0x78, 0x00, 0x01, 0x00},      // PE (Windows) as generated by llvm for dll
  2012  	{0x00, 0x00, 0x01, 0xEB},                  // Plan 9 i386
  2013  	{0x00, 0x00, 0x8a, 0x97},                  // Plan 9 amd64
  2014  	{0x00, 0x00, 0x06, 0x47},                  // Plan 9 arm
  2015  	{0x00, 0x61, 0x73, 0x6D},                  // WASM
  2016  	{0x01, 0xDF},                              // XCOFF 32bit
  2017  	{0x01, 0xF7},                              // XCOFF 64bit
  2018  }
  2019  
  2020  func isObject(s string) bool {
  2021  	f, err := os.Open(s)
  2022  	if err != nil {
  2023  		return false
  2024  	}
  2025  	defer f.Close()
  2026  	buf := make([]byte, 64)
  2027  	io.ReadFull(f, buf)
  2028  	for _, magic := range objectMagic {
  2029  		if bytes.HasPrefix(buf, magic) {
  2030  			return true
  2031  		}
  2032  	}
  2033  	return false
  2034  }
  2035  
  2036  // cCompilerEnv returns environment variables to set when running the
  2037  // C compiler. This is needed to disable escape codes in clang error
  2038  // messages that confuse tools like cgo.
  2039  func (b *Builder) cCompilerEnv() []string {
  2040  	return []string{"TERM=dumb"}
  2041  }
  2042  
  2043  // mkAbs returns an absolute path corresponding to
  2044  // evaluating f in the directory dir.
  2045  // We always pass absolute paths of source files so that
  2046  // the error messages will include the full path to a file
  2047  // in need of attention.
  2048  func mkAbs(dir, f string) string {
  2049  	// Leave absolute paths alone.
  2050  	// Also, during -n mode we use the pseudo-directory $WORK
  2051  	// instead of creating an actual work directory that won't be used.
  2052  	// Leave paths beginning with $WORK alone too.
  2053  	if filepath.IsAbs(f) || strings.HasPrefix(f, "$WORK") {
  2054  		return f
  2055  	}
  2056  	return filepath.Join(dir, f)
  2057  }
  2058  
  2059  type toolchain interface {
  2060  	// gc runs the compiler in a specific directory on a set of files
  2061  	// and returns the name of the generated output file.
  2062  	gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, out []byte, err error)
  2063  	// cc runs the toolchain's C compiler in a directory on a C file
  2064  	// to produce an output file.
  2065  	cc(b *Builder, a *Action, ofile, cfile string) error
  2066  	// asm runs the assembler in a specific directory on specific files
  2067  	// and returns a list of named output files.
  2068  	asm(b *Builder, a *Action, sfiles []string) ([]string, error)
  2069  	// symabis scans the symbol ABIs from sfiles and returns the
  2070  	// path to the output symbol ABIs file, or "" if none.
  2071  	symabis(b *Builder, a *Action, sfiles []string) (string, error)
  2072  	// pack runs the archive packer in a specific directory to create
  2073  	// an archive from a set of object files.
  2074  	// typically it is run in the object directory.
  2075  	pack(b *Builder, a *Action, afile string, ofiles []string) error
  2076  	// ld runs the linker to create an executable starting at mainpkg.
  2077  	ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error
  2078  	// ldShared runs the linker to create a shared library containing the pkgs built by toplevelactions
  2079  	ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error
  2080  
  2081  	compiler() string
  2082  	linker() string
  2083  }
  2084  
  2085  type noToolchain struct{}
  2086  
  2087  func noCompiler() error {
  2088  	log.Fatalf("unknown compiler %q", cfg.BuildContext.Compiler)
  2089  	return nil
  2090  }
  2091  
  2092  func (noToolchain) compiler() string {
  2093  	noCompiler()
  2094  	return ""
  2095  }
  2096  
  2097  func (noToolchain) linker() string {
  2098  	noCompiler()
  2099  	return ""
  2100  }
  2101  
  2102  func (noToolchain) gc(b *Builder, a *Action, archive string, importcfg, embedcfg []byte, symabis string, asmhdr bool, pgoProfile string, gofiles []string) (ofile string, out []byte, err error) {
  2103  	return "", nil, noCompiler()
  2104  }
  2105  
  2106  func (noToolchain) asm(b *Builder, a *Action, sfiles []string) ([]string, error) {
  2107  	return nil, noCompiler()
  2108  }
  2109  
  2110  func (noToolchain) symabis(b *Builder, a *Action, sfiles []string) (string, error) {
  2111  	return "", noCompiler()
  2112  }
  2113  
  2114  func (noToolchain) pack(b *Builder, a *Action, afile string, ofiles []string) error {
  2115  	return noCompiler()
  2116  }
  2117  
  2118  func (noToolchain) ld(b *Builder, root *Action, targetPath, importcfg, mainpkg string) error {
  2119  	return noCompiler()
  2120  }
  2121  
  2122  func (noToolchain) ldShared(b *Builder, root *Action, toplevelactions []*Action, targetPath, importcfg string, allactions []*Action) error {
  2123  	return noCompiler()
  2124  }
  2125  
  2126  func (noToolchain) cc(b *Builder, a *Action, ofile, cfile string) error {
  2127  	return noCompiler()
  2128  }
  2129  
  2130  // gcc runs the gcc C compiler to create an object from a single C file.
  2131  func (b *Builder) gcc(a *Action, workdir, out string, flags []string, cfile string) error {
  2132  	p := a.Package
  2133  	return b.ccompile(a, out, flags, cfile, b.GccCmd(p.Dir, workdir))
  2134  }
  2135  
  2136  // gxx runs the g++ C++ compiler to create an object from a single C++ file.
  2137  func (b *Builder) gxx(a *Action, workdir, out string, flags []string, cxxfile string) error {
  2138  	p := a.Package
  2139  	return b.ccompile(a, out, flags, cxxfile, b.GxxCmd(p.Dir, workdir))
  2140  }
  2141  
  2142  // gfortran runs the gfortran Fortran compiler to create an object from a single Fortran file.
  2143  func (b *Builder) gfortran(a *Action, workdir, out string, flags []string, ffile string) error {
  2144  	p := a.Package
  2145  	return b.ccompile(a, out, flags, ffile, b.gfortranCmd(p.Dir, workdir))
  2146  }
  2147  
  2148  // ccompile runs the given C or C++ compiler and creates an object from a single source file.
  2149  func (b *Builder) ccompile(a *Action, outfile string, flags []string, file string, compiler []string) error {
  2150  	p := a.Package
  2151  	sh := b.Shell(a)
  2152  	file = mkAbs(p.Dir, file)
  2153  	outfile = mkAbs(p.Dir, outfile)
  2154  
  2155  	// Elide source directory paths if -trimpath is set.
  2156  	// This is needed for source files (e.g., a .c file in a package directory).
  2157  	// TODO(golang.org/issue/36072): cgo also generates files with #line
  2158  	// directives pointing to the source directory. It should not generate those
  2159  	// when -trimpath is enabled.
  2160  	if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") {
  2161  		if cfg.BuildTrimpath || p.Goroot {
  2162  			prefixMapFlag := "-fdebug-prefix-map"
  2163  			if b.gccSupportsFlag(compiler, "-ffile-prefix-map=a=b") {
  2164  				prefixMapFlag = "-ffile-prefix-map"
  2165  			}
  2166  			// Keep in sync with Action.trimpath.
  2167  			// The trimmed paths are a little different, but we need to trim in mostly the
  2168  			// same situations.
  2169  			var from, toPath string
  2170  			if m := p.Module; m == nil {
  2171  				if p.Root == "" { // command-line-arguments in GOPATH mode, maybe?
  2172  					from = p.Dir
  2173  					toPath = p.ImportPath
  2174  				} else if p.Goroot {
  2175  					from = p.Root
  2176  					toPath = "GOROOT"
  2177  				} else {
  2178  					from = p.Root
  2179  					toPath = "GOPATH"
  2180  				}
  2181  			} else if m.Dir == "" {
  2182  				// The module is in the vendor directory. Replace the entire vendor
  2183  				// directory path, because the module's Dir is not filled in.
  2184  				from = modload.VendorDir()
  2185  				toPath = "vendor"
  2186  			} else {
  2187  				from = m.Dir
  2188  				toPath = m.Path
  2189  				if m.Version != "" {
  2190  					toPath += "@" + m.Version
  2191  				}
  2192  			}
  2193  			// -fdebug-prefix-map (or -ffile-prefix-map) requires an absolute "to"
  2194  			// path (or it joins the path  with the working directory). Pick something
  2195  			// that makes sense for the target platform.
  2196  			var to string
  2197  			if cfg.BuildContext.GOOS == "windows" {
  2198  				to = filepath.Join(`\\_\_`, toPath)
  2199  			} else {
  2200  				to = filepath.Join("/_", toPath)
  2201  			}
  2202  			flags = append(slices.Clip(flags), prefixMapFlag+"="+from+"="+to)
  2203  		}
  2204  	}
  2205  
  2206  	// Tell gcc to not insert truly random numbers into the build process
  2207  	// this ensures LTO won't create random numbers for symbols.
  2208  	if b.gccSupportsFlag(compiler, "-frandom-seed=1") {
  2209  		flags = append(flags, "-frandom-seed="+buildid.HashToString(a.actionID))
  2210  	}
  2211  
  2212  	overlayPath := file
  2213  	if p, ok := a.nonGoOverlay[overlayPath]; ok {
  2214  		overlayPath = p
  2215  	}
  2216  	output, err := sh.runOut(filepath.Dir(overlayPath), b.cCompilerEnv(), compiler, flags, "-o", outfile, "-c", filepath.Base(overlayPath))
  2217  
  2218  	// On FreeBSD 11, when we pass -g to clang 3.8 it
  2219  	// invokes its internal assembler with -dwarf-version=2.
  2220  	// When it sees .section .note.GNU-stack, it warns
  2221  	// "DWARF2 only supports one section per compilation unit".
  2222  	// This warning makes no sense, since the section is empty,
  2223  	// but it confuses people.
  2224  	// We work around the problem by detecting the warning
  2225  	// and dropping -g and trying again.
  2226  	if bytes.Contains(output, []byte("DWARF2 only supports one section per compilation unit")) {
  2227  		newFlags := make([]string, 0, len(flags))
  2228  		for _, f := range flags {
  2229  			if !strings.HasPrefix(f, "-g") {
  2230  				newFlags = append(newFlags, f)
  2231  			}
  2232  		}
  2233  		if len(newFlags) < len(flags) {
  2234  			return b.ccompile(a, outfile, newFlags, file, compiler)
  2235  		}
  2236  	}
  2237  
  2238  	if len(output) > 0 && err == nil && os.Getenv("GO_BUILDER_NAME") != "" {
  2239  		output = append(output, "C compiler warning promoted to error on Go builders\n"...)
  2240  		err = errors.New("warning promoted to error")
  2241  	}
  2242  
  2243  	return sh.reportCmd("", "", output, err)
  2244  }
  2245  
  2246  // gccld runs the gcc linker to create an executable from a set of object files.
  2247  func (b *Builder) gccld(a *Action, objdir, outfile string, flags []string, objs []string) error {
  2248  	p := a.Package
  2249  	sh := b.Shell(a)
  2250  	var cmd []string
  2251  	if len(p.CXXFiles) > 0 || len(p.SwigCXXFiles) > 0 {
  2252  		cmd = b.GxxCmd(p.Dir, objdir)
  2253  	} else {
  2254  		cmd = b.GccCmd(p.Dir, objdir)
  2255  	}
  2256  
  2257  	cmdargs := []any{cmd, "-o", outfile, objs, flags}
  2258  	_, err := sh.runOut(base.Cwd(), b.cCompilerEnv(), cmdargs...)
  2259  
  2260  	// Note that failure is an expected outcome here, so we report output only
  2261  	// in debug mode and don't report the error.
  2262  	if cfg.BuildN || cfg.BuildX {
  2263  		saw := "succeeded"
  2264  		if err != nil {
  2265  			saw = "failed"
  2266  		}
  2267  		sh.ShowCmd("", "%s # test for internal linking errors (%s)", joinUnambiguously(str.StringList(cmdargs...)), saw)
  2268  	}
  2269  
  2270  	return err
  2271  }
  2272  
  2273  // GccCmd returns a gcc command line prefix
  2274  // defaultCC is defined in zdefaultcc.go, written by cmd/dist.
  2275  func (b *Builder) GccCmd(incdir, workdir string) []string {
  2276  	return b.compilerCmd(b.ccExe(), incdir, workdir)
  2277  }
  2278  
  2279  // GxxCmd returns a g++ command line prefix
  2280  // defaultCXX is defined in zdefaultcc.go, written by cmd/dist.
  2281  func (b *Builder) GxxCmd(incdir, workdir string) []string {
  2282  	return b.compilerCmd(b.cxxExe(), incdir, workdir)
  2283  }
  2284  
  2285  // gfortranCmd returns a gfortran command line prefix.
  2286  func (b *Builder) gfortranCmd(incdir, workdir string) []string {
  2287  	return b.compilerCmd(b.fcExe(), incdir, workdir)
  2288  }
  2289  
  2290  // ccExe returns the CC compiler setting without all the extra flags we add implicitly.
  2291  func (b *Builder) ccExe() []string {
  2292  	return envList("CC", cfg.DefaultCC(cfg.Goos, cfg.Goarch))
  2293  }
  2294  
  2295  // cxxExe returns the CXX compiler setting without all the extra flags we add implicitly.
  2296  func (b *Builder) cxxExe() []string {
  2297  	return envList("CXX", cfg.DefaultCXX(cfg.Goos, cfg.Goarch))
  2298  }
  2299  
  2300  // fcExe returns the FC compiler setting without all the extra flags we add implicitly.
  2301  func (b *Builder) fcExe() []string {
  2302  	return envList("FC", "gfortran")
  2303  }
  2304  
  2305  // compilerCmd returns a command line prefix for the given environment
  2306  // variable and using the default command when the variable is empty.
  2307  func (b *Builder) compilerCmd(compiler []string, incdir, workdir string) []string {
  2308  	a := append(compiler, "-I", incdir)
  2309  
  2310  	// Definitely want -fPIC but on Windows gcc complains
  2311  	// "-fPIC ignored for target (all code is position independent)"
  2312  	if cfg.Goos != "windows" {
  2313  		a = append(a, "-fPIC")
  2314  	}
  2315  	a = append(a, b.gccArchArgs()...)
  2316  	// gcc-4.5 and beyond require explicit "-pthread" flag
  2317  	// for multithreading with pthread library.
  2318  	if cfg.BuildContext.CgoEnabled {
  2319  		switch cfg.Goos {
  2320  		case "windows":
  2321  			a = append(a, "-mthreads")
  2322  		default:
  2323  			a = append(a, "-pthread")
  2324  		}
  2325  	}
  2326  
  2327  	if cfg.Goos == "aix" {
  2328  		// mcmodel=large must always be enabled to allow large TOC.
  2329  		a = append(a, "-mcmodel=large")
  2330  	}
  2331  
  2332  	// disable ASCII art in clang errors, if possible
  2333  	if b.gccSupportsFlag(compiler, "-fno-caret-diagnostics") {
  2334  		a = append(a, "-fno-caret-diagnostics")
  2335  	}
  2336  	// clang is too smart about command-line arguments
  2337  	if b.gccSupportsFlag(compiler, "-Qunused-arguments") {
  2338  		a = append(a, "-Qunused-arguments")
  2339  	}
  2340  
  2341  	// zig cc passes --gc-sections to the underlying linker, which then causes
  2342  	// undefined symbol errors when compiling with cgo but without C code.
  2343  	// https://github.com/golang/go/issues/52690
  2344  	if b.gccSupportsFlag(compiler, "-Wl,--no-gc-sections") {
  2345  		a = append(a, "-Wl,--no-gc-sections")
  2346  	}
  2347  
  2348  	// disable word wrapping in error messages
  2349  	a = append(a, "-fmessage-length=0")
  2350  
  2351  	// Tell gcc not to include the work directory in object files.
  2352  	if b.gccSupportsFlag(compiler, "-fdebug-prefix-map=a=b") {
  2353  		if workdir == "" {
  2354  			workdir = b.WorkDir
  2355  		}
  2356  		workdir = strings.TrimSuffix(workdir, string(filepath.Separator))
  2357  		if b.gccSupportsFlag(compiler, "-ffile-prefix-map=a=b") {
  2358  			a = append(a, "-ffile-prefix-map="+workdir+"=/tmp/go-build")
  2359  		} else {
  2360  			a = append(a, "-fdebug-prefix-map="+workdir+"=/tmp/go-build")
  2361  		}
  2362  	}
  2363  
  2364  	// Tell gcc not to include flags in object files, which defeats the
  2365  	// point of -fdebug-prefix-map above.
  2366  	if b.gccSupportsFlag(compiler, "-gno-record-gcc-switches") {
  2367  		a = append(a, "-gno-record-gcc-switches")
  2368  	}
  2369  
  2370  	// On OS X, some of the compilers behave as if -fno-common
  2371  	// is always set, and the Mach-O linker in 6l/8l assumes this.
  2372  	// See https://golang.org/issue/3253.
  2373  	if cfg.Goos == "darwin" || cfg.Goos == "ios" {
  2374  		a = append(a, "-fno-common")
  2375  	}
  2376  
  2377  	return a
  2378  }
  2379  
  2380  // gccNoPie returns the flag to use to request non-PIE. On systems
  2381  // with PIE (position independent executables) enabled by default,
  2382  // -no-pie must be passed when doing a partial link with -Wl,-r.
  2383  // But -no-pie is not supported by all compilers, and clang spells it -nopie.
  2384  func (b *Builder) gccNoPie(linker []string) string {
  2385  	if b.gccSupportsFlag(linker, "-no-pie") {
  2386  		return "-no-pie"
  2387  	}
  2388  	if b.gccSupportsFlag(linker, "-nopie") {
  2389  		return "-nopie"
  2390  	}
  2391  	return ""
  2392  }
  2393  
  2394  // gccSupportsFlag checks to see if the compiler supports a flag.
  2395  func (b *Builder) gccSupportsFlag(compiler []string, flag string) bool {
  2396  	// We use the background shell for operations here because, while this is
  2397  	// triggered by some Action, it's not really about that Action, and often we
  2398  	// just get the results from the global cache.
  2399  	sh := b.BackgroundShell()
  2400  
  2401  	key := [2]string{compiler[0], flag}
  2402  
  2403  	// We used to write an empty C file, but that gets complicated with go
  2404  	// build -n. We tried using a file that does not exist, but that fails on
  2405  	// systems with GCC version 4.2.1; that is the last GPLv2 version of GCC,
  2406  	// so some systems have frozen on it. Now we pass an empty file on stdin,
  2407  	// which should work at least for GCC and clang.
  2408  	//
  2409  	// If the argument is "-Wl,", then it is testing the linker. In that case,
  2410  	// skip "-c". If it's not "-Wl,", then we are testing the compiler and can
  2411  	// omit the linking step with "-c".
  2412  	//
  2413  	// Using the same CFLAGS/LDFLAGS here and for building the program.
  2414  
  2415  	// On the iOS builder the command
  2416  	//   $CC -Wl,--no-gc-sections -x c - -o /dev/null < /dev/null
  2417  	// is failing with:
  2418  	//   Unable to remove existing file: Invalid argument
  2419  	tmp := os.DevNull
  2420  	if runtime.GOOS == "windows" || runtime.GOOS == "ios" {
  2421  		f, err := os.CreateTemp(b.WorkDir, "")
  2422  		if err != nil {
  2423  			return false
  2424  		}
  2425  		f.Close()
  2426  		tmp = f.Name()
  2427  		defer os.Remove(tmp)
  2428  	}
  2429  
  2430  	cmdArgs := str.StringList(compiler, flag)
  2431  	if strings.HasPrefix(flag, "-Wl,") /* linker flag */ {
  2432  		ldflags, err := buildFlags("LDFLAGS", DefaultCFlags, nil, checkLinkerFlags)
  2433  		if err != nil {
  2434  			return false
  2435  		}
  2436  		cmdArgs = append(cmdArgs, ldflags...)
  2437  	} else { /* compiler flag, add "-c" */
  2438  		cflags, err := buildFlags("CFLAGS", DefaultCFlags, nil, checkCompilerFlags)
  2439  		if err != nil {
  2440  			return false
  2441  		}
  2442  		cmdArgs = append(cmdArgs, cflags...)
  2443  		cmdArgs = append(cmdArgs, "-c")
  2444  	}
  2445  
  2446  	cmdArgs = append(cmdArgs, "-x", "c", "-", "-o", tmp)
  2447  
  2448  	if cfg.BuildN {
  2449  		sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs))
  2450  		return false
  2451  	}
  2452  
  2453  	// gccCompilerID acquires b.exec, so do before acquiring lock.
  2454  	compilerID, cacheOK := b.gccCompilerID(compiler[0])
  2455  
  2456  	b.exec.Lock()
  2457  	defer b.exec.Unlock()
  2458  	if b, ok := b.flagCache[key]; ok {
  2459  		return b
  2460  	}
  2461  	if b.flagCache == nil {
  2462  		b.flagCache = make(map[[2]string]bool)
  2463  	}
  2464  
  2465  	// Look in build cache.
  2466  	var flagID cache.ActionID
  2467  	if cacheOK {
  2468  		flagID = cache.Subkey(compilerID, "gccSupportsFlag "+flag)
  2469  		if data, _, err := cache.GetBytes(cache.Default(), flagID); err == nil {
  2470  			supported := string(data) == "true"
  2471  			b.flagCache[key] = supported
  2472  			return supported
  2473  		}
  2474  	}
  2475  
  2476  	if cfg.BuildX {
  2477  		sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously(cmdArgs))
  2478  	}
  2479  	cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...)
  2480  	cmd.Dir = b.WorkDir
  2481  	cmd.Env = append(cmd.Environ(), "LC_ALL=C")
  2482  	out, _ := cmd.CombinedOutput()
  2483  	// GCC says "unrecognized command line option".
  2484  	// clang says "unknown argument".
  2485  	// tcc says "unsupported"
  2486  	// AIX says "not recognized"
  2487  	// Older versions of GCC say "unrecognised debug output level".
  2488  	// For -fsplit-stack GCC says "'-fsplit-stack' is not supported".
  2489  	supported := !bytes.Contains(out, []byte("unrecognized")) &&
  2490  		!bytes.Contains(out, []byte("unknown")) &&
  2491  		!bytes.Contains(out, []byte("unrecognised")) &&
  2492  		!bytes.Contains(out, []byte("is not supported")) &&
  2493  		!bytes.Contains(out, []byte("not recognized")) &&
  2494  		!bytes.Contains(out, []byte("unsupported"))
  2495  
  2496  	if cacheOK {
  2497  		s := "false"
  2498  		if supported {
  2499  			s = "true"
  2500  		}
  2501  		cache.PutBytes(cache.Default(), flagID, []byte(s))
  2502  	}
  2503  
  2504  	b.flagCache[key] = supported
  2505  	return supported
  2506  }
  2507  
  2508  // statString returns a string form of an os.FileInfo, for serializing and comparison.
  2509  func statString(info os.FileInfo) string {
  2510  	return fmt.Sprintf("stat %d %x %v %v\n", info.Size(), uint64(info.Mode()), info.ModTime(), info.IsDir())
  2511  }
  2512  
  2513  // gccCompilerID returns a build cache key for the current gcc,
  2514  // as identified by running 'compiler'.
  2515  // The caller can use subkeys of the key.
  2516  // Other parts of cmd/go can use the id as a hash
  2517  // of the installed compiler version.
  2518  func (b *Builder) gccCompilerID(compiler string) (id cache.ActionID, ok bool) {
  2519  	// We use the background shell for operations here because, while this is
  2520  	// triggered by some Action, it's not really about that Action, and often we
  2521  	// just get the results from the global cache.
  2522  	sh := b.BackgroundShell()
  2523  
  2524  	if cfg.BuildN {
  2525  		sh.ShowCmd(b.WorkDir, "%s || true", joinUnambiguously([]string{compiler, "--version"}))
  2526  		return cache.ActionID{}, false
  2527  	}
  2528  
  2529  	b.exec.Lock()
  2530  	defer b.exec.Unlock()
  2531  
  2532  	if id, ok := b.gccCompilerIDCache[compiler]; ok {
  2533  		return id, ok
  2534  	}
  2535  
  2536  	// We hash the compiler's full path to get a cache entry key.
  2537  	// That cache entry holds a validation description,
  2538  	// which is of the form:
  2539  	//
  2540  	//	filename \x00 statinfo \x00
  2541  	//	...
  2542  	//	compiler id
  2543  	//
  2544  	// If os.Stat of each filename matches statinfo,
  2545  	// then the entry is still valid, and we can use the
  2546  	// compiler id without any further expense.
  2547  	//
  2548  	// Otherwise, we compute a new validation description
  2549  	// and compiler id (below).
  2550  	exe, err := pathcache.LookPath(compiler)
  2551  	if err != nil {
  2552  		return cache.ActionID{}, false
  2553  	}
  2554  
  2555  	h := cache.NewHash("gccCompilerID")
  2556  	fmt.Fprintf(h, "gccCompilerID %q", exe)
  2557  	key := h.Sum()
  2558  	data, _, err := cache.GetBytes(cache.Default(), key)
  2559  	if err == nil && len(data) > len(id) {
  2560  		stats := strings.Split(string(data[:len(data)-len(id)]), "\x00")
  2561  		if len(stats)%2 != 0 {
  2562  			goto Miss
  2563  		}
  2564  		for i := 0; i+2 <= len(stats); i++ {
  2565  			info, err := os.Stat(stats[i])
  2566  			if err != nil || statString(info) != stats[i+1] {
  2567  				goto Miss
  2568  			}
  2569  		}
  2570  		copy(id[:], data[len(data)-len(id):])
  2571  		return id, true
  2572  	Miss:
  2573  	}
  2574  
  2575  	// Validation failed. Compute a new description (in buf) and compiler ID (in h).
  2576  	// For now, there are only at most two filenames in the stat information.
  2577  	// The first one is the compiler executable we invoke.
  2578  	// The second is the underlying compiler as reported by -v -###
  2579  	// (see b.gccToolID implementation in buildid.go).
  2580  	toolID, exe2, err := b.gccToolID(compiler, "c")
  2581  	if err != nil {
  2582  		return cache.ActionID{}, false
  2583  	}
  2584  
  2585  	exes := []string{exe, exe2}
  2586  	str.Uniq(&exes)
  2587  	fmt.Fprintf(h, "gccCompilerID %q %q\n", exes, toolID)
  2588  	id = h.Sum()
  2589  
  2590  	var buf bytes.Buffer
  2591  	for _, exe := range exes {
  2592  		if exe == "" {
  2593  			continue
  2594  		}
  2595  		info, err := os.Stat(exe)
  2596  		if err != nil {
  2597  			return cache.ActionID{}, false
  2598  		}
  2599  		buf.WriteString(exe)
  2600  		buf.WriteString("\x00")
  2601  		buf.WriteString(statString(info))
  2602  		buf.WriteString("\x00")
  2603  	}
  2604  	buf.Write(id[:])
  2605  
  2606  	cache.PutBytes(cache.Default(), key, buf.Bytes())
  2607  	if b.gccCompilerIDCache == nil {
  2608  		b.gccCompilerIDCache = make(map[string]cache.ActionID)
  2609  	}
  2610  	b.gccCompilerIDCache[compiler] = id
  2611  	return id, true
  2612  }
  2613  
  2614  // gccArchArgs returns arguments to pass to gcc based on the architecture.
  2615  func (b *Builder) gccArchArgs() []string {
  2616  	switch cfg.Goarch {
  2617  	case "386":
  2618  		return []string{"-m32"}
  2619  	case "amd64":
  2620  		if cfg.Goos == "darwin" {
  2621  			return []string{"-arch", "x86_64", "-m64"}
  2622  		}
  2623  		return []string{"-m64"}
  2624  	case "arm64":
  2625  		if cfg.Goos == "darwin" {
  2626  			return []string{"-arch", "arm64"}
  2627  		}
  2628  	case "arm":
  2629  		return []string{"-marm"} // not thumb
  2630  	case "s390x":
  2631  		return []string{"-m64", "-march=z196"}
  2632  	case "mips64", "mips64le":
  2633  		args := []string{"-mabi=64"}
  2634  		if cfg.GOMIPS64 == "hardfloat" {
  2635  			return append(args, "-mhard-float")
  2636  		} else if cfg.GOMIPS64 == "softfloat" {
  2637  			return append(args, "-msoft-float")
  2638  		}
  2639  	case "mips", "mipsle":
  2640  		args := []string{"-mabi=32", "-march=mips32"}
  2641  		if cfg.GOMIPS == "hardfloat" {
  2642  			return append(args, "-mhard-float", "-mfp32", "-mno-odd-spreg")
  2643  		} else if cfg.GOMIPS == "softfloat" {
  2644  			return append(args, "-msoft-float")
  2645  		}
  2646  	case "loong64":
  2647  		return []string{"-mabi=lp64d"}
  2648  	case "ppc64":
  2649  		if cfg.Goos == "aix" {
  2650  			return []string{"-maix64"}
  2651  		}
  2652  	}
  2653  	return nil
  2654  }
  2655  
  2656  // envList returns the value of the given environment variable broken
  2657  // into fields, using the default value when the variable is empty.
  2658  //
  2659  // The environment variable must be quoted correctly for
  2660  // quoted.Split. This should be done before building
  2661  // anything, for example, in BuildInit.
  2662  func envList(key, def string) []string {
  2663  	v := cfg.Getenv(key)
  2664  	if v == "" {
  2665  		v = def
  2666  	}
  2667  	args, err := quoted.Split(v)
  2668  	if err != nil {
  2669  		panic(fmt.Sprintf("could not parse environment variable %s with value %q: %v", key, v, err))
  2670  	}
  2671  	return args
  2672  }
  2673  
  2674  // CFlags returns the flags to use when invoking the C, C++ or Fortran compilers, or cgo.
  2675  func (b *Builder) CFlags(p *load.Package) (cppflags, cflags, cxxflags, fflags, ldflags []string, err error) {
  2676  	if cppflags, err = buildFlags("CPPFLAGS", "", p.CgoCPPFLAGS, checkCompilerFlags); err != nil {
  2677  		return
  2678  	}
  2679  	if cflags, err = buildFlags("CFLAGS", DefaultCFlags, p.CgoCFLAGS, checkCompilerFlags); err != nil {
  2680  		return
  2681  	}
  2682  	if cxxflags, err = buildFlags("CXXFLAGS", DefaultCFlags, p.CgoCXXFLAGS, checkCompilerFlags); err != nil {
  2683  		return
  2684  	}
  2685  	if fflags, err = buildFlags("FFLAGS", DefaultCFlags, p.CgoFFLAGS, checkCompilerFlags); err != nil {
  2686  		return
  2687  	}
  2688  	if ldflags, err = buildFlags("LDFLAGS", DefaultCFlags, p.CgoLDFLAGS, checkLinkerFlags); err != nil {
  2689  		return
  2690  	}
  2691  
  2692  	return
  2693  }
  2694  
  2695  func buildFlags(name, defaults string, fromPackage []string, check func(string, string, []string) error) ([]string, error) {
  2696  	if err := check(name, "#cgo "+name, fromPackage); err != nil {
  2697  		return nil, err
  2698  	}
  2699  	return str.StringList(envList("CGO_"+name, defaults), fromPackage), nil
  2700  }
  2701  
  2702  var cgoRe = lazyregexp.New(`[/\\:]`)
  2703  
  2704  func (b *Builder) cgo(a *Action, cgoExe, objdir string, pcCFLAGS, pcLDFLAGS, cgofiles, gccfiles, gxxfiles, mfiles, ffiles []string) (outGo, outObj []string, err error) {
  2705  	p := a.Package
  2706  	sh := b.Shell(a)
  2707  
  2708  	cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS, cgoLDFLAGS, err := b.CFlags(p)
  2709  	if err != nil {
  2710  		return nil, nil, err
  2711  	}
  2712  
  2713  	cgoCPPFLAGS = append(cgoCPPFLAGS, pcCFLAGS...)
  2714  	cgoLDFLAGS = append(cgoLDFLAGS, pcLDFLAGS...)
  2715  	// If we are compiling Objective-C code, then we need to link against libobjc
  2716  	if len(mfiles) > 0 {
  2717  		cgoLDFLAGS = append(cgoLDFLAGS, "-lobjc")
  2718  	}
  2719  
  2720  	// Likewise for Fortran, except there are many Fortran compilers.
  2721  	// Support gfortran out of the box and let others pass the correct link options
  2722  	// via CGO_LDFLAGS
  2723  	if len(ffiles) > 0 {
  2724  		fc := cfg.Getenv("FC")
  2725  		if fc == "" {
  2726  			fc = "gfortran"
  2727  		}
  2728  		if strings.Contains(fc, "gfortran") {
  2729  			cgoLDFLAGS = append(cgoLDFLAGS, "-lgfortran")
  2730  		}
  2731  	}
  2732  
  2733  	// Scrutinize CFLAGS and related for flags that might cause
  2734  	// problems if we are using internal linking (for example, use of
  2735  	// plugins, LTO, etc) by calling a helper routine that builds on
  2736  	// the existing CGO flags allow-lists. If we see anything
  2737  	// suspicious, emit a special token file "preferlinkext" (known to
  2738  	// the linker) in the object file to signal the that it should not
  2739  	// try to link internally and should revert to external linking.
  2740  	// The token we pass is a suggestion, not a mandate; if a user is
  2741  	// explicitly asking for a specific linkmode via the "-linkmode"
  2742  	// flag, the token will be ignored. NB: in theory we could ditch
  2743  	// the token approach and just pass a flag to the linker when we
  2744  	// eventually invoke it, and the linker flag could then be
  2745  	// documented (although coming up with a simple explanation of the
  2746  	// flag might be challenging). For more context see issues #58619,
  2747  	// #58620, and #58848.
  2748  	flagSources := []string{"CGO_CFLAGS", "CGO_CXXFLAGS", "CGO_FFLAGS"}
  2749  	flagLists := [][]string{cgoCFLAGS, cgoCXXFLAGS, cgoFFLAGS}
  2750  	if flagsNotCompatibleWithInternalLinking(flagSources, flagLists) {
  2751  		tokenFile := objdir + "preferlinkext"
  2752  		if err := sh.writeFile(tokenFile, nil); err != nil {
  2753  			return nil, nil, err
  2754  		}
  2755  		outObj = append(outObj, tokenFile)
  2756  	}
  2757  
  2758  	if cfg.BuildMSan {
  2759  		cgoCFLAGS = append([]string{"-fsanitize=memory"}, cgoCFLAGS...)
  2760  		cgoLDFLAGS = append([]string{"-fsanitize=memory"}, cgoLDFLAGS...)
  2761  	}
  2762  	if cfg.BuildASan {
  2763  		cgoCFLAGS = append([]string{"-fsanitize=address"}, cgoCFLAGS...)
  2764  		cgoLDFLAGS = append([]string{"-fsanitize=address"}, cgoLDFLAGS...)
  2765  	}
  2766  
  2767  	// Allows including _cgo_export.h, as well as the user's .h files,
  2768  	// from .[ch] files in the package.
  2769  	cgoCPPFLAGS = append(cgoCPPFLAGS, "-I", objdir)
  2770  
  2771  	// cgo
  2772  	// TODO: CGO_FLAGS?
  2773  	gofiles := []string{objdir + "_cgo_gotypes.go"}
  2774  	cfiles := []string{"_cgo_export.c"}
  2775  	for _, fn := range cgofiles {
  2776  		f := strings.TrimSuffix(filepath.Base(fn), ".go")
  2777  		gofiles = append(gofiles, objdir+f+".cgo1.go")
  2778  		cfiles = append(cfiles, f+".cgo2.c")
  2779  	}
  2780  
  2781  	// TODO: make cgo not depend on $GOARCH?
  2782  
  2783  	cgoflags := []string{}
  2784  	if p.Standard && p.ImportPath == "runtime/cgo" {
  2785  		cgoflags = append(cgoflags, "-import_runtime_cgo=false")
  2786  	}
  2787  	if p.Standard && (p.ImportPath == "runtime/race" || p.ImportPath == "runtime/msan" || p.ImportPath == "runtime/cgo" || p.ImportPath == "runtime/asan") {
  2788  		cgoflags = append(cgoflags, "-import_syscall=false")
  2789  	}
  2790  
  2791  	// cgoLDFLAGS, which includes p.CgoLDFLAGS, can be very long.
  2792  	// Pass it to cgo on the command line, so that we use a
  2793  	// response file if necessary.
  2794  	//
  2795  	// These flags are recorded in the generated _cgo_gotypes.go file
  2796  	// using //go:cgo_ldflag directives, the compiler records them in the
  2797  	// object file for the package, and then the Go linker passes them
  2798  	// along to the host linker. At this point in the code, cgoLDFLAGS
  2799  	// consists of the original $CGO_LDFLAGS (unchecked) and all the
  2800  	// flags put together from source code (checked).
  2801  	cgoenv := b.cCompilerEnv()
  2802  	var ldflagsOption []string
  2803  	if len(cgoLDFLAGS) > 0 {
  2804  		flags := make([]string, len(cgoLDFLAGS))
  2805  		for i, f := range cgoLDFLAGS {
  2806  			flags[i] = strconv.Quote(f)
  2807  		}
  2808  		ldflagsOption = []string{"-ldflags=" + strings.Join(flags, " ")}
  2809  
  2810  		// Remove CGO_LDFLAGS from the environment.
  2811  		cgoenv = append(cgoenv, "CGO_LDFLAGS=")
  2812  	}
  2813  
  2814  	if cfg.BuildToolchainName == "gccgo" {
  2815  		if b.gccSupportsFlag([]string{BuildToolchain.compiler()}, "-fsplit-stack") {
  2816  			cgoCFLAGS = append(cgoCFLAGS, "-fsplit-stack")
  2817  		}
  2818  		cgoflags = append(cgoflags, "-gccgo")
  2819  		if pkgpath := gccgoPkgpath(p); pkgpath != "" {
  2820  			cgoflags = append(cgoflags, "-gccgopkgpath="+pkgpath)
  2821  		}
  2822  		if !BuildToolchain.(gccgoToolchain).supportsCgoIncomplete(b, a) {
  2823  			cgoflags = append(cgoflags, "-gccgo_define_cgoincomplete")
  2824  		}
  2825  	}
  2826  
  2827  	switch cfg.BuildBuildmode {
  2828  	case "c-archive", "c-shared":
  2829  		// Tell cgo that if there are any exported functions
  2830  		// it should generate a header file that C code can
  2831  		// #include.
  2832  		cgoflags = append(cgoflags, "-exportheader="+objdir+"_cgo_install.h")
  2833  	}
  2834  
  2835  	// Rewrite overlaid paths in cgo files.
  2836  	// cgo adds //line and #line pragmas in generated files with these paths.
  2837  	var trimpath []string
  2838  	for i := range cgofiles {
  2839  		path := mkAbs(p.Dir, cgofiles[i])
  2840  		if opath, ok := fsys.OverlayPath(path); ok {
  2841  			cgofiles[i] = opath
  2842  			trimpath = append(trimpath, opath+"=>"+path)
  2843  		}
  2844  	}
  2845  	if len(trimpath) > 0 {
  2846  		cgoflags = append(cgoflags, "-trimpath", strings.Join(trimpath, ";"))
  2847  	}
  2848  
  2849  	if err := sh.run(p.Dir, p.ImportPath, cgoenv, cfg.BuildToolexec, cgoExe, "-objdir", objdir, "-importpath", p.ImportPath, cgoflags, ldflagsOption, "--", cgoCPPFLAGS, cgoCFLAGS, cgofiles); err != nil {
  2850  		return nil, nil, err
  2851  	}
  2852  	outGo = append(outGo, gofiles...)
  2853  
  2854  	// Use sequential object file names to keep them distinct
  2855  	// and short enough to fit in the .a header file name slots.
  2856  	// We no longer collect them all into _all.o, and we'd like
  2857  	// tools to see both the .o suffix and unique names, so
  2858  	// we need to make them short enough not to be truncated
  2859  	// in the final archive.
  2860  	oseq := 0
  2861  	nextOfile := func() string {
  2862  		oseq++
  2863  		return objdir + fmt.Sprintf("_x%03d.o", oseq)
  2864  	}
  2865  
  2866  	// gcc
  2867  	cflags := str.StringList(cgoCPPFLAGS, cgoCFLAGS)
  2868  	for _, cfile := range cfiles {
  2869  		ofile := nextOfile()
  2870  		if err := b.gcc(a, a.Objdir, ofile, cflags, objdir+cfile); err != nil {
  2871  			return nil, nil, err
  2872  		}
  2873  		outObj = append(outObj, ofile)
  2874  	}
  2875  
  2876  	for _, file := range gccfiles {
  2877  		ofile := nextOfile()
  2878  		if err := b.gcc(a, a.Objdir, ofile, cflags, file); err != nil {
  2879  			return nil, nil, err
  2880  		}
  2881  		outObj = append(outObj, ofile)
  2882  	}
  2883  
  2884  	cxxflags := str.StringList(cgoCPPFLAGS, cgoCXXFLAGS)
  2885  	for _, file := range gxxfiles {
  2886  		ofile := nextOfile()
  2887  		if err := b.gxx(a, a.Objdir, ofile, cxxflags, file); err != nil {
  2888  			return nil, nil, err
  2889  		}
  2890  		outObj = append(outObj, ofile)
  2891  	}
  2892  
  2893  	for _, file := range mfiles {
  2894  		ofile := nextOfile()
  2895  		if err := b.gcc(a, a.Objdir, ofile, cflags, file); err != nil {
  2896  			return nil, nil, err
  2897  		}
  2898  		outObj = append(outObj, ofile)
  2899  	}
  2900  
  2901  	fflags := str.StringList(cgoCPPFLAGS, cgoFFLAGS)
  2902  	for _, file := range ffiles {
  2903  		ofile := nextOfile()
  2904  		if err := b.gfortran(a, a.Objdir, ofile, fflags, file); err != nil {
  2905  			return nil, nil, err
  2906  		}
  2907  		outObj = append(outObj, ofile)
  2908  	}
  2909  
  2910  	switch cfg.BuildToolchainName {
  2911  	case "gc":
  2912  		importGo := objdir + "_cgo_import.go"
  2913  		dynOutGo, dynOutObj, err := b.dynimport(a, objdir, importGo, cgoExe, cflags, cgoLDFLAGS, outObj)
  2914  		if err != nil {
  2915  			return nil, nil, err
  2916  		}
  2917  		if dynOutGo != "" {
  2918  			outGo = append(outGo, dynOutGo)
  2919  		}
  2920  		if dynOutObj != "" {
  2921  			outObj = append(outObj, dynOutObj)
  2922  		}
  2923  
  2924  	case "gccgo":
  2925  		defunC := objdir + "_cgo_defun.c"
  2926  		defunObj := objdir + "_cgo_defun.o"
  2927  		if err := BuildToolchain.cc(b, a, defunObj, defunC); err != nil {
  2928  			return nil, nil, err
  2929  		}
  2930  		outObj = append(outObj, defunObj)
  2931  
  2932  	default:
  2933  		noCompiler()
  2934  	}
  2935  
  2936  	// Double check the //go:cgo_ldflag comments in the generated files.
  2937  	// The compiler only permits such comments in files whose base name
  2938  	// starts with "_cgo_". Make sure that the comments in those files
  2939  	// are safe. This is a backstop against people somehow smuggling
  2940  	// such a comment into a file generated by cgo.
  2941  	if cfg.BuildToolchainName == "gc" && !cfg.BuildN {
  2942  		var flags []string
  2943  		for _, f := range outGo {
  2944  			if !strings.HasPrefix(filepath.Base(f), "_cgo_") {
  2945  				continue
  2946  			}
  2947  
  2948  			src, err := os.ReadFile(f)
  2949  			if err != nil {
  2950  				return nil, nil, err
  2951  			}
  2952  
  2953  			const cgoLdflag = "//go:cgo_ldflag"
  2954  			idx := bytes.Index(src, []byte(cgoLdflag))
  2955  			for idx >= 0 {
  2956  				// We are looking at //go:cgo_ldflag.
  2957  				// Find start of line.
  2958  				start := bytes.LastIndex(src[:idx], []byte("\n"))
  2959  				if start == -1 {
  2960  					start = 0
  2961  				}
  2962  
  2963  				// Find end of line.
  2964  				end := bytes.Index(src[idx:], []byte("\n"))
  2965  				if end == -1 {
  2966  					end = len(src)
  2967  				} else {
  2968  					end += idx
  2969  				}
  2970  
  2971  				// Check for first line comment in line.
  2972  				// We don't worry about /* */ comments,
  2973  				// which normally won't appear in files
  2974  				// generated by cgo.
  2975  				commentStart := bytes.Index(src[start:], []byte("//"))
  2976  				commentStart += start
  2977  				// If that line comment is //go:cgo_ldflag,
  2978  				// it's a match.
  2979  				if bytes.HasPrefix(src[commentStart:], []byte(cgoLdflag)) {
  2980  					// Pull out the flag, and unquote it.
  2981  					// This is what the compiler does.
  2982  					flag := string(src[idx+len(cgoLdflag) : end])
  2983  					flag = strings.TrimSpace(flag)
  2984  					flag = strings.Trim(flag, `"`)
  2985  					flags = append(flags, flag)
  2986  				}
  2987  				src = src[end:]
  2988  				idx = bytes.Index(src, []byte(cgoLdflag))
  2989  			}
  2990  		}
  2991  
  2992  		// We expect to find the contents of cgoLDFLAGS in flags.
  2993  		if len(cgoLDFLAGS) > 0 {
  2994  		outer:
  2995  			for i := range flags {
  2996  				for j, f := range cgoLDFLAGS {
  2997  					if f != flags[i+j] {
  2998  						continue outer
  2999  					}
  3000  				}
  3001  				flags = append(flags[:i], flags[i+len(cgoLDFLAGS):]...)
  3002  				break
  3003  			}
  3004  		}
  3005  
  3006  		if err := checkLinkerFlags("LDFLAGS", "go:cgo_ldflag", flags); err != nil {
  3007  			return nil, nil, err
  3008  		}
  3009  	}
  3010  
  3011  	return outGo, outObj, nil
  3012  }
  3013  
  3014  // flagsNotCompatibleWithInternalLinking scans the list of cgo
  3015  // compiler flags (C/C++/Fortran) looking for flags that might cause
  3016  // problems if the build in question uses internal linking. The
  3017  // primary culprits are use of plugins or use of LTO, but we err on
  3018  // the side of caution, supporting only those flags that are on the
  3019  // allow-list for safe flags from security perspective. Return is TRUE
  3020  // if a sensitive flag is found, FALSE otherwise.
  3021  func flagsNotCompatibleWithInternalLinking(sourceList []string, flagListList [][]string) bool {
  3022  	for i := range sourceList {
  3023  		sn := sourceList[i]
  3024  		fll := flagListList[i]
  3025  		if err := checkCompilerFlagsForInternalLink(sn, sn, fll); err != nil {
  3026  			return true
  3027  		}
  3028  	}
  3029  	return false
  3030  }
  3031  
  3032  // dynimport creates a Go source file named importGo containing
  3033  // //go:cgo_import_dynamic directives for each symbol or library
  3034  // dynamically imported by the object files outObj.
  3035  // dynOutGo, if not empty, is a new Go file to build as part of the package.
  3036  // dynOutObj, if not empty, is a new file to add to the generated archive.
  3037  func (b *Builder) dynimport(a *Action, objdir, importGo, cgoExe string, cflags, cgoLDFLAGS, outObj []string) (dynOutGo, dynOutObj string, err error) {
  3038  	p := a.Package
  3039  	sh := b.Shell(a)
  3040  
  3041  	cfile := objdir + "_cgo_main.c"
  3042  	ofile := objdir + "_cgo_main.o"
  3043  	if err := b.gcc(a, objdir, ofile, cflags, cfile); err != nil {
  3044  		return "", "", err
  3045  	}
  3046  
  3047  	// Gather .syso files from this package and all (transitive) dependencies.
  3048  	var syso []string
  3049  	seen := make(map[*Action]bool)
  3050  	var gatherSyso func(*Action)
  3051  	gatherSyso = func(a1 *Action) {
  3052  		if seen[a1] {
  3053  			return
  3054  		}
  3055  		seen[a1] = true
  3056  		if p1 := a1.Package; p1 != nil {
  3057  			syso = append(syso, mkAbsFiles(p1.Dir, p1.SysoFiles)...)
  3058  		}
  3059  		for _, a2 := range a1.Deps {
  3060  			gatherSyso(a2)
  3061  		}
  3062  	}
  3063  	gatherSyso(a)
  3064  	sort.Strings(syso)
  3065  	str.Uniq(&syso)
  3066  	linkobj := str.StringList(ofile, outObj, syso)
  3067  	dynobj := objdir + "_cgo_.o"
  3068  
  3069  	ldflags := cgoLDFLAGS
  3070  	if (cfg.Goarch == "arm" && cfg.Goos == "linux") || cfg.Goos == "android" {
  3071  		if !slices.Contains(ldflags, "-no-pie") {
  3072  			// we need to use -pie for Linux/ARM to get accurate imported sym (added in https://golang.org/cl/5989058)
  3073  			// this seems to be outdated, but we don't want to break existing builds depending on this (Issue 45940)
  3074  			ldflags = append(ldflags, "-pie")
  3075  		}
  3076  		if slices.Contains(ldflags, "-pie") && slices.Contains(ldflags, "-static") {
  3077  			// -static -pie doesn't make sense, and causes link errors.
  3078  			// Issue 26197.
  3079  			n := make([]string, 0, len(ldflags)-1)
  3080  			for _, flag := range ldflags {
  3081  				if flag != "-static" {
  3082  					n = append(n, flag)
  3083  				}
  3084  			}
  3085  			ldflags = n
  3086  		}
  3087  	}
  3088  	if err := b.gccld(a, objdir, dynobj, ldflags, linkobj); err != nil {
  3089  		// We only need this information for internal linking.
  3090  		// If this link fails, mark the object as requiring
  3091  		// external linking. This link can fail for things like
  3092  		// syso files that have unexpected dependencies.
  3093  		// cmd/link explicitly looks for the name "dynimportfail".
  3094  		// See issue #52863.
  3095  		fail := objdir + "dynimportfail"
  3096  		if err := sh.writeFile(fail, nil); err != nil {
  3097  			return "", "", err
  3098  		}
  3099  		return "", fail, nil
  3100  	}
  3101  
  3102  	// cgo -dynimport
  3103  	var cgoflags []string
  3104  	if p.Standard && p.ImportPath == "runtime/cgo" {
  3105  		cgoflags = []string{"-dynlinker"} // record path to dynamic linker
  3106  	}
  3107  	err = sh.run(base.Cwd(), p.ImportPath, b.cCompilerEnv(), cfg.BuildToolexec, cgoExe, "-dynpackage", p.Name, "-dynimport", dynobj, "-dynout", importGo, cgoflags)
  3108  	if err != nil {
  3109  		return "", "", err
  3110  	}
  3111  	return importGo, "", nil
  3112  }
  3113  
  3114  // Run SWIG on all SWIG input files.
  3115  // TODO: Don't build a shared library, once SWIG emits the necessary
  3116  // pragmas for external linking.
  3117  func (b *Builder) swig(a *Action, objdir string, pcCFLAGS []string) (outGo, outC, outCXX []string, err error) {
  3118  	p := a.Package
  3119  
  3120  	if err := b.swigVersionCheck(); err != nil {
  3121  		return nil, nil, nil, err
  3122  	}
  3123  
  3124  	intgosize, err := b.swigIntSize(objdir)
  3125  	if err != nil {
  3126  		return nil, nil, nil, err
  3127  	}
  3128  
  3129  	for _, f := range p.SwigFiles {
  3130  		goFile, cFile, err := b.swigOne(a, f, objdir, pcCFLAGS, false, intgosize)
  3131  		if err != nil {
  3132  			return nil, nil, nil, err
  3133  		}
  3134  		if goFile != "" {
  3135  			outGo = append(outGo, goFile)
  3136  		}
  3137  		if cFile != "" {
  3138  			outC = append(outC, cFile)
  3139  		}
  3140  	}
  3141  	for _, f := range p.SwigCXXFiles {
  3142  		goFile, cxxFile, err := b.swigOne(a, f, objdir, pcCFLAGS, true, intgosize)
  3143  		if err != nil {
  3144  			return nil, nil, nil, err
  3145  		}
  3146  		if goFile != "" {
  3147  			outGo = append(outGo, goFile)
  3148  		}
  3149  		if cxxFile != "" {
  3150  			outCXX = append(outCXX, cxxFile)
  3151  		}
  3152  	}
  3153  	return outGo, outC, outCXX, nil
  3154  }
  3155  
  3156  // Make sure SWIG is new enough.
  3157  var (
  3158  	swigCheckOnce sync.Once
  3159  	swigCheck     error
  3160  )
  3161  
  3162  func (b *Builder) swigDoVersionCheck() error {
  3163  	sh := b.BackgroundShell()
  3164  	out, err := sh.runOut(".", nil, "swig", "-version")
  3165  	if err != nil {
  3166  		return err
  3167  	}
  3168  	re := regexp.MustCompile(`[vV]ersion +(\d+)([.]\d+)?([.]\d+)?`)
  3169  	matches := re.FindSubmatch(out)
  3170  	if matches == nil {
  3171  		// Can't find version number; hope for the best.
  3172  		return nil
  3173  	}
  3174  
  3175  	major, err := strconv.Atoi(string(matches[1]))
  3176  	if err != nil {
  3177  		// Can't find version number; hope for the best.
  3178  		return nil
  3179  	}
  3180  	const errmsg = "must have SWIG version >= 3.0.6"
  3181  	if major < 3 {
  3182  		return errors.New(errmsg)
  3183  	}
  3184  	if major > 3 {
  3185  		// 4.0 or later
  3186  		return nil
  3187  	}
  3188  
  3189  	// We have SWIG version 3.x.
  3190  	if len(matches[2]) > 0 {
  3191  		minor, err := strconv.Atoi(string(matches[2][1:]))
  3192  		if err != nil {
  3193  			return nil
  3194  		}
  3195  		if minor > 0 {
  3196  			// 3.1 or later
  3197  			return nil
  3198  		}
  3199  	}
  3200  
  3201  	// We have SWIG version 3.0.x.
  3202  	if len(matches[3]) > 0 {
  3203  		patch, err := strconv.Atoi(string(matches[3][1:]))
  3204  		if err != nil {
  3205  			return nil
  3206  		}
  3207  		if patch < 6 {
  3208  			// Before 3.0.6.
  3209  			return errors.New(errmsg)
  3210  		}
  3211  	}
  3212  
  3213  	return nil
  3214  }
  3215  
  3216  func (b *Builder) swigVersionCheck() error {
  3217  	swigCheckOnce.Do(func() {
  3218  		swigCheck = b.swigDoVersionCheck()
  3219  	})
  3220  	return swigCheck
  3221  }
  3222  
  3223  // Find the value to pass for the -intgosize option to swig.
  3224  var (
  3225  	swigIntSizeOnce  sync.Once
  3226  	swigIntSize      string
  3227  	swigIntSizeError error
  3228  )
  3229  
  3230  // This code fails to build if sizeof(int) <= 32
  3231  const swigIntSizeCode = `
  3232  package main
  3233  const i int = 1 << 32
  3234  `
  3235  
  3236  // Determine the size of int on the target system for the -intgosize option
  3237  // of swig >= 2.0.9. Run only once.
  3238  func (b *Builder) swigDoIntSize(objdir string) (intsize string, err error) {
  3239  	if cfg.BuildN {
  3240  		return "$INTBITS", nil
  3241  	}
  3242  	src := filepath.Join(b.WorkDir, "swig_intsize.go")
  3243  	if err = os.WriteFile(src, []byte(swigIntSizeCode), 0666); err != nil {
  3244  		return
  3245  	}
  3246  	srcs := []string{src}
  3247  
  3248  	p := load.GoFilesPackage(context.TODO(), load.PackageOpts{}, srcs)
  3249  
  3250  	if _, _, e := BuildToolchain.gc(b, &Action{Mode: "swigDoIntSize", Package: p, Objdir: objdir}, "", nil, nil, "", false, "", srcs); e != nil {
  3251  		return "32", nil
  3252  	}
  3253  	return "64", nil
  3254  }
  3255  
  3256  // Determine the size of int on the target system for the -intgosize option
  3257  // of swig >= 2.0.9.
  3258  func (b *Builder) swigIntSize(objdir string) (intsize string, err error) {
  3259  	swigIntSizeOnce.Do(func() {
  3260  		swigIntSize, swigIntSizeError = b.swigDoIntSize(objdir)
  3261  	})
  3262  	return swigIntSize, swigIntSizeError
  3263  }
  3264  
  3265  // Run SWIG on one SWIG input file.
  3266  func (b *Builder) swigOne(a *Action, file, objdir string, pcCFLAGS []string, cxx bool, intgosize string) (outGo, outC string, err error) {
  3267  	p := a.Package
  3268  	sh := b.Shell(a)
  3269  
  3270  	cgoCPPFLAGS, cgoCFLAGS, cgoCXXFLAGS, _, _, err := b.CFlags(p)
  3271  	if err != nil {
  3272  		return "", "", err
  3273  	}
  3274  
  3275  	var cflags []string
  3276  	if cxx {
  3277  		cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCXXFLAGS)
  3278  	} else {
  3279  		cflags = str.StringList(cgoCPPFLAGS, pcCFLAGS, cgoCFLAGS)
  3280  	}
  3281  
  3282  	n := 5 // length of ".swig"
  3283  	if cxx {
  3284  		n = 8 // length of ".swigcxx"
  3285  	}
  3286  	base := file[:len(file)-n]
  3287  	goFile := base + ".go"
  3288  	gccBase := base + "_wrap."
  3289  	gccExt := "c"
  3290  	if cxx {
  3291  		gccExt = "cxx"
  3292  	}
  3293  
  3294  	gccgo := cfg.BuildToolchainName == "gccgo"
  3295  
  3296  	// swig
  3297  	args := []string{
  3298  		"-go",
  3299  		"-cgo",
  3300  		"-intgosize", intgosize,
  3301  		"-module", base,
  3302  		"-o", objdir + gccBase + gccExt,
  3303  		"-outdir", objdir,
  3304  	}
  3305  
  3306  	for _, f := range cflags {
  3307  		if len(f) > 3 && f[:2] == "-I" {
  3308  			args = append(args, f)
  3309  		}
  3310  	}
  3311  
  3312  	if gccgo {
  3313  		args = append(args, "-gccgo")
  3314  		if pkgpath := gccgoPkgpath(p); pkgpath != "" {
  3315  			args = append(args, "-go-pkgpath", pkgpath)
  3316  		}
  3317  	}
  3318  	if cxx {
  3319  		args = append(args, "-c++")
  3320  	}
  3321  
  3322  	out, err := sh.runOut(p.Dir, nil, "swig", args, file)
  3323  	if err != nil && (bytes.Contains(out, []byte("-intgosize")) || bytes.Contains(out, []byte("-cgo"))) {
  3324  		return "", "", errors.New("must have SWIG version >= 3.0.6")
  3325  	}
  3326  	if err := sh.reportCmd("", "", out, err); err != nil {
  3327  		return "", "", err
  3328  	}
  3329  
  3330  	// If the input was x.swig, the output is x.go in the objdir.
  3331  	// But there might be an x.go in the original dir too, and if it
  3332  	// uses cgo as well, cgo will be processing both and will
  3333  	// translate both into x.cgo1.go in the objdir, overwriting one.
  3334  	// Rename x.go to _x_swig.go to avoid this problem.
  3335  	// We ignore files in the original dir that begin with underscore
  3336  	// so _x_swig.go cannot conflict with an original file we were
  3337  	// going to compile.
  3338  	goFile = objdir + goFile
  3339  	newGoFile := objdir + "_" + base + "_swig.go"
  3340  	if cfg.BuildX || cfg.BuildN {
  3341  		sh.ShowCmd("", "mv %s %s", goFile, newGoFile)
  3342  	}
  3343  	if !cfg.BuildN {
  3344  		if err := os.Rename(goFile, newGoFile); err != nil {
  3345  			return "", "", err
  3346  		}
  3347  	}
  3348  	return newGoFile, objdir + gccBase + gccExt, nil
  3349  }
  3350  
  3351  // disableBuildID adjusts a linker command line to avoid creating a
  3352  // build ID when creating an object file rather than an executable or
  3353  // shared library. Some systems, such as Ubuntu, always add
  3354  // --build-id to every link, but we don't want a build ID when we are
  3355  // producing an object file. On some of those system a plain -r (not
  3356  // -Wl,-r) will turn off --build-id, but clang 3.0 doesn't support a
  3357  // plain -r. I don't know how to turn off --build-id when using clang
  3358  // other than passing a trailing --build-id=none. So that is what we
  3359  // do, but only on systems likely to support it, which is to say,
  3360  // systems that normally use gold or the GNU linker.
  3361  func (b *Builder) disableBuildID(ldflags []string) []string {
  3362  	switch cfg.Goos {
  3363  	case "android", "dragonfly", "linux", "netbsd":
  3364  		ldflags = append(ldflags, "-Wl,--build-id=none")
  3365  	}
  3366  	return ldflags
  3367  }
  3368  
  3369  // mkAbsFiles converts files into a list of absolute files,
  3370  // assuming they were originally relative to dir,
  3371  // and returns that new list.
  3372  func mkAbsFiles(dir string, files []string) []string {
  3373  	abs := make([]string, len(files))
  3374  	for i, f := range files {
  3375  		if !filepath.IsAbs(f) {
  3376  			f = filepath.Join(dir, f)
  3377  		}
  3378  		abs[i] = f
  3379  	}
  3380  	return abs
  3381  }
  3382  
  3383  // passLongArgsInResponseFiles modifies cmd such that, for
  3384  // certain programs, long arguments are passed in "response files", a
  3385  // file on disk with the arguments, with one arg per line. An actual
  3386  // argument starting with '@' means that the rest of the argument is
  3387  // a filename of arguments to expand.
  3388  //
  3389  // See issues 18468 (Windows) and 37768 (Darwin).
  3390  func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func()) {
  3391  	cleanup = func() {} // no cleanup by default
  3392  
  3393  	var argLen int
  3394  	for _, arg := range cmd.Args {
  3395  		argLen += len(arg)
  3396  	}
  3397  
  3398  	// If we're not approaching 32KB of args, just pass args normally.
  3399  	// (use 30KB instead to be conservative; not sure how accounting is done)
  3400  	if !useResponseFile(cmd.Path, argLen) {
  3401  		return
  3402  	}
  3403  
  3404  	tf, err := os.CreateTemp("", "args")
  3405  	if err != nil {
  3406  		log.Fatalf("error writing long arguments to response file: %v", err)
  3407  	}
  3408  	cleanup = func() { os.Remove(tf.Name()) }
  3409  	var buf bytes.Buffer
  3410  	for _, arg := range cmd.Args[1:] {
  3411  		fmt.Fprintf(&buf, "%s\n", encodeArg(arg))
  3412  	}
  3413  	if _, err := tf.Write(buf.Bytes()); err != nil {
  3414  		tf.Close()
  3415  		cleanup()
  3416  		log.Fatalf("error writing long arguments to response file: %v", err)
  3417  	}
  3418  	if err := tf.Close(); err != nil {
  3419  		cleanup()
  3420  		log.Fatalf("error writing long arguments to response file: %v", err)
  3421  	}
  3422  	cmd.Args = []string{cmd.Args[0], "@" + tf.Name()}
  3423  	return cleanup
  3424  }
  3425  
  3426  func useResponseFile(path string, argLen int) bool {
  3427  	// Unless the program uses objabi.Flagparse, which understands
  3428  	// response files, don't use response files.
  3429  	// TODO: Note that other toolchains like CC are missing here for now.
  3430  	prog := strings.TrimSuffix(filepath.Base(path), ".exe")
  3431  	switch prog {
  3432  	case "compile", "link", "cgo", "asm", "cover":
  3433  	default:
  3434  		return false
  3435  	}
  3436  
  3437  	if argLen > sys.ExecArgLengthLimit {
  3438  		return true
  3439  	}
  3440  
  3441  	// On the Go build system, use response files about 10% of the
  3442  	// time, just to exercise this codepath.
  3443  	isBuilder := os.Getenv("GO_BUILDER_NAME") != ""
  3444  	if isBuilder && rand.Intn(10) == 0 {
  3445  		return true
  3446  	}
  3447  
  3448  	return false
  3449  }
  3450  
  3451  // encodeArg encodes an argument for response file writing.
  3452  func encodeArg(arg string) string {
  3453  	// If there aren't any characters we need to reencode, fastpath out.
  3454  	if !strings.ContainsAny(arg, "\\\n") {
  3455  		return arg
  3456  	}
  3457  	var b strings.Builder
  3458  	for _, r := range arg {
  3459  		switch r {
  3460  		case '\\':
  3461  			b.WriteByte('\\')
  3462  			b.WriteByte('\\')
  3463  		case '\n':
  3464  			b.WriteByte('\\')
  3465  			b.WriteByte('n')
  3466  		default:
  3467  			b.WriteRune(r)
  3468  		}
  3469  	}
  3470  	return b.String()
  3471  }
  3472  

View as plain text