github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/cmd/go/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  	"container/heap"
    13  	"debug/elf"
    14  	"encoding/json"
    15  	"fmt"
    16  	"io/ioutil"
    17  	"os"
    18  	"path/filepath"
    19  	"strings"
    20  	"sync"
    21  
    22  	"cmd/go/internal/base"
    23  	"cmd/go/internal/cache"
    24  	"cmd/go/internal/cfg"
    25  	"cmd/go/internal/load"
    26  	"cmd/internal/buildid"
    27  )
    28  
    29  // A Builder holds global state about a build.
    30  // It does not hold per-package state, because we
    31  // build packages in parallel, and the builder is shared.
    32  type Builder struct {
    33  	WorkDir     string               // the temporary work directory (ends in filepath.Separator)
    34  	actionCache map[cacheKey]*Action // a cache of already-constructed actions
    35  	mkdirCache  map[string]bool      // a cache of created directories
    36  	flagCache   map[[2]string]bool   // a cache of supported compiler flags
    37  	Print       func(args ...interface{}) (int, error)
    38  
    39  	ComputeStaleOnly bool // compute staleness for go list; no actual build
    40  
    41  	objdirSeq int // counter for NewObjdir
    42  	pkgSeq    int
    43  
    44  	output    sync.Mutex
    45  	scriptDir string // current directory in printed script
    46  
    47  	exec      sync.Mutex
    48  	readySema chan bool
    49  	ready     actionQueue
    50  
    51  	id           sync.Mutex
    52  	toolIDCache  map[string]string // tool name -> tool ID
    53  	buildIDCache map[string]string // file name -> build ID
    54  }
    55  
    56  // NOTE: Much of Action would not need to be exported if not for test.
    57  // Maybe test functionality should move into this package too?
    58  
    59  // An Action represents a single action in the action graph.
    60  type Action struct {
    61  	Mode       string                        // description of action operation
    62  	Package    *load.Package                 // the package this action works on
    63  	Deps       []*Action                     // actions that must happen before this one
    64  	Func       func(*Builder, *Action) error // the action itself (nil = no-op)
    65  	IgnoreFail bool                          // whether to run f even if dependencies fail
    66  	TestOutput *bytes.Buffer                 // test output buffer
    67  	Args       []string                      // additional args for runProgram
    68  
    69  	triggers []*Action // inverse of deps
    70  
    71  	buggyInstall bool // is this a buggy install (see -linkshared)?
    72  
    73  	TryCache func(*Builder, *Action) bool // callback for cache bypass
    74  
    75  	// Generated files, directories.
    76  	Objdir   string         // directory for intermediate objects
    77  	Target   string         // goal of the action: the created package or executable
    78  	built    string         // the actual created package or executable
    79  	actionID cache.ActionID // cache ID of action input
    80  	buildID  string         // build ID of action output
    81  
    82  	needVet bool       // Mode=="build": need to fill in vet config
    83  	vetCfg  *vetConfig // vet config
    84  
    85  	// Execution state.
    86  	pending  int  // number of deps yet to complete
    87  	priority int  // relative execution priority
    88  	Failed   bool // whether the action failed
    89  }
    90  
    91  // BuildActionID returns the action ID section of a's build ID.
    92  func (a *Action) BuildActionID() string { return actionID(a.buildID) }
    93  
    94  // BuildContentID returns the content ID section of a's build ID.
    95  func (a *Action) BuildContentID() string { return contentID(a.buildID) }
    96  
    97  // BuildID returns a's build ID.
    98  func (a *Action) BuildID() string { return a.buildID }
    99  
   100  // An actionQueue is a priority queue of actions.
   101  type actionQueue []*Action
   102  
   103  // Implement heap.Interface
   104  func (q *actionQueue) Len() int           { return len(*q) }
   105  func (q *actionQueue) Swap(i, j int)      { (*q)[i], (*q)[j] = (*q)[j], (*q)[i] }
   106  func (q *actionQueue) Less(i, j int) bool { return (*q)[i].priority < (*q)[j].priority }
   107  func (q *actionQueue) Push(x interface{}) { *q = append(*q, x.(*Action)) }
   108  func (q *actionQueue) Pop() interface{} {
   109  	n := len(*q) - 1
   110  	x := (*q)[n]
   111  	*q = (*q)[:n]
   112  	return x
   113  }
   114  
   115  func (q *actionQueue) push(a *Action) {
   116  	heap.Push(q, a)
   117  }
   118  
   119  func (q *actionQueue) pop() *Action {
   120  	return heap.Pop(q).(*Action)
   121  }
   122  
   123  type actionJSON struct {
   124  	ID         int
   125  	Mode       string
   126  	Package    string
   127  	Deps       []int    `json:",omitempty"`
   128  	IgnoreFail bool     `json:",omitempty"`
   129  	Args       []string `json:",omitempty"`
   130  	Link       bool     `json:",omitempty"`
   131  	Objdir     string   `json:",omitempty"`
   132  	Target     string   `json:",omitempty"`
   133  	Priority   int      `json:",omitempty"`
   134  	Failed     bool     `json:",omitempty"`
   135  	Built      string   `json:",omitempty"`
   136  }
   137  
   138  // cacheKey is the key for the action cache.
   139  type cacheKey struct {
   140  	mode string
   141  	p    *load.Package
   142  }
   143  
   144  func actionGraphJSON(a *Action) string {
   145  	var workq []*Action
   146  	var inWorkq = make(map[*Action]int)
   147  
   148  	add := func(a *Action) {
   149  		if _, ok := inWorkq[a]; ok {
   150  			return
   151  		}
   152  		inWorkq[a] = len(workq)
   153  		workq = append(workq, a)
   154  	}
   155  	add(a)
   156  
   157  	for i := 0; i < len(workq); i++ {
   158  		for _, dep := range workq[i].Deps {
   159  			add(dep)
   160  		}
   161  	}
   162  
   163  	var list []*actionJSON
   164  	for id, a := range workq {
   165  		aj := &actionJSON{
   166  			Mode:       a.Mode,
   167  			ID:         id,
   168  			IgnoreFail: a.IgnoreFail,
   169  			Args:       a.Args,
   170  			Objdir:     a.Objdir,
   171  			Target:     a.Target,
   172  			Failed:     a.Failed,
   173  			Priority:   a.priority,
   174  			Built:      a.built,
   175  		}
   176  		if a.Package != nil {
   177  			// TODO(rsc): Make this a unique key for a.Package somehow.
   178  			aj.Package = a.Package.ImportPath
   179  		}
   180  		for _, a1 := range a.Deps {
   181  			aj.Deps = append(aj.Deps, inWorkq[a1])
   182  		}
   183  		list = append(list, aj)
   184  	}
   185  
   186  	js, err := json.MarshalIndent(list, "", "\t")
   187  	if err != nil {
   188  		fmt.Fprintf(os.Stderr, "go: writing debug action graph: %v\n", err)
   189  		return ""
   190  	}
   191  	return string(js)
   192  }
   193  
   194  // BuildMode specifies the build mode:
   195  // are we just building things or also installing the results?
   196  type BuildMode int
   197  
   198  const (
   199  	ModeBuild BuildMode = iota
   200  	ModeInstall
   201  	ModeBuggyInstall
   202  )
   203  
   204  func (b *Builder) Init() {
   205  	var err error
   206  	b.Print = func(a ...interface{}) (int, error) {
   207  		return fmt.Fprint(os.Stderr, a...)
   208  	}
   209  	b.actionCache = make(map[cacheKey]*Action)
   210  	b.mkdirCache = make(map[string]bool)
   211  	b.toolIDCache = make(map[string]string)
   212  	b.buildIDCache = make(map[string]string)
   213  
   214  	if cfg.BuildN {
   215  		b.WorkDir = "$WORK"
   216  	} else {
   217  		b.WorkDir, err = ioutil.TempDir(os.Getenv("GOTMPDIR"), "go-build")
   218  		if err != nil {
   219  			base.Fatalf("%s", err)
   220  		}
   221  		if cfg.BuildX || cfg.BuildWork {
   222  			fmt.Fprintf(os.Stderr, "WORK=%s\n", b.WorkDir)
   223  		}
   224  		if !cfg.BuildWork {
   225  			workdir := b.WorkDir
   226  			base.AtExit(func() { os.RemoveAll(workdir) })
   227  		}
   228  	}
   229  
   230  	if _, ok := cfg.OSArchSupportsCgo[cfg.Goos+"/"+cfg.Goarch]; !ok && cfg.BuildContext.Compiler == "gc" {
   231  		fmt.Fprintf(os.Stderr, "cmd/go: unsupported GOOS/GOARCH pair %s/%s\n", cfg.Goos, cfg.Goarch)
   232  		os.Exit(2)
   233  	}
   234  	for _, tag := range cfg.BuildContext.BuildTags {
   235  		if strings.Contains(tag, ",") {
   236  			fmt.Fprintf(os.Stderr, "cmd/go: -tags space-separated list contains comma\n")
   237  			os.Exit(2)
   238  		}
   239  	}
   240  }
   241  
   242  // NewObjdir returns the name of a fresh object directory under b.WorkDir.
   243  // It is up to the caller to call b.Mkdir on the result at an appropriate time.
   244  // The result ends in a slash, so that file names in that directory
   245  // can be constructed with direct string addition.
   246  //
   247  // NewObjdir must be called only from a single goroutine at a time,
   248  // so it is safe to call during action graph construction, but it must not
   249  // be called during action graph execution.
   250  func (b *Builder) NewObjdir() string {
   251  	b.objdirSeq++
   252  	return filepath.Join(b.WorkDir, fmt.Sprintf("b%03d", b.objdirSeq)) + string(filepath.Separator)
   253  }
   254  
   255  // readpkglist returns the list of packages that were built into the shared library
   256  // at shlibpath. For the native toolchain this list is stored, newline separated, in
   257  // an ELF note with name "Go\x00\x00" and type 1. For GCCGO it is extracted from the
   258  // .go_export section.
   259  func readpkglist(shlibpath string) (pkgs []*load.Package) {
   260  	var stk load.ImportStack
   261  	if cfg.BuildToolchainName == "gccgo" {
   262  		f, _ := elf.Open(shlibpath)
   263  		sect := f.Section(".go_export")
   264  		data, _ := sect.Data()
   265  		scanner := bufio.NewScanner(bytes.NewBuffer(data))
   266  		for scanner.Scan() {
   267  			t := scanner.Text()
   268  			if strings.HasPrefix(t, "pkgpath ") {
   269  				t = strings.TrimPrefix(t, "pkgpath ")
   270  				t = strings.TrimSuffix(t, ";")
   271  				pkgs = append(pkgs, load.LoadPackage(t, &stk))
   272  			}
   273  		}
   274  	} else {
   275  		pkglistbytes, err := buildid.ReadELFNote(shlibpath, "Go\x00\x00", 1)
   276  		if err != nil {
   277  			base.Fatalf("readELFNote failed: %v", err)
   278  		}
   279  		scanner := bufio.NewScanner(bytes.NewBuffer(pkglistbytes))
   280  		for scanner.Scan() {
   281  			t := scanner.Text()
   282  			pkgs = append(pkgs, load.LoadPackage(t, &stk))
   283  		}
   284  	}
   285  	return
   286  }
   287  
   288  // cacheAction looks up {mode, p} in the cache and returns the resulting action.
   289  // If the cache has no such action, f() is recorded and returned.
   290  // TODO(rsc): Change the second key from *load.Package to interface{},
   291  // to make the caching in linkShared less awkward?
   292  func (b *Builder) cacheAction(mode string, p *load.Package, f func() *Action) *Action {
   293  	a := b.actionCache[cacheKey{mode, p}]
   294  	if a == nil {
   295  		a = f()
   296  		b.actionCache[cacheKey{mode, p}] = a
   297  	}
   298  	return a
   299  }
   300  
   301  // AutoAction returns the "right" action for go build or go install of p.
   302  func (b *Builder) AutoAction(mode, depMode BuildMode, p *load.Package) *Action {
   303  	if p.Name == "main" {
   304  		return b.LinkAction(mode, depMode, p)
   305  	}
   306  	return b.CompileAction(mode, depMode, p)
   307  }
   308  
   309  // CompileAction returns the action for compiling and possibly installing
   310  // (according to mode) the given package. The resulting action is only
   311  // for building packages (archives), never for linking executables.
   312  // depMode is the action (build or install) to use when building dependencies.
   313  // To turn package main into an executable, call b.Link instead.
   314  func (b *Builder) CompileAction(mode, depMode BuildMode, p *load.Package) *Action {
   315  	if mode != ModeBuild && p.Internal.Local && p.Target == "" {
   316  		// Imported via local path. No permanent target.
   317  		mode = ModeBuild
   318  	}
   319  	if mode != ModeBuild && p.Name == "main" {
   320  		// We never install the .a file for a main package.
   321  		mode = ModeBuild
   322  	}
   323  
   324  	// Construct package build action.
   325  	a := b.cacheAction("build", p, func() *Action {
   326  		a := &Action{
   327  			Mode:    "build",
   328  			Package: p,
   329  			Func:    (*Builder).build,
   330  			Objdir:  b.NewObjdir(),
   331  		}
   332  
   333  		for _, p1 := range p.Internal.Imports {
   334  			a.Deps = append(a.Deps, b.CompileAction(depMode, depMode, p1))
   335  		}
   336  
   337  		if p.Standard {
   338  			switch p.ImportPath {
   339  			case "builtin", "unsafe":
   340  				// Fake packages - nothing to build.
   341  				a.Mode = "built-in package"
   342  				a.Func = nil
   343  				return a
   344  			}
   345  
   346  			// gccgo standard library is "fake" too.
   347  			if cfg.BuildToolchainName == "gccgo" {
   348  				// the target name is needed for cgo.
   349  				a.Mode = "gccgo stdlib"
   350  				a.Target = p.Target
   351  				a.Func = nil
   352  				return a
   353  			}
   354  		}
   355  
   356  		return a
   357  	})
   358  
   359  	// Construct install action.
   360  	if mode == ModeInstall || mode == ModeBuggyInstall {
   361  		a = b.installAction(a, mode)
   362  	}
   363  
   364  	return a
   365  }
   366  
   367  // VetAction returns the action for running go vet on package p.
   368  // It depends on the action for compiling p.
   369  // If the caller may be causing p to be installed, it is up to the caller
   370  // to make sure that the install depends on (runs after) vet.
   371  func (b *Builder) VetAction(mode, depMode BuildMode, p *load.Package) *Action {
   372  	// Construct vet action.
   373  	a := b.cacheAction("vet", p, func() *Action {
   374  		a1 := b.CompileAction(mode, depMode, p)
   375  
   376  		// vet expects to be able to import "fmt".
   377  		var stk load.ImportStack
   378  		stk.Push("vet")
   379  		p1 := load.LoadPackage("fmt", &stk)
   380  		stk.Pop()
   381  		aFmt := b.CompileAction(ModeBuild, depMode, p1)
   382  
   383  		a := &Action{
   384  			Mode:    "vet",
   385  			Package: p,
   386  			Deps:    []*Action{a1, aFmt},
   387  			Objdir:  a1.Objdir,
   388  		}
   389  		if a1.Func == nil {
   390  			// Built-in packages like unsafe.
   391  			return a
   392  		}
   393  		a1.needVet = true
   394  		a.Func = (*Builder).vet
   395  
   396  		return a
   397  	})
   398  	return a
   399  }
   400  
   401  // LinkAction returns the action for linking p into an executable
   402  // and possibly installing the result (according to mode).
   403  // depMode is the action (build or install) to use when compiling dependencies.
   404  func (b *Builder) LinkAction(mode, depMode BuildMode, p *load.Package) *Action {
   405  	// Construct link action.
   406  	a := b.cacheAction("link", p, func() *Action {
   407  		a := &Action{
   408  			Mode:    "link",
   409  			Package: p,
   410  		}
   411  
   412  		a1 := b.CompileAction(ModeBuild, depMode, p)
   413  		a.Func = (*Builder).link
   414  		a.Deps = []*Action{a1}
   415  		a.Objdir = a1.Objdir
   416  
   417  		// An executable file. (This is the name of a temporary file.)
   418  		// Because we run the temporary file in 'go run' and 'go test',
   419  		// the name will show up in ps listings. If the caller has specified
   420  		// a name, use that instead of a.out. The binary is generated
   421  		// in an otherwise empty subdirectory named exe to avoid
   422  		// naming conflicts. The only possible conflict is if we were
   423  		// to create a top-level package named exe.
   424  		name := "a.out"
   425  		if p.Internal.ExeName != "" {
   426  			name = p.Internal.ExeName
   427  		} else if (cfg.Goos == "darwin" || cfg.Goos == "windows") && cfg.BuildBuildmode == "c-shared" && p.Target != "" {
   428  			// On OS X, the linker output name gets recorded in the
   429  			// shared library's LC_ID_DYLIB load command.
   430  			// The code invoking the linker knows to pass only the final
   431  			// path element. Arrange that the path element matches what
   432  			// we'll install it as; otherwise the library is only loadable as "a.out".
   433  			// On Windows, DLL file name is recorded in PE file
   434  			// export section, so do like on OS X.
   435  			_, name = filepath.Split(p.Target)
   436  		}
   437  		a.Target = a.Objdir + filepath.Join("exe", name) + cfg.ExeSuffix
   438  		a.built = a.Target
   439  		b.addTransitiveLinkDeps(a, a1, "")
   440  
   441  		// Sequence the build of the main package (a1) strictly after the build
   442  		// of all other dependencies that go into the link. It is likely to be after
   443  		// them anyway, but just make sure. This is required by the build ID-based
   444  		// shortcut in (*Builder).useCache(a1), which will call b.linkActionID(a).
   445  		// In order for that linkActionID call to compute the right action ID, all the
   446  		// dependencies of a (except a1) must have completed building and have
   447  		// recorded their build IDs.
   448  		a1.Deps = append(a1.Deps, &Action{Mode: "nop", Deps: a.Deps[1:]})
   449  		return a
   450  	})
   451  
   452  	if mode == ModeInstall || mode == ModeBuggyInstall {
   453  		a = b.installAction(a, mode)
   454  	}
   455  
   456  	return a
   457  }
   458  
   459  // installAction returns the action for installing the result of a1.
   460  func (b *Builder) installAction(a1 *Action, mode BuildMode) *Action {
   461  	// Because we overwrite the build action with the install action below,
   462  	// a1 may already be an install action fetched from the "build" cache key,
   463  	// and the caller just doesn't realize.
   464  	if strings.HasSuffix(a1.Mode, "-install") {
   465  		if a1.buggyInstall && mode == ModeInstall {
   466  			//  Congratulations! The buggy install is now a proper install.
   467  			a1.buggyInstall = false
   468  		}
   469  		return a1
   470  	}
   471  
   472  	// If there's no actual action to build a1,
   473  	// there's nothing to install either.
   474  	// This happens if a1 corresponds to reusing an already-built object.
   475  	if a1.Func == nil {
   476  		return a1
   477  	}
   478  
   479  	p := a1.Package
   480  	return b.cacheAction(a1.Mode+"-install", p, func() *Action {
   481  		// The install deletes the temporary build result,
   482  		// so we need all other actions, both past and future,
   483  		// that attempt to depend on the build to depend instead
   484  		// on the install.
   485  
   486  		// Make a private copy of a1 (the build action),
   487  		// no longer accessible to any other rules.
   488  		buildAction := new(Action)
   489  		*buildAction = *a1
   490  
   491  		// Overwrite a1 with the install action.
   492  		// This takes care of updating past actions that
   493  		// point at a1 for the build action; now they will
   494  		// point at a1 and get the install action.
   495  		// We also leave a1 in the action cache as the result
   496  		// for "build", so that actions not yet created that
   497  		// try to depend on the build will instead depend
   498  		// on the install.
   499  		*a1 = Action{
   500  			Mode:    buildAction.Mode + "-install",
   501  			Func:    BuildInstallFunc,
   502  			Package: p,
   503  			Objdir:  buildAction.Objdir,
   504  			Deps:    []*Action{buildAction},
   505  			Target:  p.Target,
   506  			built:   p.Target,
   507  
   508  			buggyInstall: mode == ModeBuggyInstall,
   509  		}
   510  
   511  		b.addInstallHeaderAction(a1)
   512  		return a1
   513  	})
   514  }
   515  
   516  // addTransitiveLinkDeps adds to the link action a all packages
   517  // that are transitive dependencies of a1.Deps.
   518  // That is, if a is a link of package main, a1 is the compile of package main
   519  // and a1.Deps is the actions for building packages directly imported by
   520  // package main (what the compiler needs). The linker needs all packages
   521  // transitively imported by the whole program; addTransitiveLinkDeps
   522  // makes sure those are present in a.Deps.
   523  // If shlib is non-empty, then a corresponds to the build and installation of shlib,
   524  // so any rebuild of shlib should not be added as a dependency.
   525  func (b *Builder) addTransitiveLinkDeps(a, a1 *Action, shlib string) {
   526  	// Expand Deps to include all built packages, for the linker.
   527  	// Use breadth-first search to find rebuilt-for-test packages
   528  	// before the standard ones.
   529  	// TODO(rsc): Eliminate the standard ones from the action graph,
   530  	// which will require doing a little bit more rebuilding.
   531  	workq := []*Action{a1}
   532  	haveDep := map[string]bool{}
   533  	if a1.Package != nil {
   534  		haveDep[a1.Package.ImportPath] = true
   535  	}
   536  	for i := 0; i < len(workq); i++ {
   537  		a1 := workq[i]
   538  		for _, a2 := range a1.Deps {
   539  			// TODO(rsc): Find a better discriminator than the Mode strings, once the dust settles.
   540  			if a2.Package == nil || (a2.Mode != "build-install" && a2.Mode != "build") || haveDep[a2.Package.ImportPath] {
   541  				continue
   542  			}
   543  			haveDep[a2.Package.ImportPath] = true
   544  			a.Deps = append(a.Deps, a2)
   545  			if a2.Mode == "build-install" {
   546  				a2 = a2.Deps[0] // walk children of "build" action
   547  			}
   548  			workq = append(workq, a2)
   549  		}
   550  	}
   551  
   552  	// If this is go build -linkshared, then the link depends on the shared libraries
   553  	// in addition to the packages themselves. (The compile steps do not.)
   554  	if cfg.BuildLinkshared {
   555  		haveShlib := map[string]bool{shlib: true}
   556  		for _, a1 := range a.Deps {
   557  			p1 := a1.Package
   558  			if p1 == nil || p1.Shlib == "" || haveShlib[filepath.Base(p1.Shlib)] {
   559  				continue
   560  			}
   561  			haveShlib[filepath.Base(p1.Shlib)] = true
   562  			// TODO(rsc): The use of ModeInstall here is suspect, but if we only do ModeBuild,
   563  			// we'll end up building an overall library or executable that depends at runtime
   564  			// on other libraries that are out-of-date, which is clearly not good either.
   565  			// We call it ModeBuggyInstall to make clear that this is not right.
   566  			a.Deps = append(a.Deps, b.linkSharedAction(ModeBuggyInstall, ModeBuggyInstall, p1.Shlib, nil))
   567  		}
   568  	}
   569  }
   570  
   571  // addInstallHeaderAction adds an install header action to a, if needed.
   572  // The action a should be an install action as generated by either
   573  // b.CompileAction or b.LinkAction with mode=ModeInstall,
   574  // and so a.Deps[0] is the corresponding build action.
   575  func (b *Builder) addInstallHeaderAction(a *Action) {
   576  	// Install header for cgo in c-archive and c-shared modes.
   577  	p := a.Package
   578  	if p.UsesCgo() && (cfg.BuildBuildmode == "c-archive" || cfg.BuildBuildmode == "c-shared") {
   579  		hdrTarget := a.Target[:len(a.Target)-len(filepath.Ext(a.Target))] + ".h"
   580  		if cfg.BuildContext.Compiler == "gccgo" {
   581  			// For the header file, remove the "lib"
   582  			// added by go/build, so we generate pkg.h
   583  			// rather than libpkg.h.
   584  			dir, file := filepath.Split(hdrTarget)
   585  			file = strings.TrimPrefix(file, "lib")
   586  			hdrTarget = filepath.Join(dir, file)
   587  		}
   588  		ah := &Action{
   589  			Mode:    "install header",
   590  			Package: a.Package,
   591  			Deps:    []*Action{a.Deps[0]},
   592  			Func:    (*Builder).installHeader,
   593  			Objdir:  a.Deps[0].Objdir,
   594  			Target:  hdrTarget,
   595  		}
   596  		a.Deps = append(a.Deps, ah)
   597  	}
   598  }
   599  
   600  // buildmodeShared takes the "go build" action a1 into the building of a shared library of a1.Deps.
   601  // That is, the input a1 represents "go build pkgs" and the result represents "go build -buidmode=shared pkgs".
   602  func (b *Builder) buildmodeShared(mode, depMode BuildMode, args []string, pkgs []*load.Package, a1 *Action) *Action {
   603  	name, err := libname(args, pkgs)
   604  	if err != nil {
   605  		base.Fatalf("%v", err)
   606  	}
   607  	return b.linkSharedAction(mode, depMode, name, a1)
   608  }
   609  
   610  // linkSharedAction takes a grouping action a1 corresponding to a list of built packages
   611  // and returns an action that links them together into a shared library with the name shlib.
   612  // If a1 is nil, shlib should be an absolute path to an existing shared library,
   613  // and then linkSharedAction reads that library to find out the package list.
   614  func (b *Builder) linkSharedAction(mode, depMode BuildMode, shlib string, a1 *Action) *Action {
   615  	fullShlib := shlib
   616  	shlib = filepath.Base(shlib)
   617  	a := b.cacheAction("build-shlib "+shlib, nil, func() *Action {
   618  		if a1 == nil {
   619  			// TODO(rsc): Need to find some other place to store config,
   620  			// not in pkg directory. See golang.org/issue/22196.
   621  			pkgs := readpkglist(fullShlib)
   622  			a1 = &Action{
   623  				Mode: "shlib packages",
   624  			}
   625  			for _, p := range pkgs {
   626  				a1.Deps = append(a1.Deps, b.CompileAction(mode, depMode, p))
   627  			}
   628  		}
   629  
   630  		// Fake package to hold ldflags.
   631  		// As usual shared libraries are a kludgy, abstraction-violating special case:
   632  		// we let them use the flags specified for the command-line arguments.
   633  		p := &load.Package{}
   634  		p.Internal.CmdlinePkg = true
   635  		p.Internal.Ldflags = load.BuildLdflags.For(p)
   636  		p.Internal.Gccgoflags = load.BuildGccgoflags.For(p)
   637  
   638  		// Add implicit dependencies to pkgs list.
   639  		// Currently buildmode=shared forces external linking mode, and
   640  		// external linking mode forces an import of runtime/cgo (and
   641  		// math on arm). So if it was not passed on the command line and
   642  		// it is not present in another shared library, add it here.
   643  		// TODO(rsc): Maybe this should only happen if "runtime" is in the original package set.
   644  		// TODO(rsc): This should probably be changed to use load.LinkerDeps(p).
   645  		// TODO(rsc): Find out and explain here why gccgo is excluded.
   646  		// If the answer is that gccgo is different in implicit linker deps, maybe
   647  		// load.LinkerDeps should be used and updated.
   648  		// Link packages into a shared library.
   649  
   650  		a := &Action{
   651  			Mode:    "go build -buildmode=shared",
   652  			Package: p,
   653  			Objdir:  b.NewObjdir(),
   654  			Func:    (*Builder).linkShared,
   655  			Deps:    []*Action{a1},
   656  		}
   657  		a.Target = filepath.Join(a.Objdir, shlib)
   658  		if cfg.BuildToolchainName != "gccgo" {
   659  			add := func(a1 *Action, pkg string, force bool) {
   660  				for _, a2 := range a1.Deps {
   661  					if a2.Package != nil && a2.Package.ImportPath == pkg {
   662  						return
   663  					}
   664  				}
   665  				var stk load.ImportStack
   666  				p := load.LoadPackage(pkg, &stk)
   667  				if p.Error != nil {
   668  					base.Fatalf("load %s: %v", pkg, p.Error)
   669  				}
   670  				// Assume that if pkg (runtime/cgo or math)
   671  				// is already accounted for in a different shared library,
   672  				// then that shared library also contains runtime,
   673  				// so that anything we do will depend on that library,
   674  				// so we don't need to include pkg in our shared library.
   675  				if force || p.Shlib == "" || filepath.Base(p.Shlib) == pkg {
   676  					a1.Deps = append(a1.Deps, b.CompileAction(depMode, depMode, p))
   677  				}
   678  			}
   679  			add(a1, "runtime/cgo", false)
   680  			if cfg.Goarch == "arm" {
   681  				add(a1, "math", false)
   682  			}
   683  
   684  			// The linker step still needs all the usual linker deps.
   685  			// (For example, the linker always opens runtime.a.)
   686  			for _, dep := range load.LinkerDeps(nil) {
   687  				add(a, dep, true)
   688  			}
   689  		}
   690  		b.addTransitiveLinkDeps(a, a1, shlib)
   691  		return a
   692  	})
   693  
   694  	// Install result.
   695  	if (mode == ModeInstall || mode == ModeBuggyInstall) && a.Func != nil {
   696  		buildAction := a
   697  
   698  		a = b.cacheAction("install-shlib "+shlib, nil, func() *Action {
   699  			// Determine the eventual install target.
   700  			// The install target is root/pkg/shlib, where root is the source root
   701  			// in which all the packages lie.
   702  			// TODO(rsc): Perhaps this cross-root check should apply to the full
   703  			// transitive package dependency list, not just the ones named
   704  			// on the command line?
   705  			pkgDir := a1.Deps[0].Package.Internal.Build.PkgTargetRoot
   706  			for _, a2 := range a1.Deps {
   707  				if dir := a2.Package.Internal.Build.PkgTargetRoot; dir != pkgDir {
   708  					base.Fatalf("installing shared library: cannot use packages %s and %s from different roots %s and %s",
   709  						a1.Deps[0].Package.ImportPath,
   710  						a2.Package.ImportPath,
   711  						pkgDir,
   712  						dir)
   713  				}
   714  			}
   715  			// TODO(rsc): Find out and explain here why gccgo is different.
   716  			if cfg.BuildToolchainName == "gccgo" {
   717  				pkgDir = filepath.Join(pkgDir, "shlibs")
   718  			}
   719  			target := filepath.Join(pkgDir, shlib)
   720  
   721  			a := &Action{
   722  				Mode:   "go install -buildmode=shared",
   723  				Objdir: buildAction.Objdir,
   724  				Func:   BuildInstallFunc,
   725  				Deps:   []*Action{buildAction},
   726  				Target: target,
   727  			}
   728  			for _, a2 := range buildAction.Deps[0].Deps {
   729  				p := a2.Package
   730  				if p.Target == "" {
   731  					continue
   732  				}
   733  				a.Deps = append(a.Deps, &Action{
   734  					Mode:    "shlibname",
   735  					Package: p,
   736  					Func:    (*Builder).installShlibname,
   737  					Target:  strings.TrimSuffix(p.Target, ".a") + ".shlibname",
   738  					Deps:    []*Action{a.Deps[0]},
   739  				})
   740  			}
   741  			return a
   742  		})
   743  	}
   744  
   745  	return a
   746  }