github.com/bir3/gocompiler@v0.9.2202/src/cmd/gocmd/internal/work/action.go (about)

     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  	"github.com/bir3/gocompiler/src/cmd/internal/cov/covcmd"
    13  	"container/heap"
    14  	"context"
    15  	"debug/elf"
    16  	"encoding/json"
    17  	"fmt"
    18  	"github.com/bir3/gocompiler/src/internal/platform"
    19  	"os"
    20  	"path/filepath"
    21  	"strings"
    22  	"sync"
    23  	"time"
    24  
    25  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/base"
    26  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/cache"
    27  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/cfg"
    28  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/load"
    29  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/robustio"
    30  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/str"
    31  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/trace"
    32  	"github.com/bir3/gocompiler/src/cmd/internal/buildid"
    33  )
    34  
    35  // A Builder holds global state about a build.
    36  // It does not hold per-package state, because we
    37  // build packages in parallel, and the builder is shared.
    38  type Builder struct {
    39  	WorkDir			string				// the temporary work directory (ends in filepath.Separator)
    40  	actionCache		map[cacheKey]*Action		// a cache of already-constructed actions
    41  	flagCache		map[[2]string]bool		// a cache of supported compiler flags
    42  	gccCompilerIDCache	map[string]cache.ActionID	// cache for gccCompilerID
    43  
    44  	IsCmdList		bool	// running as part of go list; set p.Stale and additional fields below
    45  	NeedError		bool	// list needs p.Error
    46  	NeedExport		bool	// list needs p.Export
    47  	NeedCompiledGoFiles	bool	// list needs p.CompiledGoFiles
    48  	AllowErrors		bool	// errors don't immediately exit the program
    49  
    50  	objdirSeq	int	// counter for NewObjdir
    51  	pkgSeq		int
    52  
    53  	backgroundSh	*Shell	// Shell that per-Action Shells are derived from
    54  
    55  	exec		sync.Mutex
    56  	readySema	chan bool
    57  	ready		actionQueue
    58  
    59  	id		sync.Mutex
    60  	toolIDCache	map[string]string	// tool name -> tool ID
    61  	buildIDCache	map[string]string	// file name -> build ID
    62  }
    63  
    64  // NOTE: Much of Action would not need to be exported if not for test.
    65  // Maybe test functionality should move into this package too?
    66  
    67  // An Actor runs an action.
    68  type Actor interface {
    69  	Act(*Builder, context.Context, *Action) error
    70  }
    71  
    72  // An ActorFunc is an Actor that calls the function.
    73  type ActorFunc func(*Builder, context.Context, *Action) error
    74  
    75  func (f ActorFunc) Act(b *Builder, ctx context.Context, a *Action) error {
    76  	return f(b, ctx, a)
    77  }
    78  
    79  // An Action represents a single action in the action graph.
    80  type Action struct {
    81  	Mode		string		// description of action operation
    82  	Package		*load.Package	// the package this action works on
    83  	Deps		[]*Action	// actions that must happen before this one
    84  	Actor		Actor		// the action itself (nil = no-op)
    85  	IgnoreFail	bool		// whether to run f even if dependencies fail
    86  	TestOutput	*bytes.Buffer	// test output buffer
    87  	Args		[]string	// additional args for runProgram
    88  
    89  	triggers	[]*Action	// inverse of deps
    90  
    91  	buggyInstall	bool	// is this a buggy install (see -linkshared)?
    92  
    93  	TryCache	func(*Builder, *Action) bool	// callback for cache bypass
    94  
    95  	// Generated files, directories.
    96  	Objdir		string		// directory for intermediate objects
    97  	Target		string		// goal of the action: the created package or executable
    98  	built		string		// the actual created package or executable
    99  	actionID	cache.ActionID	// cache ID of action input
   100  	buildID		string		// build ID of action output
   101  
   102  	VetxOnly	bool		// Mode=="vet": only being called to supply info about dependencies
   103  	needVet		bool		// Mode=="build": need to fill in vet config
   104  	needBuild	bool		// Mode=="build": need to do actual build (can be false if needVet is true)
   105  	vetCfg		*vetConfig	// vet config
   106  	output		[]byte		// output redirect buffer (nil means use b.Print)
   107  
   108  	sh	*Shell	// lazily created per-Action shell; see Builder.Shell
   109  
   110  	// Execution state.
   111  	pending		int			// number of deps yet to complete
   112  	priority	int			// relative execution priority
   113  	Failed		bool			// whether the action failed
   114  	json		*actionJSON		// action graph information
   115  	nonGoOverlay	map[string]string	// map from non-.go source files to copied files in objdir. Nil if no overlay is used.
   116  	traceSpan	*trace.Span
   117  }
   118  
   119  // BuildActionID returns the action ID section of a's build ID.
   120  func (a *Action) BuildActionID() string	{ return actionID(a.buildID) }
   121  
   122  // BuildContentID returns the content ID section of a's build ID.
   123  func (a *Action) BuildContentID() string	{ return contentID(a.buildID) }
   124  
   125  // BuildID returns a's build ID.
   126  func (a *Action) BuildID() string	{ return a.buildID }
   127  
   128  // BuiltTarget returns the actual file that was built. This differs
   129  // from Target when the result was cached.
   130  func (a *Action) BuiltTarget() string	{ return a.built }
   131  
   132  // An actionQueue is a priority queue of actions.
   133  type actionQueue []*Action
   134  
   135  // Implement heap.Interface
   136  func (q *actionQueue) Len() int			{ return len(*q) }
   137  func (q *actionQueue) Swap(i, j int)		{ (*q)[i], (*q)[j] = (*q)[j], (*q)[i] }
   138  func (q *actionQueue) Less(i, j int) bool	{ return (*q)[i].priority < (*q)[j].priority }
   139  func (q *actionQueue) Push(x any)		{ *q = append(*q, x.(*Action)) }
   140  func (q *actionQueue) Pop() any {
   141  	n := len(*q) - 1
   142  	x := (*q)[n]
   143  	*q = (*q)[:n]
   144  	return x
   145  }
   146  
   147  func (q *actionQueue) push(a *Action) {
   148  	if a.json != nil {
   149  		a.json.TimeReady = time.Now()
   150  	}
   151  	heap.Push(q, a)
   152  }
   153  
   154  func (q *actionQueue) pop() *Action {
   155  	return heap.Pop(q).(*Action)
   156  }
   157  
   158  type actionJSON struct {
   159  	ID		int
   160  	Mode		string
   161  	Package		string
   162  	Deps		[]int		`json:",omitempty"`
   163  	IgnoreFail	bool		`json:",omitempty"`
   164  	Args		[]string	`json:",omitempty"`
   165  	Link		bool		`json:",omitempty"`
   166  	Objdir		string		`json:",omitempty"`
   167  	Target		string		`json:",omitempty"`
   168  	Priority	int		`json:",omitempty"`
   169  	Failed		bool		`json:",omitempty"`
   170  	Built		string		`json:",omitempty"`
   171  	VetxOnly	bool		`json:",omitempty"`
   172  	NeedVet		bool		`json:",omitempty"`
   173  	NeedBuild	bool		`json:",omitempty"`
   174  	ActionID	string		`json:",omitempty"`
   175  	BuildID		string		`json:",omitempty"`
   176  	TimeReady	time.Time	`json:",omitempty"`
   177  	TimeStart	time.Time	`json:",omitempty"`
   178  	TimeDone	time.Time	`json:",omitempty"`
   179  
   180  	Cmd	[]string	// `json:",omitempty"`
   181  	CmdReal	time.Duration	`json:",omitempty"`
   182  	CmdUser	time.Duration	`json:",omitempty"`
   183  	CmdSys	time.Duration	`json:",omitempty"`
   184  }
   185  
   186  // cacheKey is the key for the action cache.
   187  type cacheKey struct {
   188  	mode	string
   189  	p	*load.Package
   190  }
   191  
   192  func actionGraphJSON(a *Action) string {
   193  	var workq []*Action
   194  	var inWorkq = make(map[*Action]int)
   195  
   196  	add := func(a *Action) {
   197  		if _, ok := inWorkq[a]; ok {
   198  			return
   199  		}
   200  		inWorkq[a] = len(workq)
   201  		workq = append(workq, a)
   202  	}
   203  	add(a)
   204  
   205  	for i := 0; i < len(workq); i++ {
   206  		for _, dep := range workq[i].Deps {
   207  			add(dep)
   208  		}
   209  	}
   210  
   211  	var list []*actionJSON
   212  	for id, a := range workq {
   213  		if a.json == nil {
   214  			a.json = &actionJSON{
   215  				Mode:		a.Mode,
   216  				ID:		id,
   217  				IgnoreFail:	a.IgnoreFail,
   218  				Args:		a.Args,
   219  				Objdir:		a.Objdir,
   220  				Target:		a.Target,
   221  				Failed:		a.Failed,
   222  				Priority:	a.priority,
   223  				Built:		a.built,
   224  				VetxOnly:	a.VetxOnly,
   225  				NeedBuild:	a.needBuild,
   226  				NeedVet:	a.needVet,
   227  			}
   228  			if a.Package != nil {
   229  				// TODO(rsc): Make this a unique key for a.Package somehow.
   230  				a.json.Package = a.Package.ImportPath
   231  			}
   232  			for _, a1 := range a.Deps {
   233  				a.json.Deps = append(a.json.Deps, inWorkq[a1])
   234  			}
   235  		}
   236  		list = append(list, a.json)
   237  	}
   238  
   239  	js, err := json.MarshalIndent(list, "", "\t")
   240  	if err != nil {
   241  		fmt.Fprintf(os.Stderr, "go: writing debug action graph: %v\n", err)
   242  		return ""
   243  	}
   244  	return string(js)
   245  }
   246  
   247  // BuildMode specifies the build mode:
   248  // are we just building things or also installing the results?
   249  type BuildMode int
   250  
   251  const (
   252  	ModeBuild	BuildMode	= iota
   253  	ModeInstall
   254  	ModeBuggyInstall
   255  
   256  	ModeVetOnly	= 1 << 8
   257  )
   258  
   259  // NewBuilder returns a new Builder ready for use.
   260  //
   261  // If workDir is the empty string, NewBuilder creates a WorkDir if needed
   262  // and arranges for it to be removed in case of an unclean exit.
   263  // The caller must Close the builder explicitly to clean up the WorkDir
   264  // before a clean exit.
   265  func NewBuilder(workDir string) *Builder {
   266  	b := new(Builder)
   267  
   268  	b.actionCache = make(map[cacheKey]*Action)
   269  	b.toolIDCache = make(map[string]string)
   270  	b.buildIDCache = make(map[string]string)
   271  
   272  	if workDir != "" {
   273  		b.WorkDir = workDir
   274  	} else if cfg.BuildN {
   275  		b.WorkDir = "$WORK"
   276  	} else {
   277  		if !buildInitStarted {
   278  			panic("internal error: NewBuilder called before BuildInit")
   279  		}
   280  		tmp, err := os.MkdirTemp(cfg.Getenv("GOTMPDIR"), "go-build")
   281  		if err != nil {
   282  			base.Fatalf("go: creating work dir: %v", err)
   283  		}
   284  		if !filepath.IsAbs(tmp) {
   285  			abs, err := filepath.Abs(tmp)
   286  			if err != nil {
   287  				os.RemoveAll(tmp)
   288  				base.Fatalf("go: creating work dir: %v", err)
   289  			}
   290  			tmp = abs
   291  		}
   292  		b.WorkDir = tmp
   293  		builderWorkDirs.Store(b, b.WorkDir)
   294  		if cfg.BuildX || cfg.BuildWork {
   295  			fmt.Fprintf(os.Stderr, "WORK=%s\n", b.WorkDir)
   296  		}
   297  	}
   298  
   299  	b.backgroundSh = NewShell(b.WorkDir, nil)
   300  
   301  	if err := CheckGOOSARCHPair(cfg.Goos, cfg.Goarch); err != nil {
   302  		fmt.Fprintf(os.Stderr, "go: %v\n", err)
   303  		base.SetExitStatus(2)
   304  		base.Exit()
   305  	}
   306  
   307  	for _, tag := range cfg.BuildContext.BuildTags {
   308  		if strings.Contains(tag, ",") {
   309  			fmt.Fprintf(os.Stderr, "go: -tags space-separated list contains comma\n")
   310  			base.SetExitStatus(2)
   311  			base.Exit()
   312  		}
   313  	}
   314  
   315  	return b
   316  }
   317  
   318  var builderWorkDirs sync.Map	// *Builder → WorkDir
   319  
   320  func (b *Builder) Close() error {
   321  	wd, ok := builderWorkDirs.Load(b)
   322  	if !ok {
   323  		return nil
   324  	}
   325  	defer builderWorkDirs.Delete(b)
   326  
   327  	if b.WorkDir != wd.(string) {
   328  		base.Errorf("go: internal error: Builder WorkDir unexpectedly changed from %s to %s", wd, b.WorkDir)
   329  	}
   330  
   331  	if !cfg.BuildWork {
   332  		if err := robustio.RemoveAll(b.WorkDir); err != nil {
   333  			return err
   334  		}
   335  	}
   336  	b.WorkDir = ""
   337  	return nil
   338  }
   339  
   340  func closeBuilders() {
   341  	leakedBuilders := 0
   342  	builderWorkDirs.Range(func(bi, _ any) bool {
   343  		leakedBuilders++
   344  		if err := bi.(*Builder).Close(); err != nil {
   345  			base.Error(err)
   346  		}
   347  		return true
   348  	})
   349  
   350  	if leakedBuilders > 0 && base.GetExitStatus() == 0 {
   351  		fmt.Fprintf(os.Stderr, "go: internal error: Builder leaked on successful exit\n")
   352  		base.SetExitStatus(1)
   353  	}
   354  }
   355  
   356  func CheckGOOSARCHPair(goos, goarch string) error {
   357  	if !platform.BuildModeSupported(cfg.BuildContext.Compiler, "default", goos, goarch) {
   358  		return fmt.Errorf("unsupported GOOS/GOARCH pair %s/%s", goos, goarch)
   359  	}
   360  	return nil
   361  }
   362  
   363  // NewObjdir returns the name of a fresh object directory under b.WorkDir.
   364  // It is up to the caller to call b.Mkdir on the result at an appropriate time.
   365  // The result ends in a slash, so that file names in that directory
   366  // can be constructed with direct string addition.
   367  //
   368  // NewObjdir must be called only from a single goroutine at a time,
   369  // so it is safe to call during action graph construction, but it must not
   370  // be called during action graph execution.
   371  func (b *Builder) NewObjdir() string {
   372  	b.objdirSeq++
   373  	return str.WithFilePathSeparator(filepath.Join(b.WorkDir, fmt.Sprintf("b%03d", b.objdirSeq)))
   374  }
   375  
   376  // readpkglist returns the list of packages that were built into the shared library
   377  // at shlibpath. For the native toolchain this list is stored, newline separated, in
   378  // an ELF note with name "Go\x00\x00" and type 1. For GCCGO it is extracted from the
   379  // .go_export section.
   380  func readpkglist(shlibpath string) (pkgs []*load.Package) {
   381  	var stk load.ImportStack
   382  	if cfg.BuildToolchainName == "gccgo" {
   383  		f, err := elf.Open(shlibpath)
   384  		if err != nil {
   385  			base.Fatal(fmt.Errorf("failed to open shared library: %v", err))
   386  		}
   387  		sect := f.Section(".go_export")
   388  		if sect == nil {
   389  			base.Fatal(fmt.Errorf("%s: missing .go_export section", shlibpath))
   390  		}
   391  		data, err := sect.Data()
   392  		if err != nil {
   393  			base.Fatal(fmt.Errorf("%s: failed to read .go_export section: %v", shlibpath, err))
   394  		}
   395  		pkgpath := []byte("pkgpath ")
   396  		for _, line := range bytes.Split(data, []byte{'\n'}) {
   397  			if path, found := bytes.CutPrefix(line, pkgpath); found {
   398  				path = bytes.TrimSuffix(path, []byte{';'})
   399  				pkgs = append(pkgs, load.LoadPackageWithFlags(string(path), base.Cwd(), &stk, nil, 0))
   400  			}
   401  		}
   402  	} else {
   403  		pkglistbytes, err := buildid.ReadELFNote(shlibpath, "Go\x00\x00", 1)
   404  		if err != nil {
   405  			base.Fatalf("readELFNote failed: %v", err)
   406  		}
   407  		scanner := bufio.NewScanner(bytes.NewBuffer(pkglistbytes))
   408  		for scanner.Scan() {
   409  			t := scanner.Text()
   410  			pkgs = append(pkgs, load.LoadPackageWithFlags(t, base.Cwd(), &stk, nil, 0))
   411  		}
   412  	}
   413  	return
   414  }
   415  
   416  // cacheAction looks up {mode, p} in the cache and returns the resulting action.
   417  // If the cache has no such action, f() is recorded and returned.
   418  // TODO(rsc): Change the second key from *load.Package to interface{},
   419  // to make the caching in linkShared less awkward?
   420  func (b *Builder) cacheAction(mode string, p *load.Package, f func() *Action) *Action {
   421  	a := b.actionCache[cacheKey{mode, p}]
   422  	if a == nil {
   423  		a = f()
   424  		b.actionCache[cacheKey{mode, p}] = a
   425  	}
   426  	return a
   427  }
   428  
   429  // AutoAction returns the "right" action for go build or go install of p.
   430  func (b *Builder) AutoAction(mode, depMode BuildMode, p *load.Package) *Action {
   431  	if p.Name == "main" {
   432  		return b.LinkAction(mode, depMode, p)
   433  	}
   434  	return b.CompileAction(mode, depMode, p)
   435  }
   436  
   437  // buildActor implements the Actor interface for package build
   438  // actions. For most package builds this simply means invoking th
   439  // *Builder.build method; in the case of "go test -cover" for
   440  // a package with no test files, we stores some additional state
   441  // information in the build actor to help with reporting.
   442  type buildActor struct {
   443  	// name of static meta-data file fragment emitted by the cover
   444  	// tool as part of the package build action, for selected
   445  	// "go test -cover" runs.
   446  	covMetaFileName string
   447  }
   448  
   449  // newBuildActor returns a new buildActor object, setting up the
   450  // covMetaFileName field if 'genCoverMeta' flag is set.
   451  func newBuildActor(p *load.Package, genCoverMeta bool) *buildActor {
   452  	ba := &buildActor{}
   453  	if genCoverMeta {
   454  		ba.covMetaFileName = covcmd.MetaFileForPackage(p.ImportPath)
   455  	}
   456  	return ba
   457  }
   458  
   459  func (ba *buildActor) Act(b *Builder, ctx context.Context, a *Action) error {
   460  	return b.build(ctx, a)
   461  }
   462  
   463  // CompileAction returns the action for compiling and possibly installing
   464  // (according to mode) the given package. The resulting action is only
   465  // for building packages (archives), never for linking executables.
   466  // depMode is the action (build or install) to use when building dependencies.
   467  // To turn package main into an executable, call b.Link instead.
   468  func (b *Builder) CompileAction(mode, depMode BuildMode, p *load.Package) *Action {
   469  	vetOnly := mode&ModeVetOnly != 0
   470  	mode &^= ModeVetOnly
   471  
   472  	if mode != ModeBuild && p.Target == "" {
   473  		// No permanent target.
   474  		mode = ModeBuild
   475  	}
   476  	if mode != ModeBuild && p.Name == "main" {
   477  		// We never install the .a file for a main package.
   478  		mode = ModeBuild
   479  	}
   480  
   481  	// Construct package build action.
   482  	a := b.cacheAction("build", p, func() *Action {
   483  		a := &Action{
   484  			Mode:		"build",
   485  			Package:	p,
   486  			Actor:		newBuildActor(p, p.Internal.Cover.GenMeta),
   487  			Objdir:		b.NewObjdir(),
   488  		}
   489  
   490  		if p.Error == nil || !p.Error.IsImportCycle {
   491  			for _, p1 := range p.Internal.Imports {
   492  				a.Deps = append(a.Deps, b.CompileAction(depMode, depMode, p1))
   493  			}
   494  		}
   495  
   496  		if p.Standard {
   497  			switch p.ImportPath {
   498  			case "builtin", "unsafe":
   499  				// Fake packages - nothing to build.
   500  				a.Mode = "built-in package"
   501  				a.Actor = nil
   502  				return a
   503  			}
   504  
   505  			// gccgo standard library is "fake" too.
   506  			if cfg.BuildToolchainName == "gccgo" {
   507  				// the target name is needed for cgo.
   508  				a.Mode = "gccgo stdlib"
   509  				a.Target = p.Target
   510  				a.Actor = nil
   511  				return a
   512  			}
   513  		}
   514  
   515  		return a
   516  	})
   517  
   518  	// Find the build action; the cache entry may have been replaced
   519  	// by the install action during (*Builder).installAction.
   520  	buildAction := a
   521  	switch buildAction.Mode {
   522  	case "build", "built-in package", "gccgo stdlib":
   523  		// ok
   524  	case "build-install":
   525  		buildAction = a.Deps[0]
   526  	default:
   527  		panic("lost build action: " + buildAction.Mode)
   528  	}
   529  	buildAction.needBuild = buildAction.needBuild || !vetOnly
   530  
   531  	// Construct install action.
   532  	if mode == ModeInstall || mode == ModeBuggyInstall {
   533  		a = b.installAction(a, mode)
   534  	}
   535  
   536  	return a
   537  }
   538  
   539  // VetAction returns the action for running go vet on package p.
   540  // It depends on the action for compiling p.
   541  // If the caller may be causing p to be installed, it is up to the caller
   542  // to make sure that the install depends on (runs after) vet.
   543  func (b *Builder) VetAction(mode, depMode BuildMode, p *load.Package) *Action {
   544  	a := b.vetAction(mode, depMode, p)
   545  	a.VetxOnly = false
   546  	return a
   547  }
   548  
   549  func (b *Builder) vetAction(mode, depMode BuildMode, p *load.Package) *Action {
   550  	// Construct vet action.
   551  	a := b.cacheAction("vet", p, func() *Action {
   552  		a1 := b.CompileAction(mode|ModeVetOnly, depMode, p)
   553  
   554  		// vet expects to be able to import "fmt".
   555  		var stk load.ImportStack
   556  		stk.Push("vet")
   557  		p1, err := load.LoadImportWithFlags("fmt", p.Dir, p, &stk, nil, 0)
   558  		if err != nil {
   559  			base.Fatalf("unexpected error loading fmt package from package %s: %v", p.ImportPath, err)
   560  		}
   561  		stk.Pop()
   562  		aFmt := b.CompileAction(ModeBuild, depMode, p1)
   563  
   564  		var deps []*Action
   565  		if a1.buggyInstall {
   566  			// (*Builder).vet expects deps[0] to be the package
   567  			// and deps[1] to be "fmt". If we see buggyInstall
   568  			// here then a1 is an install of a shared library,
   569  			// and the real package is a1.Deps[0].
   570  			deps = []*Action{a1.Deps[0], aFmt, a1}
   571  		} else {
   572  			deps = []*Action{a1, aFmt}
   573  		}
   574  		for _, p1 := range p.Internal.Imports {
   575  			deps = append(deps, b.vetAction(mode, depMode, p1))
   576  		}
   577  
   578  		a := &Action{
   579  			Mode:		"vet",
   580  			Package:	p,
   581  			Deps:		deps,
   582  			Objdir:		a1.Objdir,
   583  			VetxOnly:	true,
   584  			IgnoreFail:	true,	// it's OK if vet of dependencies "fails" (reports problems)
   585  		}
   586  		if a1.Actor == nil {
   587  			// Built-in packages like unsafe.
   588  			return a
   589  		}
   590  		deps[0].needVet = true
   591  		a.Actor = ActorFunc((*Builder).vet)
   592  		return a
   593  	})
   594  	return a
   595  }
   596  
   597  // LinkAction returns the action for linking p into an executable
   598  // and possibly installing the result (according to mode).
   599  // depMode is the action (build or install) to use when compiling dependencies.
   600  func (b *Builder) LinkAction(mode, depMode BuildMode, p *load.Package) *Action {
   601  	// Construct link action.
   602  	a := b.cacheAction("link", p, func() *Action {
   603  		a := &Action{
   604  			Mode:		"link",
   605  			Package:	p,
   606  		}
   607  
   608  		a1 := b.CompileAction(ModeBuild, depMode, p)
   609  		a.Actor = ActorFunc((*Builder).link)
   610  		a.Deps = []*Action{a1}
   611  		a.Objdir = a1.Objdir
   612  
   613  		// An executable file. (This is the name of a temporary file.)
   614  		// Because we run the temporary file in 'go run' and 'go test',
   615  		// the name will show up in ps listings. If the caller has specified
   616  		// a name, use that instead of a.out. The binary is generated
   617  		// in an otherwise empty subdirectory named exe to avoid
   618  		// naming conflicts. The only possible conflict is if we were
   619  		// to create a top-level package named exe.
   620  		name := "a.out"
   621  		if p.Internal.ExeName != "" {
   622  			name = p.Internal.ExeName
   623  		} else if (cfg.Goos == "darwin" || cfg.Goos == "windows") && cfg.BuildBuildmode == "c-shared" && p.Target != "" {
   624  			// On OS X, the linker output name gets recorded in the
   625  			// shared library's LC_ID_DYLIB load command.
   626  			// The code invoking the linker knows to pass only the final
   627  			// path element. Arrange that the path element matches what
   628  			// we'll install it as; otherwise the library is only loadable as "a.out".
   629  			// On Windows, DLL file name is recorded in PE file
   630  			// export section, so do like on OS X.
   631  			_, name = filepath.Split(p.Target)
   632  		}
   633  		a.Target = a.Objdir + filepath.Join("exe", name) + cfg.ExeSuffix
   634  		a.built = a.Target
   635  		b.addTransitiveLinkDeps(a, a1, "")
   636  
   637  		// Sequence the build of the main package (a1) strictly after the build
   638  		// of all other dependencies that go into the link. It is likely to be after
   639  		// them anyway, but just make sure. This is required by the build ID-based
   640  		// shortcut in (*Builder).useCache(a1), which will call b.linkActionID(a).
   641  		// In order for that linkActionID call to compute the right action ID, all the
   642  		// dependencies of a (except a1) must have completed building and have
   643  		// recorded their build IDs.
   644  		a1.Deps = append(a1.Deps, &Action{Mode: "nop", Deps: a.Deps[1:]})
   645  		return a
   646  	})
   647  
   648  	if mode == ModeInstall || mode == ModeBuggyInstall {
   649  		a = b.installAction(a, mode)
   650  	}
   651  
   652  	return a
   653  }
   654  
   655  // installAction returns the action for installing the result of a1.
   656  func (b *Builder) installAction(a1 *Action, mode BuildMode) *Action {
   657  	// Because we overwrite the build action with the install action below,
   658  	// a1 may already be an install action fetched from the "build" cache key,
   659  	// and the caller just doesn't realize.
   660  	if strings.HasSuffix(a1.Mode, "-install") {
   661  		if a1.buggyInstall && mode == ModeInstall {
   662  			//  Congratulations! The buggy install is now a proper install.
   663  			a1.buggyInstall = false
   664  		}
   665  		return a1
   666  	}
   667  
   668  	// If there's no actual action to build a1,
   669  	// there's nothing to install either.
   670  	// This happens if a1 corresponds to reusing an already-built object.
   671  	if a1.Actor == nil {
   672  		return a1
   673  	}
   674  
   675  	p := a1.Package
   676  	return b.cacheAction(a1.Mode+"-install", p, func() *Action {
   677  		// The install deletes the temporary build result,
   678  		// so we need all other actions, both past and future,
   679  		// that attempt to depend on the build to depend instead
   680  		// on the install.
   681  
   682  		// Make a private copy of a1 (the build action),
   683  		// no longer accessible to any other rules.
   684  		buildAction := new(Action)
   685  		*buildAction = *a1
   686  
   687  		// Overwrite a1 with the install action.
   688  		// This takes care of updating past actions that
   689  		// point at a1 for the build action; now they will
   690  		// point at a1 and get the install action.
   691  		// We also leave a1 in the action cache as the result
   692  		// for "build", so that actions not yet created that
   693  		// try to depend on the build will instead depend
   694  		// on the install.
   695  		*a1 = Action{
   696  			Mode:		buildAction.Mode + "-install",
   697  			Actor:		ActorFunc(BuildInstallFunc),
   698  			Package:	p,
   699  			Objdir:		buildAction.Objdir,
   700  			Deps:		[]*Action{buildAction},
   701  			Target:		p.Target,
   702  			built:		p.Target,
   703  
   704  			buggyInstall:	mode == ModeBuggyInstall,
   705  		}
   706  
   707  		b.addInstallHeaderAction(a1)
   708  		return a1
   709  	})
   710  }
   711  
   712  // addTransitiveLinkDeps adds to the link action a all packages
   713  // that are transitive dependencies of a1.Deps.
   714  // That is, if a is a link of package main, a1 is the compile of package main
   715  // and a1.Deps is the actions for building packages directly imported by
   716  // package main (what the compiler needs). The linker needs all packages
   717  // transitively imported by the whole program; addTransitiveLinkDeps
   718  // makes sure those are present in a.Deps.
   719  // If shlib is non-empty, then a corresponds to the build and installation of shlib,
   720  // so any rebuild of shlib should not be added as a dependency.
   721  func (b *Builder) addTransitiveLinkDeps(a, a1 *Action, shlib string) {
   722  	// Expand Deps to include all built packages, for the linker.
   723  	// Use breadth-first search to find rebuilt-for-test packages
   724  	// before the standard ones.
   725  	// TODO(rsc): Eliminate the standard ones from the action graph,
   726  	// which will require doing a little bit more rebuilding.
   727  	workq := []*Action{a1}
   728  	haveDep := map[string]bool{}
   729  	if a1.Package != nil {
   730  		haveDep[a1.Package.ImportPath] = true
   731  	}
   732  	for i := 0; i < len(workq); i++ {
   733  		a1 := workq[i]
   734  		for _, a2 := range a1.Deps {
   735  			// TODO(rsc): Find a better discriminator than the Mode strings, once the dust settles.
   736  			if a2.Package == nil || (a2.Mode != "build-install" && a2.Mode != "build") || haveDep[a2.Package.ImportPath] {
   737  				continue
   738  			}
   739  			haveDep[a2.Package.ImportPath] = true
   740  			a.Deps = append(a.Deps, a2)
   741  			if a2.Mode == "build-install" {
   742  				a2 = a2.Deps[0]	// walk children of "build" action
   743  			}
   744  			workq = append(workq, a2)
   745  		}
   746  	}
   747  
   748  	// If this is go build -linkshared, then the link depends on the shared libraries
   749  	// in addition to the packages themselves. (The compile steps do not.)
   750  	if cfg.BuildLinkshared {
   751  		haveShlib := map[string]bool{shlib: true}
   752  		for _, a1 := range a.Deps {
   753  			p1 := a1.Package
   754  			if p1 == nil || p1.Shlib == "" || haveShlib[filepath.Base(p1.Shlib)] {
   755  				continue
   756  			}
   757  			haveShlib[filepath.Base(p1.Shlib)] = true
   758  			// TODO(rsc): The use of ModeInstall here is suspect, but if we only do ModeBuild,
   759  			// we'll end up building an overall library or executable that depends at runtime
   760  			// on other libraries that are out-of-date, which is clearly not good either.
   761  			// We call it ModeBuggyInstall to make clear that this is not right.
   762  			a.Deps = append(a.Deps, b.linkSharedAction(ModeBuggyInstall, ModeBuggyInstall, p1.Shlib, nil))
   763  		}
   764  	}
   765  }
   766  
   767  // addInstallHeaderAction adds an install header action to a, if needed.
   768  // The action a should be an install action as generated by either
   769  // b.CompileAction or b.LinkAction with mode=ModeInstall,
   770  // and so a.Deps[0] is the corresponding build action.
   771  func (b *Builder) addInstallHeaderAction(a *Action) {
   772  	// Install header for cgo in c-archive and c-shared modes.
   773  	p := a.Package
   774  	if p.UsesCgo() && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") {
   775  		hdrTarget := a.Target[:len(a.Target)-len(filepath.Ext(a.Target))] + ".h"
   776  		if cfg.BuildContext.Compiler == "gccgo" && cfg.BuildO == "" {
   777  			// For the header file, remove the "lib"
   778  			// added by go/build, so we generate pkg.h
   779  			// rather than libpkg.h.
   780  			dir, file := filepath.Split(hdrTarget)
   781  			file = strings.TrimPrefix(file, "lib")
   782  			hdrTarget = filepath.Join(dir, file)
   783  		}
   784  		ah := &Action{
   785  			Mode:		"install header",
   786  			Package:	a.Package,
   787  			Deps:		[]*Action{a.Deps[0]},
   788  			Actor:		ActorFunc((*Builder).installHeader),
   789  			Objdir:		a.Deps[0].Objdir,
   790  			Target:		hdrTarget,
   791  		}
   792  		a.Deps = append(a.Deps, ah)
   793  	}
   794  }
   795  
   796  // buildmodeShared takes the "go build" action a1 into the building of a shared library of a1.Deps.
   797  // That is, the input a1 represents "go build pkgs" and the result represents "go build -buildmode=shared pkgs".
   798  func (b *Builder) buildmodeShared(mode, depMode BuildMode, args []string, pkgs []*load.Package, a1 *Action) *Action {
   799  	name, err := libname(args, pkgs)
   800  	if err != nil {
   801  		base.Fatalf("%v", err)
   802  	}
   803  	return b.linkSharedAction(mode, depMode, name, a1)
   804  }
   805  
   806  // linkSharedAction takes a grouping action a1 corresponding to a list of built packages
   807  // and returns an action that links them together into a shared library with the name shlib.
   808  // If a1 is nil, shlib should be an absolute path to an existing shared library,
   809  // and then linkSharedAction reads that library to find out the package list.
   810  func (b *Builder) linkSharedAction(mode, depMode BuildMode, shlib string, a1 *Action) *Action {
   811  	fullShlib := shlib
   812  	shlib = filepath.Base(shlib)
   813  	a := b.cacheAction("build-shlib "+shlib, nil, func() *Action {
   814  		if a1 == nil {
   815  			// TODO(rsc): Need to find some other place to store config,
   816  			// not in pkg directory. See golang.org/issue/22196.
   817  			pkgs := readpkglist(fullShlib)
   818  			a1 = &Action{
   819  				Mode: "shlib packages",
   820  			}
   821  			for _, p := range pkgs {
   822  				a1.Deps = append(a1.Deps, b.CompileAction(mode, depMode, p))
   823  			}
   824  		}
   825  
   826  		// Fake package to hold ldflags.
   827  		// As usual shared libraries are a kludgy, abstraction-violating special case:
   828  		// we let them use the flags specified for the command-line arguments.
   829  		p := &load.Package{}
   830  		p.Internal.CmdlinePkg = true
   831  		p.Internal.Ldflags = load.BuildLdflags.For(p)
   832  		p.Internal.Gccgoflags = load.BuildGccgoflags.For(p)
   833  
   834  		// Add implicit dependencies to pkgs list.
   835  		// Currently buildmode=shared forces external linking mode, and
   836  		// external linking mode forces an import of runtime/cgo (and
   837  		// math on arm). So if it was not passed on the command line and
   838  		// it is not present in another shared library, add it here.
   839  		// TODO(rsc): Maybe this should only happen if "runtime" is in the original package set.
   840  		// TODO(rsc): This should probably be changed to use load.LinkerDeps(p).
   841  		// TODO(rsc): We don't add standard library imports for gccgo
   842  		// because they are all always linked in anyhow.
   843  		// Maybe load.LinkerDeps should be used and updated.
   844  		a := &Action{
   845  			Mode:		"go build -buildmode=shared",
   846  			Package:	p,
   847  			Objdir:		b.NewObjdir(),
   848  			Actor:		ActorFunc((*Builder).linkShared),
   849  			Deps:		[]*Action{a1},
   850  		}
   851  		a.Target = filepath.Join(a.Objdir, shlib)
   852  		if cfg.BuildToolchainName != "gccgo" {
   853  			add := func(a1 *Action, pkg string, force bool) {
   854  				for _, a2 := range a1.Deps {
   855  					if a2.Package != nil && a2.Package.ImportPath == pkg {
   856  						return
   857  					}
   858  				}
   859  				var stk load.ImportStack
   860  				p := load.LoadPackageWithFlags(pkg, base.Cwd(), &stk, nil, 0)
   861  				if p.Error != nil {
   862  					base.Fatalf("load %s: %v", pkg, p.Error)
   863  				}
   864  				// Assume that if pkg (runtime/cgo or math)
   865  				// is already accounted for in a different shared library,
   866  				// then that shared library also contains runtime,
   867  				// so that anything we do will depend on that library,
   868  				// so we don't need to include pkg in our shared library.
   869  				if force || p.Shlib == "" || filepath.Base(p.Shlib) == pkg {
   870  					a1.Deps = append(a1.Deps, b.CompileAction(depMode, depMode, p))
   871  				}
   872  			}
   873  			add(a1, "runtime/cgo", false)
   874  			if cfg.Goarch == "arm" {
   875  				add(a1, "math", false)
   876  			}
   877  
   878  			// The linker step still needs all the usual linker deps.
   879  			// (For example, the linker always opens runtime.a.)
   880  			ldDeps, err := load.LinkerDeps(nil)
   881  			if err != nil {
   882  				base.Error(err)
   883  			}
   884  			for _, dep := range ldDeps {
   885  				add(a, dep, true)
   886  			}
   887  		}
   888  		b.addTransitiveLinkDeps(a, a1, shlib)
   889  		return a
   890  	})
   891  
   892  	// Install result.
   893  	if (mode == ModeInstall || mode == ModeBuggyInstall) && a.Actor != nil {
   894  		buildAction := a
   895  
   896  		a = b.cacheAction("install-shlib "+shlib, nil, func() *Action {
   897  			// Determine the eventual install target.
   898  			// The install target is root/pkg/shlib, where root is the source root
   899  			// in which all the packages lie.
   900  			// TODO(rsc): Perhaps this cross-root check should apply to the full
   901  			// transitive package dependency list, not just the ones named
   902  			// on the command line?
   903  			pkgDir := a1.Deps[0].Package.Internal.Build.PkgTargetRoot
   904  			for _, a2 := range a1.Deps {
   905  				if dir := a2.Package.Internal.Build.PkgTargetRoot; dir != pkgDir {
   906  					base.Fatalf("installing shared library: cannot use packages %s and %s from different roots %s and %s",
   907  						a1.Deps[0].Package.ImportPath,
   908  						a2.Package.ImportPath,
   909  						pkgDir,
   910  						dir)
   911  				}
   912  			}
   913  			// TODO(rsc): Find out and explain here why gccgo is different.
   914  			if cfg.BuildToolchainName == "gccgo" {
   915  				pkgDir = filepath.Join(pkgDir, "shlibs")
   916  			}
   917  			target := filepath.Join(pkgDir, shlib)
   918  
   919  			a := &Action{
   920  				Mode:	"go install -buildmode=shared",
   921  				Objdir:	buildAction.Objdir,
   922  				Actor:	ActorFunc(BuildInstallFunc),
   923  				Deps:	[]*Action{buildAction},
   924  				Target:	target,
   925  			}
   926  			for _, a2 := range buildAction.Deps[0].Deps {
   927  				p := a2.Package
   928  				pkgTargetRoot := p.Internal.Build.PkgTargetRoot
   929  				if pkgTargetRoot == "" {
   930  					continue
   931  				}
   932  				a.Deps = append(a.Deps, &Action{
   933  					Mode:		"shlibname",
   934  					Package:	p,
   935  					Actor:		ActorFunc((*Builder).installShlibname),
   936  					Target:		filepath.Join(pkgTargetRoot, p.ImportPath+".shlibname"),
   937  					Deps:		[]*Action{a.Deps[0]},
   938  				})
   939  			}
   940  			return a
   941  		})
   942  	}
   943  
   944  	return a
   945  }