Source file src/cmd/go/internal/work/action.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 creation (planning).
     6  
     7  package work
     8  
     9  import (
    10  	"bufio"
    11  	"bytes"
    12  	"cmd/internal/cov/covcmd"
    13  	"cmd/internal/par"
    14  	"container/heap"
    15  	"context"
    16  	"debug/elf"
    17  	"encoding/json"
    18  	"fmt"
    19  	"internal/platform"
    20  	"os"
    21  	"path/filepath"
    22  	"slices"
    23  	"strings"
    24  	"sync"
    25  	"time"
    26  
    27  	"cmd/go/internal/base"
    28  	"cmd/go/internal/cache"
    29  	"cmd/go/internal/cfg"
    30  	"cmd/go/internal/load"
    31  	"cmd/go/internal/str"
    32  	"cmd/go/internal/trace"
    33  	"cmd/internal/buildid"
    34  	"cmd/internal/robustio"
    35  )
    36  
    37  // A Builder holds global state about a build.
    38  // It does not hold per-package state, because we
    39  // build packages in parallel, and the builder is shared.
    40  type Builder struct {
    41  	WorkDir            string                    // the temporary work directory (ends in filepath.Separator)
    42  	actionCache        map[cacheKey]*Action      // a cache of already-constructed actions
    43  	flagCache          map[[2]string]bool        // a cache of supported compiler flags
    44  	gccCompilerIDCache map[string]cache.ActionID // cache for gccCompilerID
    45  
    46  	IsCmdList           bool // running as part of go list; set p.Stale and additional fields below
    47  	NeedError           bool // list needs p.Error
    48  	NeedExport          bool // list needs p.Export
    49  	NeedCompiledGoFiles bool // list needs p.CompiledGoFiles
    50  	AllowErrors         bool // errors don't immediately exit the program
    51  
    52  	objdirSeq int // counter for NewObjdir
    53  	pkgSeq    int
    54  
    55  	backgroundSh *Shell // Shell that per-Action Shells are derived from
    56  
    57  	exec      sync.Mutex
    58  	readySema chan bool
    59  	ready     actionQueue
    60  
    61  	id             sync.Mutex
    62  	toolIDCache    par.Cache[string, string] // tool name -> tool ID
    63  	gccToolIDCache map[string]string         // tool name -> tool ID
    64  	buildIDCache   map[string]string         // file name -> build ID
    65  }
    66  
    67  // NOTE: Much of Action would not need to be exported if not for test.
    68  // Maybe test functionality should move into this package too?
    69  
    70  // An Actor runs an action.
    71  type Actor interface {
    72  	Act(*Builder, context.Context, *Action) error
    73  }
    74  
    75  // An ActorFunc is an Actor that calls the function.
    76  type ActorFunc func(*Builder, context.Context, *Action) error
    77  
    78  func (f ActorFunc) Act(b *Builder, ctx context.Context, a *Action) error {
    79  	return f(b, ctx, a)
    80  }
    81  
    82  // An Action represents a single action in the action graph.
    83  type Action struct {
    84  	Mode       string        // description of action operation
    85  	Package    *load.Package // the package this action works on
    86  	Deps       []*Action     // actions that must happen before this one
    87  	Actor      Actor         // the action itself (nil = no-op)
    88  	IgnoreFail bool          // whether to run f even if dependencies fail
    89  	TestOutput *bytes.Buffer // test output buffer
    90  	Args       []string      // additional args for runProgram
    91  
    92  	Provider any // Additional information to be passed to successive actions. Similar to a Bazel provider.
    93  
    94  	triggers []*Action // inverse of deps
    95  
    96  	buggyInstall bool // is this a buggy install (see -linkshared)?
    97  
    98  	TryCache func(*Builder, *Action, *Action) bool // callback for cache bypass
    99  
   100  	CacheExecutable bool // Whether to cache executables produced by link steps
   101  
   102  	// Generated files, directories.
   103  	Objdir           string         // directory for intermediate objects
   104  	Target           string         // goal of the action: the created package or executable
   105  	built            string         // the actual created package or executable
   106  	cachedExecutable string         // the cached executable, if CacheExecutable was set
   107  	actionID         cache.ActionID // cache ID of action input
   108  	buildID          string         // build ID of action output
   109  
   110  	VetxOnly  bool       // Mode=="vet": only being called to supply info about dependencies
   111  	needVet   bool       // Mode=="build": need to fill in vet config
   112  	needBuild bool       // Mode=="build": need to do actual build (can be false if needVet is true)
   113  	vetCfg    *vetConfig // vet config
   114  	output    []byte     // output redirect buffer (nil means use b.Print)
   115  
   116  	sh *Shell // lazily created per-Action shell; see Builder.Shell
   117  
   118  	// Execution state.
   119  	pending      int               // number of deps yet to complete
   120  	priority     int               // relative execution priority
   121  	Failed       *Action           // set to root cause if the action failed
   122  	json         *actionJSON       // action graph information
   123  	nonGoOverlay map[string]string // map from non-.go source files to copied files in objdir. Nil if no overlay is used.
   124  	traceSpan    *trace.Span
   125  }
   126  
   127  // BuildActionID returns the action ID section of a's build ID.
   128  func (a *Action) BuildActionID() string { return actionID(a.buildID) }
   129  
   130  // BuildContentID returns the content ID section of a's build ID.
   131  func (a *Action) BuildContentID() string { return contentID(a.buildID) }
   132  
   133  // BuildID returns a's build ID.
   134  func (a *Action) BuildID() string { return a.buildID }
   135  
   136  // BuiltTarget returns the actual file that was built. This differs
   137  // from Target when the result was cached.
   138  func (a *Action) BuiltTarget() string { return a.built }
   139  
   140  // CachedExecutable returns the cached executable, if CacheExecutable
   141  // was set and the executable could be cached, and "" otherwise.
   142  func (a *Action) CachedExecutable() string { return a.cachedExecutable }
   143  
   144  // An actionQueue is a priority queue of actions.
   145  type actionQueue []*Action
   146  
   147  // Implement heap.Interface
   148  func (q *actionQueue) Len() int           { return len(*q) }
   149  func (q *actionQueue) Swap(i, j int)      { (*q)[i], (*q)[j] = (*q)[j], (*q)[i] }
   150  func (q *actionQueue) Less(i, j int) bool { return (*q)[i].priority < (*q)[j].priority }
   151  func (q *actionQueue) Push(x any)         { *q = append(*q, x.(*Action)) }
   152  func (q *actionQueue) Pop() any {
   153  	n := len(*q) - 1
   154  	x := (*q)[n]
   155  	*q = (*q)[:n]
   156  	return x
   157  }
   158  
   159  func (q *actionQueue) push(a *Action) {
   160  	if a.json != nil {
   161  		a.json.TimeReady = time.Now()
   162  	}
   163  	heap.Push(q, a)
   164  }
   165  
   166  func (q *actionQueue) pop() *Action {
   167  	return heap.Pop(q).(*Action)
   168  }
   169  
   170  type actionJSON struct {
   171  	ID         int
   172  	Mode       string
   173  	Package    string
   174  	Deps       []int     `json:",omitempty"`
   175  	IgnoreFail bool      `json:",omitempty"`
   176  	Args       []string  `json:",omitempty"`
   177  	Link       bool      `json:",omitempty"`
   178  	Objdir     string    `json:",omitempty"`
   179  	Target     string    `json:",omitempty"`
   180  	Priority   int       `json:",omitempty"`
   181  	Failed     bool      `json:",omitempty"`
   182  	Built      string    `json:",omitempty"`
   183  	VetxOnly   bool      `json:",omitempty"`
   184  	NeedVet    bool      `json:",omitempty"`
   185  	NeedBuild  bool      `json:",omitempty"`
   186  	ActionID   string    `json:",omitempty"`
   187  	BuildID    string    `json:",omitempty"`
   188  	TimeReady  time.Time `json:",omitempty"`
   189  	TimeStart  time.Time `json:",omitempty"`
   190  	TimeDone   time.Time `json:",omitempty"`
   191  
   192  	Cmd     []string      // `json:",omitempty"`
   193  	CmdReal time.Duration `json:",omitempty"`
   194  	CmdUser time.Duration `json:",omitempty"`
   195  	CmdSys  time.Duration `json:",omitempty"`
   196  }
   197  
   198  // cacheKey is the key for the action cache.
   199  type cacheKey struct {
   200  	mode string
   201  	p    *load.Package
   202  }
   203  
   204  func actionGraphJSON(a *Action) string {
   205  	var workq []*Action
   206  	var inWorkq = make(map[*Action]int)
   207  
   208  	add := func(a *Action) {
   209  		if _, ok := inWorkq[a]; ok {
   210  			return
   211  		}
   212  		inWorkq[a] = len(workq)
   213  		workq = append(workq, a)
   214  	}
   215  	add(a)
   216  
   217  	for i := 0; i < len(workq); i++ {
   218  		for _, dep := range workq[i].Deps {
   219  			add(dep)
   220  		}
   221  	}
   222  
   223  	list := make([]*actionJSON, 0, len(workq))
   224  	for id, a := range workq {
   225  		if a.json == nil {
   226  			a.json = &actionJSON{
   227  				Mode:       a.Mode,
   228  				ID:         id,
   229  				IgnoreFail: a.IgnoreFail,
   230  				Args:       a.Args,
   231  				Objdir:     a.Objdir,
   232  				Target:     a.Target,
   233  				Failed:     a.Failed != nil,
   234  				Priority:   a.priority,
   235  				Built:      a.built,
   236  				VetxOnly:   a.VetxOnly,
   237  				NeedBuild:  a.needBuild,
   238  				NeedVet:    a.needVet,
   239  			}
   240  			if a.Package != nil {
   241  				// TODO(rsc): Make this a unique key for a.Package somehow.
   242  				a.json.Package = a.Package.ImportPath
   243  			}
   244  			for _, a1 := range a.Deps {
   245  				a.json.Deps = append(a.json.Deps, inWorkq[a1])
   246  			}
   247  		}
   248  		list = append(list, a.json)
   249  	}
   250  
   251  	js, err := json.MarshalIndent(list, "", "\t")
   252  	if err != nil {
   253  		fmt.Fprintf(os.Stderr, "go: writing debug action graph: %v\n", err)
   254  		return ""
   255  	}
   256  	return string(js)
   257  }
   258  
   259  // BuildMode specifies the build mode:
   260  // are we just building things or also installing the results?
   261  type BuildMode int
   262  
   263  const (
   264  	ModeBuild BuildMode = iota
   265  	ModeInstall
   266  	ModeBuggyInstall
   267  
   268  	ModeVetOnly = 1 << 8
   269  )
   270  
   271  // NewBuilder returns a new Builder ready for use.
   272  //
   273  // If workDir is the empty string, NewBuilder creates a WorkDir if needed
   274  // and arranges for it to be removed in case of an unclean exit.
   275  // The caller must Close the builder explicitly to clean up the WorkDir
   276  // before a clean exit.
   277  func NewBuilder(workDir string) *Builder {
   278  	b := new(Builder)
   279  
   280  	b.actionCache = make(map[cacheKey]*Action)
   281  	b.gccToolIDCache = make(map[string]string)
   282  	b.buildIDCache = make(map[string]string)
   283  
   284  	printWorkDir := false
   285  	if workDir != "" {
   286  		b.WorkDir = workDir
   287  	} else if cfg.BuildN {
   288  		b.WorkDir = "$WORK"
   289  	} else {
   290  		if !buildInitStarted {
   291  			panic("internal error: NewBuilder called before BuildInit")
   292  		}
   293  		tmp, err := os.MkdirTemp(cfg.Getenv("GOTMPDIR"), "go-build")
   294  		if err != nil {
   295  			base.Fatalf("go: creating work dir: %v", err)
   296  		}
   297  		if !filepath.IsAbs(tmp) {
   298  			abs, err := filepath.Abs(tmp)
   299  			if err != nil {
   300  				os.RemoveAll(tmp)
   301  				base.Fatalf("go: creating work dir: %v", err)
   302  			}
   303  			tmp = abs
   304  		}
   305  		b.WorkDir = tmp
   306  		builderWorkDirs.Store(b, b.WorkDir)
   307  		printWorkDir = cfg.BuildX || cfg.BuildWork
   308  	}
   309  
   310  	b.backgroundSh = NewShell(b.WorkDir, nil)
   311  
   312  	if printWorkDir {
   313  		b.BackgroundShell().Printf("WORK=%s\n", b.WorkDir)
   314  	}
   315  
   316  	if err := CheckGOOSARCHPair(cfg.Goos, cfg.Goarch); err != nil {
   317  		fmt.Fprintf(os.Stderr, "go: %v\n", err)
   318  		base.SetExitStatus(2)
   319  		base.Exit()
   320  	}
   321  
   322  	for _, tag := range cfg.BuildContext.BuildTags {
   323  		if strings.Contains(tag, ",") {
   324  			fmt.Fprintf(os.Stderr, "go: -tags space-separated list contains comma\n")
   325  			base.SetExitStatus(2)
   326  			base.Exit()
   327  		}
   328  	}
   329  
   330  	return b
   331  }
   332  
   333  var builderWorkDirs sync.Map // *Builder → WorkDir
   334  
   335  func (b *Builder) Close() error {
   336  	wd, ok := builderWorkDirs.Load(b)
   337  	if !ok {
   338  		return nil
   339  	}
   340  	defer builderWorkDirs.Delete(b)
   341  
   342  	if b.WorkDir != wd.(string) {
   343  		base.Errorf("go: internal error: Builder WorkDir unexpectedly changed from %s to %s", wd, b.WorkDir)
   344  	}
   345  
   346  	if !cfg.BuildWork {
   347  		if err := robustio.RemoveAll(b.WorkDir); err != nil {
   348  			return err
   349  		}
   350  	}
   351  	b.WorkDir = ""
   352  	return nil
   353  }
   354  
   355  func closeBuilders() {
   356  	leakedBuilders := 0
   357  	builderWorkDirs.Range(func(bi, _ any) bool {
   358  		leakedBuilders++
   359  		if err := bi.(*Builder).Close(); err != nil {
   360  			base.Error(err)
   361  		}
   362  		return true
   363  	})
   364  
   365  	if leakedBuilders > 0 && base.GetExitStatus() == 0 {
   366  		fmt.Fprintf(os.Stderr, "go: internal error: Builder leaked on successful exit\n")
   367  		base.SetExitStatus(1)
   368  	}
   369  }
   370  
   371  func CheckGOOSARCHPair(goos, goarch string) error {
   372  	if !platform.BuildModeSupported(cfg.BuildContext.Compiler, "default", goos, goarch) {
   373  		return fmt.Errorf("unsupported GOOS/GOARCH pair %s/%s", goos, goarch)
   374  	}
   375  	return nil
   376  }
   377  
   378  // NewObjdir returns the name of a fresh object directory under b.WorkDir.
   379  // It is up to the caller to call b.Mkdir on the result at an appropriate time.
   380  // The result ends in a slash, so that file names in that directory
   381  // can be constructed with direct string addition.
   382  //
   383  // NewObjdir must be called only from a single goroutine at a time,
   384  // so it is safe to call during action graph construction, but it must not
   385  // be called during action graph execution.
   386  func (b *Builder) NewObjdir() string {
   387  	b.objdirSeq++
   388  	return str.WithFilePathSeparator(filepath.Join(b.WorkDir, fmt.Sprintf("b%03d", b.objdirSeq)))
   389  }
   390  
   391  // readpkglist returns the list of packages that were built into the shared library
   392  // at shlibpath. For the native toolchain this list is stored, newline separated, in
   393  // an ELF note with name "Go\x00\x00" and type 1. For GCCGO it is extracted from the
   394  // .go_export section.
   395  func readpkglist(shlibpath string) (pkgs []*load.Package) {
   396  	var stk load.ImportStack
   397  	if cfg.BuildToolchainName == "gccgo" {
   398  		f, err := elf.Open(shlibpath)
   399  		if err != nil {
   400  			base.Fatal(fmt.Errorf("failed to open shared library: %v", err))
   401  		}
   402  		defer f.Close()
   403  		sect := f.Section(".go_export")
   404  		if sect == nil {
   405  			base.Fatal(fmt.Errorf("%s: missing .go_export section", shlibpath))
   406  		}
   407  		data, err := sect.Data()
   408  		if err != nil {
   409  			base.Fatal(fmt.Errorf("%s: failed to read .go_export section: %v", shlibpath, err))
   410  		}
   411  		pkgpath := []byte("pkgpath ")
   412  		for _, line := range bytes.Split(data, []byte{'\n'}) {
   413  			if path, found := bytes.CutPrefix(line, pkgpath); found {
   414  				path = bytes.TrimSuffix(path, []byte{';'})
   415  				pkgs = append(pkgs, load.LoadPackageWithFlags(string(path), base.Cwd(), &stk, nil, 0))
   416  			}
   417  		}
   418  	} else {
   419  		pkglistbytes, err := buildid.ReadELFNote(shlibpath, "Go\x00\x00", 1)
   420  		if err != nil {
   421  			base.Fatalf("readELFNote failed: %v", err)
   422  		}
   423  		scanner := bufio.NewScanner(bytes.NewBuffer(pkglistbytes))
   424  		for scanner.Scan() {
   425  			t := scanner.Text()
   426  			pkgs = append(pkgs, load.LoadPackageWithFlags(t, base.Cwd(), &stk, nil, 0))
   427  		}
   428  	}
   429  	return
   430  }
   431  
   432  // cacheAction looks up {mode, p} in the cache and returns the resulting action.
   433  // If the cache has no such action, f() is recorded and returned.
   434  // TODO(rsc): Change the second key from *load.Package to interface{},
   435  // to make the caching in linkShared less awkward?
   436  func (b *Builder) cacheAction(mode string, p *load.Package, f func() *Action) *Action {
   437  	a := b.actionCache[cacheKey{mode, p}]
   438  	if a == nil {
   439  		a = f()
   440  		b.actionCache[cacheKey{mode, p}] = a
   441  	}
   442  	return a
   443  }
   444  
   445  // AutoAction returns the "right" action for go build or go install of p.
   446  func (b *Builder) AutoAction(mode, depMode BuildMode, p *load.Package) *Action {
   447  	if p.Name == "main" {
   448  		return b.LinkAction(mode, depMode, p)
   449  	}
   450  	return b.CompileAction(mode, depMode, p)
   451  }
   452  
   453  // buildActor implements the Actor interface for package build
   454  // actions. For most package builds this simply means invoking the
   455  // *Builder.build method.
   456  type buildActor struct{}
   457  
   458  func (ba *buildActor) Act(b *Builder, ctx context.Context, a *Action) error {
   459  	return b.build(ctx, a)
   460  }
   461  
   462  // pgoActionID computes the action ID for a preprocess PGO action.
   463  func (b *Builder) pgoActionID(input string) cache.ActionID {
   464  	h := cache.NewHash("preprocess PGO profile " + input)
   465  
   466  	fmt.Fprintf(h, "preprocess PGO profile\n")
   467  	fmt.Fprintf(h, "preprofile %s\n", b.toolID("preprofile"))
   468  	fmt.Fprintf(h, "input %q\n", b.fileHash(input))
   469  
   470  	return h.Sum()
   471  }
   472  
   473  // pgoActor implements the Actor interface for preprocessing PGO profiles.
   474  type pgoActor struct {
   475  	// input is the path to the original pprof profile.
   476  	input string
   477  }
   478  
   479  func (p *pgoActor) Act(b *Builder, ctx context.Context, a *Action) error {
   480  	if b.useCache(a, b.pgoActionID(p.input), a.Target, !b.IsCmdList) || b.IsCmdList {
   481  		return nil
   482  	}
   483  	defer b.flushOutput(a)
   484  
   485  	sh := b.Shell(a)
   486  
   487  	if err := sh.Mkdir(a.Objdir); err != nil {
   488  		return err
   489  	}
   490  
   491  	if err := sh.run(".", p.input, nil, cfg.BuildToolexec, base.Tool("preprofile"), "-o", a.Target, "-i", p.input); err != nil {
   492  		return err
   493  	}
   494  
   495  	// N.B. Builder.build looks for the out in a.built, regardless of
   496  	// whether this came from cache.
   497  	a.built = a.Target
   498  
   499  	if !cfg.BuildN {
   500  		// Cache the output.
   501  		//
   502  		// N.B. We don't use updateBuildID here, as preprocessed PGO profiles
   503  		// do not contain a build ID. updateBuildID is typically responsible
   504  		// for adding to the cache, thus we must do so ourselves instead.
   505  
   506  		r, err := os.Open(a.Target)
   507  		if err != nil {
   508  			return fmt.Errorf("error opening target for caching: %w", err)
   509  		}
   510  
   511  		c := cache.Default()
   512  		outputID, _, err := c.Put(a.actionID, r)
   513  		r.Close()
   514  		if err != nil {
   515  			return fmt.Errorf("error adding target to cache: %w", err)
   516  		}
   517  		if cfg.BuildX {
   518  			sh.ShowCmd("", "%s # internal", joinUnambiguously(str.StringList("cp", a.Target, c.OutputFile(outputID))))
   519  		}
   520  	}
   521  
   522  	return nil
   523  }
   524  
   525  type checkCacheProvider struct {
   526  	need uint32 // What work do successive actions within this package's build need to do? Combination of need bits used in build actions.
   527  }
   528  
   529  // The actor to check the cache to determine what work needs to be done for the action.
   530  // It checks the cache and sets the need bits depending on the build mode and what's available
   531  // in the cache, so the cover and compile actions know what to do.
   532  // Currently, we don't cache the outputs of the individual actions composing the build
   533  // for a single package (such as the output of the cover actor) separately from the
   534  // output of the final build, but if we start doing so, we could schedule the run cgo
   535  // and cgo compile actions earlier because they wouldn't depend on the builds of the
   536  // dependencies of the package they belong to.
   537  type checkCacheActor struct {
   538  	covMetaFileName string
   539  	buildAction     *Action
   540  }
   541  
   542  func (cca *checkCacheActor) Act(b *Builder, ctx context.Context, a *Action) error {
   543  	buildAction := cca.buildAction
   544  	if buildAction.Mode == "build-install" {
   545  		// (*Builder).installAction can rewrite the build action with its install action,
   546  		// making the true build action its dependency. Fetch the build action in that case.
   547  		buildAction = buildAction.Deps[0]
   548  	}
   549  	pr, err := b.checkCacheForBuild(a, buildAction, cca.covMetaFileName)
   550  	if err != nil {
   551  		return err
   552  	}
   553  	a.Provider = pr
   554  	return nil
   555  }
   556  
   557  type coverProvider struct {
   558  	goSources, cgoSources []string // The go and cgo sources generated by the cover tool, which should be used instead of the raw sources on the package.
   559  }
   560  
   561  // The actor to run the cover tool to produce instrumented source files for cover
   562  // builds. In the case of a package with no test files, we store some additional state
   563  // information in the build actor to help with reporting.
   564  type coverActor struct {
   565  	// name of static meta-data file fragment emitted by the cover
   566  	// tool as part of the package cover action, for selected
   567  	// "go test -cover" runs.
   568  	covMetaFileName string
   569  
   570  	buildAction *Action
   571  }
   572  
   573  func (ca *coverActor) Act(b *Builder, ctx context.Context, a *Action) error {
   574  	pr, err := b.runCover(a, ca.buildAction, a.Objdir, a.Package.GoFiles, a.Package.CgoFiles)
   575  	if err != nil {
   576  		return err
   577  	}
   578  	a.Provider = pr
   579  	return nil
   580  }
   581  
   582  // runCgoActor implements the Actor interface for running the cgo command for the package.
   583  type runCgoActor struct {
   584  }
   585  
   586  func (c runCgoActor) Act(b *Builder, ctx context.Context, a *Action) error {
   587  	var cacheProvider *checkCacheProvider
   588  	for _, a1 := range a.Deps {
   589  		if pr, ok := a1.Provider.(*checkCacheProvider); ok {
   590  			cacheProvider = pr
   591  			break
   592  		}
   593  	}
   594  	need := cacheProvider.need
   595  	need &^= needCovMetaFile // handled by cover action
   596  	if need == 0 {
   597  		return nil
   598  	}
   599  	return b.runCgo(ctx, a)
   600  }
   601  
   602  type cgoCompileActor struct {
   603  	file string
   604  
   605  	compileFunc  func(*Action, string, string, []string, string) error
   606  	getFlagsFunc func(*runCgoProvider) []string
   607  
   608  	flags *[]string
   609  }
   610  
   611  func (c cgoCompileActor) Act(b *Builder, ctx context.Context, a *Action) error {
   612  	pr, ok := a.Deps[0].Provider.(*runCgoProvider)
   613  	if !ok {
   614  		return nil // cgo was not needed. do nothing.
   615  	}
   616  	a.nonGoOverlay = pr.nonGoOverlay
   617  	buildAction := a.triggers[0].triggers[0] // cgo compile -> cgo collect -> build
   618  
   619  	a.actionID = cache.Subkey(buildAction.actionID, "cgo compile "+c.file) // buildAction's action id was computed by the check cache action.
   620  	return c.compileFunc(a, a.Objdir, a.Target, c.getFlagsFunc(pr), c.file)
   621  }
   622  
   623  // CompileAction returns the action for compiling and possibly installing
   624  // (according to mode) the given package. The resulting action is only
   625  // for building packages (archives), never for linking executables.
   626  // depMode is the action (build or install) to use when building dependencies.
   627  // To turn package main into an executable, call b.Link instead.
   628  func (b *Builder) CompileAction(mode, depMode BuildMode, p *load.Package) *Action {
   629  	vetOnly := mode&ModeVetOnly != 0
   630  	mode &^= ModeVetOnly
   631  
   632  	if mode != ModeBuild && p.Target == "" {
   633  		// No permanent target.
   634  		mode = ModeBuild
   635  	}
   636  	if mode != ModeBuild && p.Name == "main" {
   637  		// We never install the .a file for a main package.
   638  		mode = ModeBuild
   639  	}
   640  
   641  	// Construct package build action.
   642  	a := b.cacheAction("build", p, func() *Action {
   643  		a := &Action{
   644  			Mode:    "build",
   645  			Package: p,
   646  			Actor:   &buildActor{},
   647  			Objdir:  b.NewObjdir(),
   648  		}
   649  
   650  		if p.Error == nil || !p.Error.IsImportCycle {
   651  			for _, p1 := range p.Internal.Imports {
   652  				a.Deps = append(a.Deps, b.CompileAction(depMode, depMode, p1))
   653  			}
   654  		}
   655  
   656  		if p.Internal.PGOProfile != "" {
   657  			pgoAction := b.cacheAction("preprocess PGO profile "+p.Internal.PGOProfile, nil, func() *Action {
   658  				a := &Action{
   659  					Mode:   "preprocess PGO profile",
   660  					Actor:  &pgoActor{input: p.Internal.PGOProfile},
   661  					Objdir: b.NewObjdir(),
   662  				}
   663  				a.Target = filepath.Join(a.Objdir, "pgo.preprofile")
   664  
   665  				return a
   666  			})
   667  			a.Deps = append(a.Deps, pgoAction)
   668  		}
   669  
   670  		if p.Standard {
   671  			switch p.ImportPath {
   672  			case "builtin", "unsafe":
   673  				// Fake packages - nothing to build.
   674  				a.Mode = "built-in package"
   675  				a.Actor = nil
   676  				return a
   677  			}
   678  
   679  			// gccgo standard library is "fake" too.
   680  			if cfg.BuildToolchainName == "gccgo" {
   681  				// the target name is needed for cgo.
   682  				a.Mode = "gccgo stdlib"
   683  				a.Target = p.Target
   684  				a.Actor = nil
   685  				return a
   686  			}
   687  		}
   688  
   689  		// Determine the covmeta file name.
   690  		var covMetaFileName string
   691  		if p.Internal.Cover.GenMeta {
   692  			covMetaFileName = covcmd.MetaFileForPackage(p.ImportPath)
   693  		}
   694  
   695  		// Create a cache action.
   696  		cacheAction := &Action{
   697  			Mode:    "build check cache",
   698  			Package: p,
   699  			Actor:   &checkCacheActor{buildAction: a, covMetaFileName: covMetaFileName},
   700  			Objdir:  a.Objdir,
   701  			Deps:    a.Deps, // Need outputs of dependency build actions to generate action id.
   702  		}
   703  		a.Deps = append(a.Deps, cacheAction)
   704  
   705  		// Create a cover action if we need to instrument the code for coverage.
   706  		// The cover action always runs in the same go build invocation as the build,
   707  		// and is not cached separately, so it can use the same objdir.
   708  		var coverAction *Action
   709  		if p.Internal.Cover.Mode != "" {
   710  			coverAction = b.cacheAction("cover", p, func() *Action {
   711  				return &Action{
   712  					Mode:    "cover",
   713  					Package: p,
   714  					Actor:   &coverActor{buildAction: a, covMetaFileName: covMetaFileName},
   715  					Objdir:  a.Objdir,
   716  					Deps:    []*Action{cacheAction},
   717  				}
   718  			})
   719  			a.Deps = append(a.Deps, coverAction)
   720  		}
   721  
   722  		// Create actions to run swig and cgo if needed. These actions always run in the
   723  		// same go build invocation as the build action and their actions are not cached
   724  		// separately, so they can use the same objdir.
   725  		if p.UsesCgo() || p.UsesSwig() {
   726  			deps := []*Action{cacheAction}
   727  			if coverAction != nil {
   728  				deps = append(deps, coverAction)
   729  			}
   730  			a.Deps = append(a.Deps, b.cgoAction(p, a.Objdir, deps, coverAction != nil))
   731  		}
   732  
   733  		return a
   734  	})
   735  
   736  	// Find the build action; the cache entry may have been replaced
   737  	// by the install action during (*Builder).installAction.
   738  	buildAction := a
   739  	switch buildAction.Mode {
   740  	case "build", "built-in package", "gccgo stdlib":
   741  		// ok
   742  	case "build-install":
   743  		buildAction = a.Deps[0]
   744  	default:
   745  		panic("lost build action: " + buildAction.Mode)
   746  	}
   747  	buildAction.needBuild = buildAction.needBuild || !vetOnly
   748  
   749  	// Construct install action.
   750  	if mode == ModeInstall || mode == ModeBuggyInstall {
   751  		a = b.installAction(a, mode)
   752  	}
   753  
   754  	return a
   755  }
   756  
   757  func (b *Builder) cgoAction(p *load.Package, objdir string, deps []*Action, hasCover bool) *Action {
   758  	cgoCollectAction := b.cacheAction("cgo collect", p, func() *Action {
   759  		// Run cgo
   760  		runCgo := b.cacheAction("cgo run", p, func() *Action {
   761  			return &Action{
   762  				Package: p,
   763  				Mode:    "cgo run",
   764  				Actor:   &runCgoActor{},
   765  				Objdir:  objdir,
   766  				Deps:    deps,
   767  			}
   768  		})
   769  
   770  		// Determine which files swig will produce in the cgo run action. We'll need to create
   771  		// actions to compile the C and C++ files produced by swig, as well as the C file
   772  		// produced by cgo processing swig's Go file outputs.
   773  		swigGo, swigC, swigCXX := b.swigOutputs(p, objdir)
   774  
   775  		oseq := 0
   776  		nextOfile := func() string {
   777  			oseq++
   778  			return objdir + fmt.Sprintf("_x%03d.o", oseq)
   779  		}
   780  		compileAction := func(file string, getFlagsFunc func(*runCgoProvider) []string, compileFunc func(*Action, string, string, []string, string) error) *Action {
   781  			mode := "cgo compile " + file
   782  			return b.cacheAction(mode, p, func() *Action {
   783  				return &Action{
   784  					Package: p,
   785  					Mode:    mode,
   786  					Actor:   &cgoCompileActor{file: file, getFlagsFunc: getFlagsFunc, compileFunc: compileFunc},
   787  					Deps:    []*Action{runCgo},
   788  					Objdir:  objdir,
   789  					Target:  nextOfile(),
   790  				}
   791  			})
   792  		}
   793  
   794  		var collectDeps []*Action
   795  
   796  		// Add compile actions for C files generated by cgo.
   797  		cgoFiles := p.CgoFiles
   798  		if hasCover {
   799  			cgoFiles = slices.Clone(cgoFiles)
   800  			for i := range cgoFiles {
   801  				cgoFiles[i] = strings.TrimSuffix(cgoFiles[i], ".go") + ".cover.go"
   802  			}
   803  		}
   804  		cfiles := []string{"_cgo_export.c"}
   805  		for _, fn := range slices.Concat(cgoFiles, swigGo) {
   806  			cfiles = append(cfiles, strings.TrimSuffix(filepath.Base(fn), ".go")+".cgo2.c")
   807  		}
   808  		for _, f := range cfiles {
   809  			collectDeps = append(collectDeps, compileAction(objdir+f, (*runCgoProvider).cflags, b.gcc))
   810  		}
   811  
   812  		// Add compile actions for S files.
   813  		var sfiles []string
   814  		// In a package using cgo, cgo compiles the C, C++ and assembly files with gcc.
   815  		// There is one exception: runtime/cgo's job is to bridge the
   816  		// cgo and non-cgo worlds, so it necessarily has files in both.
   817  		// In that case gcc only gets the gcc_* files.
   818  		if p.Standard && p.ImportPath == "runtime/cgo" {
   819  			for _, f := range p.SFiles {
   820  				if strings.HasPrefix(f, "gcc_") {
   821  					sfiles = append(sfiles, f)
   822  				}
   823  			}
   824  		} else {
   825  			sfiles = p.SFiles
   826  		}
   827  		for _, f := range sfiles {
   828  			collectDeps = append(collectDeps, compileAction(f, (*runCgoProvider).cflags, b.gas))
   829  		}
   830  
   831  		// Add compile actions for C files in the package, M files, and those generated by swig.
   832  		for _, f := range slices.Concat(p.CFiles, p.MFiles, swigC) {
   833  			collectDeps = append(collectDeps, compileAction(f, (*runCgoProvider).cflags, b.gcc))
   834  		}
   835  
   836  		// Add compile actions for C++ files in the package, and those generated by swig.
   837  		for _, f := range slices.Concat(p.CXXFiles, swigCXX) {
   838  			collectDeps = append(collectDeps, compileAction(f, (*runCgoProvider).cxxflags, b.gxx))
   839  		}
   840  
   841  		// Add compile actions for Fortran files in the package.
   842  		for _, f := range p.FFiles {
   843  			collectDeps = append(collectDeps, compileAction(f, (*runCgoProvider).fflags, b.gfortran))
   844  		}
   845  
   846  		// Add a single convenience action that does nothing to join the previous action,
   847  		// and better separate the cgo action dependencies of the build action from the
   848  		// build actions for its package dependencies.
   849  		return &Action{
   850  			Mode: "collect cgo",
   851  			Actor: ActorFunc(func(b *Builder, ctx context.Context, a *Action) error {
   852  				// Use the cgo run action's provider as our provider output,
   853  				// so it can be easily accessed by the build action.
   854  				a.Provider = a.Deps[0].Deps[0].Provider
   855  				return nil
   856  			}),
   857  			Deps:   collectDeps,
   858  			Objdir: objdir,
   859  		}
   860  	})
   861  
   862  	return cgoCollectAction
   863  }
   864  
   865  // VetAction returns the action for running go vet on package p.
   866  // It depends on the action for compiling p.
   867  // If the caller may be causing p to be installed, it is up to the caller
   868  // to make sure that the install depends on (runs after) vet.
   869  func (b *Builder) VetAction(mode, depMode BuildMode, p *load.Package) *Action {
   870  	a := b.vetAction(mode, depMode, p)
   871  	a.VetxOnly = false
   872  	return a
   873  }
   874  
   875  func (b *Builder) vetAction(mode, depMode BuildMode, p *load.Package) *Action {
   876  	// Construct vet action.
   877  	a := b.cacheAction("vet", p, func() *Action {
   878  		a1 := b.CompileAction(mode|ModeVetOnly, depMode, p)
   879  
   880  		var deps []*Action
   881  		if a1.buggyInstall {
   882  			// (*Builder).vet expects deps[0] to be the package.
   883  			// If we see buggyInstall
   884  			// here then a1 is an install of a shared library,
   885  			// and the real package is a1.Deps[0].
   886  			deps = []*Action{a1.Deps[0], a1}
   887  		} else {
   888  			deps = []*Action{a1}
   889  		}
   890  		for _, p1 := range p.Internal.Imports {
   891  			deps = append(deps, b.vetAction(mode, depMode, p1))
   892  		}
   893  
   894  		a := &Action{
   895  			Mode:       "vet",
   896  			Package:    p,
   897  			Deps:       deps,
   898  			Objdir:     a1.Objdir,
   899  			VetxOnly:   true,
   900  			IgnoreFail: true, // it's OK if vet of dependencies "fails" (reports problems)
   901  		}
   902  		if a1.Actor == nil {
   903  			// Built-in packages like unsafe.
   904  			return a
   905  		}
   906  		deps[0].needVet = true
   907  		a.Actor = ActorFunc((*Builder).vet)
   908  		return a
   909  	})
   910  	return a
   911  }
   912  
   913  // LinkAction returns the action for linking p into an executable
   914  // and possibly installing the result (according to mode).
   915  // depMode is the action (build or install) to use when compiling dependencies.
   916  func (b *Builder) LinkAction(mode, depMode BuildMode, p *load.Package) *Action {
   917  	// Construct link action.
   918  	a := b.cacheAction("link", p, func() *Action {
   919  		a := &Action{
   920  			Mode:    "link",
   921  			Package: p,
   922  		}
   923  
   924  		a1 := b.CompileAction(ModeBuild, depMode, p)
   925  		a.Actor = ActorFunc((*Builder).link)
   926  		a.Deps = []*Action{a1}
   927  		a.Objdir = a1.Objdir
   928  
   929  		// An executable file. (This is the name of a temporary file.)
   930  		// Because we run the temporary file in 'go run' and 'go test',
   931  		// the name will show up in ps listings. If the caller has specified
   932  		// a name, use that instead of a.out. The binary is generated
   933  		// in an otherwise empty subdirectory named exe to avoid
   934  		// naming conflicts. The only possible conflict is if we were
   935  		// to create a top-level package named exe.
   936  		name := "a.out"
   937  		if p.Internal.ExeName != "" {
   938  			name = p.Internal.ExeName
   939  		} else if (cfg.Goos == "darwin" || cfg.Goos == "windows") && cfg.BuildBuildmode == "c-shared" && p.Target != "" {
   940  			// On OS X, the linker output name gets recorded in the
   941  			// shared library's LC_ID_DYLIB load command.
   942  			// The code invoking the linker knows to pass only the final
   943  			// path element. Arrange that the path element matches what
   944  			// we'll install it as; otherwise the library is only loadable as "a.out".
   945  			// On Windows, DLL file name is recorded in PE file
   946  			// export section, so do like on OS X.
   947  			_, name = filepath.Split(p.Target)
   948  		}
   949  		a.Target = a.Objdir + filepath.Join("exe", name) + cfg.ExeSuffix
   950  		a.built = a.Target
   951  		b.addTransitiveLinkDeps(a, a1, "")
   952  
   953  		// Sequence the build of the main package (a1) strictly after the build
   954  		// of all other dependencies that go into the link. It is likely to be after
   955  		// them anyway, but just make sure. This is required by the build ID-based
   956  		// shortcut in (*Builder).useCache(a1), which will call b.linkActionID(a).
   957  		// In order for that linkActionID call to compute the right action ID, all the
   958  		// dependencies of a (except a1) must have completed building and have
   959  		// recorded their build IDs.
   960  		a1.Deps = append(a1.Deps, &Action{Mode: "nop", Deps: a.Deps[1:]})
   961  		return a
   962  	})
   963  
   964  	if mode == ModeInstall || mode == ModeBuggyInstall {
   965  		a = b.installAction(a, mode)
   966  	}
   967  
   968  	return a
   969  }
   970  
   971  // installAction returns the action for installing the result of a1.
   972  func (b *Builder) installAction(a1 *Action, mode BuildMode) *Action {
   973  	// Because we overwrite the build action with the install action below,
   974  	// a1 may already be an install action fetched from the "build" cache key,
   975  	// and the caller just doesn't realize.
   976  	if strings.HasSuffix(a1.Mode, "-install") {
   977  		if a1.buggyInstall && mode == ModeInstall {
   978  			//  Congratulations! The buggy install is now a proper install.
   979  			a1.buggyInstall = false
   980  		}
   981  		return a1
   982  	}
   983  
   984  	// If there's no actual action to build a1,
   985  	// there's nothing to install either.
   986  	// This happens if a1 corresponds to reusing an already-built object.
   987  	if a1.Actor == nil {
   988  		return a1
   989  	}
   990  
   991  	p := a1.Package
   992  	return b.cacheAction(a1.Mode+"-install", p, func() *Action {
   993  		// The install deletes the temporary build result,
   994  		// so we need all other actions, both past and future,
   995  		// that attempt to depend on the build to depend instead
   996  		// on the install.
   997  
   998  		// Make a private copy of a1 (the build action),
   999  		// no longer accessible to any other rules.
  1000  		buildAction := new(Action)
  1001  		*buildAction = *a1
  1002  
  1003  		// Overwrite a1 with the install action.
  1004  		// This takes care of updating past actions that
  1005  		// point at a1 for the build action; now they will
  1006  		// point at a1 and get the install action.
  1007  		// We also leave a1 in the action cache as the result
  1008  		// for "build", so that actions not yet created that
  1009  		// try to depend on the build will instead depend
  1010  		// on the install.
  1011  		*a1 = Action{
  1012  			Mode:    buildAction.Mode + "-install",
  1013  			Actor:   ActorFunc(BuildInstallFunc),
  1014  			Package: p,
  1015  			Objdir:  buildAction.Objdir,
  1016  			Deps:    []*Action{buildAction},
  1017  			Target:  p.Target,
  1018  			built:   p.Target,
  1019  
  1020  			buggyInstall: mode == ModeBuggyInstall,
  1021  		}
  1022  
  1023  		b.addInstallHeaderAction(a1)
  1024  		return a1
  1025  	})
  1026  }
  1027  
  1028  // addTransitiveLinkDeps adds to the link action a all packages
  1029  // that are transitive dependencies of a1.Deps.
  1030  // That is, if a is a link of package main, a1 is the compile of package main
  1031  // and a1.Deps is the actions for building packages directly imported by
  1032  // package main (what the compiler needs). The linker needs all packages
  1033  // transitively imported by the whole program; addTransitiveLinkDeps
  1034  // makes sure those are present in a.Deps.
  1035  // If shlib is non-empty, then a corresponds to the build and installation of shlib,
  1036  // so any rebuild of shlib should not be added as a dependency.
  1037  func (b *Builder) addTransitiveLinkDeps(a, a1 *Action, shlib string) {
  1038  	// Expand Deps to include all built packages, for the linker.
  1039  	// Use breadth-first search to find rebuilt-for-test packages
  1040  	// before the standard ones.
  1041  	// TODO(rsc): Eliminate the standard ones from the action graph,
  1042  	// which will require doing a little bit more rebuilding.
  1043  	workq := []*Action{a1}
  1044  	haveDep := map[string]bool{}
  1045  	if a1.Package != nil {
  1046  		haveDep[a1.Package.ImportPath] = true
  1047  	}
  1048  	for i := 0; i < len(workq); i++ {
  1049  		a1 := workq[i]
  1050  		for _, a2 := range a1.Deps {
  1051  			// TODO(rsc): Find a better discriminator than the Mode strings, once the dust settles.
  1052  			if a2.Package == nil || (a2.Mode != "build-install" && a2.Mode != "build") || haveDep[a2.Package.ImportPath] {
  1053  				continue
  1054  			}
  1055  			haveDep[a2.Package.ImportPath] = true
  1056  			a.Deps = append(a.Deps, a2)
  1057  			if a2.Mode == "build-install" {
  1058  				a2 = a2.Deps[0] // walk children of "build" action
  1059  			}
  1060  			workq = append(workq, a2)
  1061  		}
  1062  	}
  1063  
  1064  	// If this is go build -linkshared, then the link depends on the shared libraries
  1065  	// in addition to the packages themselves. (The compile steps do not.)
  1066  	if cfg.BuildLinkshared {
  1067  		haveShlib := map[string]bool{shlib: true}
  1068  		for _, a1 := range a.Deps {
  1069  			p1 := a1.Package
  1070  			if p1 == nil || p1.Shlib == "" || haveShlib[filepath.Base(p1.Shlib)] {
  1071  				continue
  1072  			}
  1073  			haveShlib[filepath.Base(p1.Shlib)] = true
  1074  			// TODO(rsc): The use of ModeInstall here is suspect, but if we only do ModeBuild,
  1075  			// we'll end up building an overall library or executable that depends at runtime
  1076  			// on other libraries that are out-of-date, which is clearly not good either.
  1077  			// We call it ModeBuggyInstall to make clear that this is not right.
  1078  			a.Deps = append(a.Deps, b.linkSharedAction(ModeBuggyInstall, ModeBuggyInstall, p1.Shlib, nil))
  1079  		}
  1080  	}
  1081  }
  1082  
  1083  // addInstallHeaderAction adds an install header action to a, if needed.
  1084  // The action a should be an install action as generated by either
  1085  // b.CompileAction or b.LinkAction with mode=ModeInstall,
  1086  // and so a.Deps[0] is the corresponding build action.
  1087  func (b *Builder) addInstallHeaderAction(a *Action) {
  1088  	// Install header for cgo in c-archive and c-shared modes.
  1089  	p := a.Package
  1090  	if p.UsesCgo() && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") {
  1091  		hdrTarget := a.Target[:len(a.Target)-len(filepath.Ext(a.Target))] + ".h"
  1092  		if cfg.BuildContext.Compiler == "gccgo" && cfg.BuildO == "" {
  1093  			// For the header file, remove the "lib"
  1094  			// added by go/build, so we generate pkg.h
  1095  			// rather than libpkg.h.
  1096  			dir, file := filepath.Split(hdrTarget)
  1097  			file = strings.TrimPrefix(file, "lib")
  1098  			hdrTarget = filepath.Join(dir, file)
  1099  		}
  1100  		ah := &Action{
  1101  			Mode:    "install header",
  1102  			Package: a.Package,
  1103  			Deps:    []*Action{a.Deps[0]},
  1104  			Actor:   ActorFunc((*Builder).installHeader),
  1105  			Objdir:  a.Deps[0].Objdir,
  1106  			Target:  hdrTarget,
  1107  		}
  1108  		a.Deps = append(a.Deps, ah)
  1109  	}
  1110  }
  1111  
  1112  // buildmodeShared takes the "go build" action a1 into the building of a shared library of a1.Deps.
  1113  // That is, the input a1 represents "go build pkgs" and the result represents "go build -buildmode=shared pkgs".
  1114  func (b *Builder) buildmodeShared(mode, depMode BuildMode, args []string, pkgs []*load.Package, a1 *Action) *Action {
  1115  	name, err := libname(args, pkgs)
  1116  	if err != nil {
  1117  		base.Fatalf("%v", err)
  1118  	}
  1119  	return b.linkSharedAction(mode, depMode, name, a1)
  1120  }
  1121  
  1122  // linkSharedAction takes a grouping action a1 corresponding to a list of built packages
  1123  // and returns an action that links them together into a shared library with the name shlib.
  1124  // If a1 is nil, shlib should be an absolute path to an existing shared library,
  1125  // and then linkSharedAction reads that library to find out the package list.
  1126  func (b *Builder) linkSharedAction(mode, depMode BuildMode, shlib string, a1 *Action) *Action {
  1127  	fullShlib := shlib
  1128  	shlib = filepath.Base(shlib)
  1129  	a := b.cacheAction("build-shlib "+shlib, nil, func() *Action {
  1130  		if a1 == nil {
  1131  			// TODO(rsc): Need to find some other place to store config,
  1132  			// not in pkg directory. See golang.org/issue/22196.
  1133  			pkgs := readpkglist(fullShlib)
  1134  			a1 = &Action{
  1135  				Mode: "shlib packages",
  1136  			}
  1137  			for _, p := range pkgs {
  1138  				a1.Deps = append(a1.Deps, b.CompileAction(mode, depMode, p))
  1139  			}
  1140  		}
  1141  
  1142  		// Fake package to hold ldflags.
  1143  		// As usual shared libraries are a kludgy, abstraction-violating special case:
  1144  		// we let them use the flags specified for the command-line arguments.
  1145  		p := &load.Package{}
  1146  		p.Internal.CmdlinePkg = true
  1147  		p.Internal.Ldflags = load.BuildLdflags.For(p)
  1148  		p.Internal.Gccgoflags = load.BuildGccgoflags.For(p)
  1149  
  1150  		// Add implicit dependencies to pkgs list.
  1151  		// Currently buildmode=shared forces external linking mode, and
  1152  		// external linking mode forces an import of runtime/cgo (and
  1153  		// math on arm). So if it was not passed on the command line and
  1154  		// it is not present in another shared library, add it here.
  1155  		// TODO(rsc): Maybe this should only happen if "runtime" is in the original package set.
  1156  		// TODO(rsc): This should probably be changed to use load.LinkerDeps(p).
  1157  		// TODO(rsc): We don't add standard library imports for gccgo
  1158  		// because they are all always linked in anyhow.
  1159  		// Maybe load.LinkerDeps should be used and updated.
  1160  		a := &Action{
  1161  			Mode:    "go build -buildmode=shared",
  1162  			Package: p,
  1163  			Objdir:  b.NewObjdir(),
  1164  			Actor:   ActorFunc((*Builder).linkShared),
  1165  			Deps:    []*Action{a1},
  1166  		}
  1167  		a.Target = filepath.Join(a.Objdir, shlib)
  1168  		if cfg.BuildToolchainName != "gccgo" {
  1169  			add := func(a1 *Action, pkg string, force bool) {
  1170  				for _, a2 := range a1.Deps {
  1171  					if a2.Package != nil && a2.Package.ImportPath == pkg {
  1172  						return
  1173  					}
  1174  				}
  1175  				var stk load.ImportStack
  1176  				p := load.LoadPackageWithFlags(pkg, base.Cwd(), &stk, nil, 0)
  1177  				if p.Error != nil {
  1178  					base.Fatalf("load %s: %v", pkg, p.Error)
  1179  				}
  1180  				// Assume that if pkg (runtime/cgo or math)
  1181  				// is already accounted for in a different shared library,
  1182  				// then that shared library also contains runtime,
  1183  				// so that anything we do will depend on that library,
  1184  				// so we don't need to include pkg in our shared library.
  1185  				if force || p.Shlib == "" || filepath.Base(p.Shlib) == pkg {
  1186  					a1.Deps = append(a1.Deps, b.CompileAction(depMode, depMode, p))
  1187  				}
  1188  			}
  1189  			add(a1, "runtime/cgo", false)
  1190  			if cfg.Goarch == "arm" {
  1191  				add(a1, "math", false)
  1192  			}
  1193  
  1194  			// The linker step still needs all the usual linker deps.
  1195  			// (For example, the linker always opens runtime.a.)
  1196  			ldDeps, err := load.LinkerDeps(nil)
  1197  			if err != nil {
  1198  				base.Error(err)
  1199  			}
  1200  			for _, dep := range ldDeps {
  1201  				add(a, dep, true)
  1202  			}
  1203  		}
  1204  		b.addTransitiveLinkDeps(a, a1, shlib)
  1205  		return a
  1206  	})
  1207  
  1208  	// Install result.
  1209  	if (mode == ModeInstall || mode == ModeBuggyInstall) && a.Actor != nil {
  1210  		buildAction := a
  1211  
  1212  		a = b.cacheAction("install-shlib "+shlib, nil, func() *Action {
  1213  			// Determine the eventual install target.
  1214  			// The install target is root/pkg/shlib, where root is the source root
  1215  			// in which all the packages lie.
  1216  			// TODO(rsc): Perhaps this cross-root check should apply to the full
  1217  			// transitive package dependency list, not just the ones named
  1218  			// on the command line?
  1219  			pkgDir := a1.Deps[0].Package.Internal.Build.PkgTargetRoot
  1220  			for _, a2 := range a1.Deps {
  1221  				if dir := a2.Package.Internal.Build.PkgTargetRoot; dir != pkgDir {
  1222  					base.Fatalf("installing shared library: cannot use packages %s and %s from different roots %s and %s",
  1223  						a1.Deps[0].Package.ImportPath,
  1224  						a2.Package.ImportPath,
  1225  						pkgDir,
  1226  						dir)
  1227  				}
  1228  			}
  1229  			// TODO(rsc): Find out and explain here why gccgo is different.
  1230  			if cfg.BuildToolchainName == "gccgo" {
  1231  				pkgDir = filepath.Join(pkgDir, "shlibs")
  1232  			}
  1233  			target := filepath.Join(pkgDir, shlib)
  1234  
  1235  			a := &Action{
  1236  				Mode:   "go install -buildmode=shared",
  1237  				Objdir: buildAction.Objdir,
  1238  				Actor:  ActorFunc(BuildInstallFunc),
  1239  				Deps:   []*Action{buildAction},
  1240  				Target: target,
  1241  			}
  1242  			for _, a2 := range buildAction.Deps[0].Deps {
  1243  				p := a2.Package
  1244  				pkgTargetRoot := p.Internal.Build.PkgTargetRoot
  1245  				if pkgTargetRoot == "" {
  1246  					continue
  1247  				}
  1248  				a.Deps = append(a.Deps, &Action{
  1249  					Mode:    "shlibname",
  1250  					Package: p,
  1251  					Actor:   ActorFunc((*Builder).installShlibname),
  1252  					Target:  filepath.Join(pkgTargetRoot, p.ImportPath+".shlibname"),
  1253  					Deps:    []*Action{a.Deps[0]},
  1254  				})
  1255  			}
  1256  			return a
  1257  		})
  1258  	}
  1259  
  1260  	return a
  1261  }
  1262  

View as plain text