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

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

View as plain text