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

View as plain text