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

View as plain text