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

View as plain text