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

View as plain text