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

View as plain text