github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/cmd/go/internal/load/pkg.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  // Package load loads packages.
     6  package load
     7  
     8  import (
     9  	"crypto/sha1"
    10  	"fmt"
    11  	"go/build"
    12  	"go/token"
    13  	"io/ioutil"
    14  	"os"
    15  	pathpkg "path"
    16  	"path/filepath"
    17  	"runtime"
    18  	"sort"
    19  	"strings"
    20  	"unicode"
    21  
    22  	"cmd/go/internal/base"
    23  	"cmd/go/internal/buildid"
    24  	"cmd/go/internal/cfg"
    25  	"cmd/go/internal/str"
    26  )
    27  
    28  var IgnoreImports bool // control whether we ignore imports in packages
    29  
    30  // A Package describes a single package found in a directory.
    31  type Package struct {
    32  	PackagePublic                 // visible in 'go list'
    33  	Internal      PackageInternal // for use inside go command only
    34  }
    35  
    36  type PackagePublic struct {
    37  	// Note: These fields are part of the go command's public API.
    38  	// See list.go. It is okay to add fields, but not to change or
    39  	// remove existing ones. Keep in sync with list.go
    40  	Dir           string `json:",omitempty"` // directory containing package sources
    41  	ImportPath    string `json:",omitempty"` // import path of package in dir
    42  	ImportComment string `json:",omitempty"` // path in import comment on package statement
    43  	Name          string `json:",omitempty"` // package name
    44  	Doc           string `json:",omitempty"` // package documentation string
    45  	Target        string `json:",omitempty"` // install path
    46  	Shlib         string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
    47  	Goroot        bool   `json:",omitempty"` // is this package found in the Go root?
    48  	Standard      bool   `json:",omitempty"` // is this package part of the standard Go library?
    49  	Stale         bool   `json:",omitempty"` // would 'go install' do anything for this package?
    50  	StaleReason   string `json:",omitempty"` // why is Stale true?
    51  	Root          string `json:",omitempty"` // Go root or Go path dir containing this package
    52  	ConflictDir   string `json:",omitempty"` // Dir is hidden by this other directory
    53  	BinaryOnly    bool   `json:",omitempty"` // package cannot be recompiled
    54  
    55  	// Source files
    56  	GoFiles        []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
    57  	CgoFiles       []string `json:",omitempty"` // .go sources files that import "C"
    58  	IgnoredGoFiles []string `json:",omitempty"` // .go sources ignored due to build constraints
    59  	CFiles         []string `json:",omitempty"` // .c source files
    60  	CXXFiles       []string `json:",omitempty"` // .cc, .cpp and .cxx source files
    61  	MFiles         []string `json:",omitempty"` // .m source files
    62  	HFiles         []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
    63  	FFiles         []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
    64  	SFiles         []string `json:",omitempty"` // .s source files
    65  	SwigFiles      []string `json:",omitempty"` // .swig files
    66  	SwigCXXFiles   []string `json:",omitempty"` // .swigcxx files
    67  	SysoFiles      []string `json:",omitempty"` // .syso system object files added to package
    68  
    69  	// Cgo directives
    70  	CgoCFLAGS    []string `json:",omitempty"` // cgo: flags for C compiler
    71  	CgoCPPFLAGS  []string `json:",omitempty"` // cgo: flags for C preprocessor
    72  	CgoCXXFLAGS  []string `json:",omitempty"` // cgo: flags for C++ compiler
    73  	CgoFFLAGS    []string `json:",omitempty"` // cgo: flags for Fortran compiler
    74  	CgoLDFLAGS   []string `json:",omitempty"` // cgo: flags for linker
    75  	CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
    76  
    77  	// Dependency information
    78  	Imports []string `json:",omitempty"` // import paths used by this package
    79  	Deps    []string `json:",omitempty"` // all (recursively) imported dependencies
    80  
    81  	// Error information
    82  	Incomplete bool            `json:",omitempty"` // was there an error loading this package or dependencies?
    83  	Error      *PackageError   `json:",omitempty"` // error loading this package (not dependencies)
    84  	DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
    85  
    86  	// Test information
    87  	TestGoFiles  []string `json:",omitempty"` // _test.go files in package
    88  	TestImports  []string `json:",omitempty"` // imports from TestGoFiles
    89  	XTestGoFiles []string `json:",omitempty"` // _test.go files outside package
    90  	XTestImports []string `json:",omitempty"` // imports from XTestGoFiles
    91  }
    92  
    93  type PackageInternal struct {
    94  	// Unexported fields are not part of the public API.
    95  	Build        *build.Package
    96  	Pkgdir       string     // overrides build.PkgDir
    97  	Imports      []*Package // this package's direct imports
    98  	GoFiles      []string   // GoFiles+CgoFiles+TestGoFiles+XTestGoFiles files, absolute paths
    99  	SFiles       []string
   100  	AllGoFiles   []string             // gofiles + IgnoredGoFiles, absolute paths
   101  	Target       string               // installed file for this package (may be executable)
   102  	Fake         bool                 // synthesized package
   103  	External     bool                 // synthesized external test package
   104  	ForceLibrary bool                 // this package is a library (even if named "main")
   105  	Cmdline      bool                 // defined by files listed on command line
   106  	Local        bool                 // imported via local path (./ or ../)
   107  	LocalPrefix  string               // interpret ./ and ../ imports relative to this prefix
   108  	ExeName      string               // desired name for temporary executable
   109  	CoverMode    string               // preprocess Go source files with the coverage tool in this mode
   110  	CoverVars    map[string]*CoverVar // variables created by coverage analysis
   111  	OmitDebug    bool                 // tell linker not to write debug information
   112  	BuildID      string               // expected build ID for generated package
   113  	GobinSubdir  bool                 // install target would be subdir of GOBIN
   114  }
   115  
   116  type NoGoError struct {
   117  	Package *Package
   118  }
   119  
   120  func (e *NoGoError) Error() string {
   121  	// Count files beginning with _ and ., which we will pretend don't exist at all.
   122  	dummy := 0
   123  	for _, name := range e.Package.IgnoredGoFiles {
   124  		if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
   125  			dummy++
   126  		}
   127  	}
   128  
   129  	if len(e.Package.IgnoredGoFiles) > dummy {
   130  		// Go files exist, but they were ignored due to build constraints.
   131  		return "build constraints exclude all Go files in " + e.Package.Dir
   132  	}
   133  	if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
   134  		// Test Go files exist, but we're not interested in them.
   135  		// The double-negative is unfortunate but we want e.Package.Dir
   136  		// to appear at the end of error message.
   137  		return "no non-test Go files in " + e.Package.Dir
   138  	}
   139  	return "no Go files in " + e.Package.Dir
   140  }
   141  
   142  // Vendored returns the vendor-resolved version of imports,
   143  // which should be p.TestImports or p.XTestImports, NOT p.Imports.
   144  // The imports in p.TestImports and p.XTestImports are not recursively
   145  // loaded during the initial load of p, so they list the imports found in
   146  // the source file, but most processing should be over the vendor-resolved
   147  // import paths. We do this resolution lazily both to avoid file system work
   148  // and because the eventual real load of the test imports (during 'go test')
   149  // can produce better error messages if it starts with the original paths.
   150  // The initial load of p loads all the non-test imports and rewrites
   151  // the vendored paths, so nothing should ever call p.vendored(p.Imports).
   152  func (p *Package) Vendored(imports []string) []string {
   153  	if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
   154  		panic("internal error: p.vendored(p.Imports) called")
   155  	}
   156  	seen := make(map[string]bool)
   157  	var all []string
   158  	for _, path := range imports {
   159  		path = VendoredImportPath(p, path)
   160  		if !seen[path] {
   161  			seen[path] = true
   162  			all = append(all, path)
   163  		}
   164  	}
   165  	sort.Strings(all)
   166  	return all
   167  }
   168  
   169  // CoverVar holds the name of the generated coverage variables targeting the named file.
   170  type CoverVar struct {
   171  	File string // local file name
   172  	Var  string // name of count struct
   173  }
   174  
   175  func (p *Package) copyBuild(pp *build.Package) {
   176  	p.Internal.Build = pp
   177  
   178  	if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
   179  		old := pp.PkgTargetRoot
   180  		pp.PkgRoot = cfg.BuildPkgdir
   181  		pp.PkgTargetRoot = cfg.BuildPkgdir
   182  		pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
   183  	}
   184  
   185  	p.Dir = pp.Dir
   186  	p.ImportPath = pp.ImportPath
   187  	p.ImportComment = pp.ImportComment
   188  	p.Name = pp.Name
   189  	p.Doc = pp.Doc
   190  	p.Root = pp.Root
   191  	p.ConflictDir = pp.ConflictDir
   192  	p.BinaryOnly = pp.BinaryOnly
   193  
   194  	// TODO? Target
   195  	p.Goroot = pp.Goroot
   196  	p.Standard = p.Goroot && p.ImportPath != "" && isStandardImportPath(p.ImportPath)
   197  	p.GoFiles = pp.GoFiles
   198  	p.CgoFiles = pp.CgoFiles
   199  	p.IgnoredGoFiles = pp.IgnoredGoFiles
   200  	p.CFiles = pp.CFiles
   201  	p.CXXFiles = pp.CXXFiles
   202  	p.MFiles = pp.MFiles
   203  	p.HFiles = pp.HFiles
   204  	p.FFiles = pp.FFiles
   205  	p.SFiles = pp.SFiles
   206  	p.SwigFiles = pp.SwigFiles
   207  	p.SwigCXXFiles = pp.SwigCXXFiles
   208  	p.SysoFiles = pp.SysoFiles
   209  	p.CgoCFLAGS = pp.CgoCFLAGS
   210  	p.CgoCPPFLAGS = pp.CgoCPPFLAGS
   211  	p.CgoCXXFLAGS = pp.CgoCXXFLAGS
   212  	p.CgoFFLAGS = pp.CgoFFLAGS
   213  	p.CgoLDFLAGS = pp.CgoLDFLAGS
   214  	p.CgoPkgConfig = pp.CgoPkgConfig
   215  	// We modify p.Imports in place, so make copy now.
   216  	p.Imports = make([]string, len(pp.Imports))
   217  	copy(p.Imports, pp.Imports)
   218  	p.TestGoFiles = pp.TestGoFiles
   219  	p.TestImports = pp.TestImports
   220  	p.XTestGoFiles = pp.XTestGoFiles
   221  	p.XTestImports = pp.XTestImports
   222  	if IgnoreImports {
   223  		p.Imports = nil
   224  		p.TestImports = nil
   225  		p.XTestImports = nil
   226  	}
   227  }
   228  
   229  // isStandardImportPath reports whether $GOROOT/src/path should be considered
   230  // part of the standard distribution. For historical reasons we allow people to add
   231  // their own code to $GOROOT instead of using $GOPATH, but we assume that
   232  // code will start with a domain name (dot in the first element).
   233  func isStandardImportPath(path string) bool {
   234  	i := strings.Index(path, "/")
   235  	if i < 0 {
   236  		i = len(path)
   237  	}
   238  	elem := path[:i]
   239  	return !strings.Contains(elem, ".")
   240  }
   241  
   242  // A PackageError describes an error loading information about a package.
   243  type PackageError struct {
   244  	ImportStack   []string // shortest path from package named on command line to this one
   245  	Pos           string   // position of error
   246  	Err           string   // the error itself
   247  	IsImportCycle bool     `json:"-"` // the error is an import cycle
   248  	Hard          bool     `json:"-"` // whether the error is soft or hard; soft errors are ignored in some places
   249  }
   250  
   251  func (p *PackageError) Error() string {
   252  	// Import cycles deserve special treatment.
   253  	if p.IsImportCycle {
   254  		return fmt.Sprintf("%s\npackage %s\n", p.Err, strings.Join(p.ImportStack, "\n\timports "))
   255  	}
   256  	if p.Pos != "" {
   257  		// Omit import stack. The full path to the file where the error
   258  		// is the most important thing.
   259  		return p.Pos + ": " + p.Err
   260  	}
   261  	if len(p.ImportStack) == 0 {
   262  		return p.Err
   263  	}
   264  	return "package " + strings.Join(p.ImportStack, "\n\timports ") + ": " + p.Err
   265  }
   266  
   267  // An ImportStack is a stack of import paths.
   268  type ImportStack []string
   269  
   270  func (s *ImportStack) Push(p string) {
   271  	*s = append(*s, p)
   272  }
   273  
   274  func (s *ImportStack) Pop() {
   275  	*s = (*s)[0 : len(*s)-1]
   276  }
   277  
   278  func (s *ImportStack) Copy() []string {
   279  	return append([]string{}, *s...)
   280  }
   281  
   282  // shorterThan reports whether sp is shorter than t.
   283  // We use this to record the shortest import sequence
   284  // that leads to a particular package.
   285  func (sp *ImportStack) shorterThan(t []string) bool {
   286  	s := *sp
   287  	if len(s) != len(t) {
   288  		return len(s) < len(t)
   289  	}
   290  	// If they are the same length, settle ties using string ordering.
   291  	for i := range s {
   292  		if s[i] != t[i] {
   293  			return s[i] < t[i]
   294  		}
   295  	}
   296  	return false // they are equal
   297  }
   298  
   299  // packageCache is a lookup cache for loadPackage,
   300  // so that if we look up a package multiple times
   301  // we return the same pointer each time.
   302  var packageCache = map[string]*Package{}
   303  
   304  func ClearPackageCache() {
   305  	for name := range packageCache {
   306  		delete(packageCache, name)
   307  	}
   308  }
   309  
   310  func ClearPackageCachePartial(args []string) {
   311  	for _, arg := range args {
   312  		p := packageCache[arg]
   313  		if p != nil {
   314  			delete(packageCache, p.Dir)
   315  			delete(packageCache, p.ImportPath)
   316  		}
   317  	}
   318  }
   319  
   320  // reloadPackage is like loadPackage but makes sure
   321  // not to use the package cache.
   322  func ReloadPackage(arg string, stk *ImportStack) *Package {
   323  	p := packageCache[arg]
   324  	if p != nil {
   325  		delete(packageCache, p.Dir)
   326  		delete(packageCache, p.ImportPath)
   327  	}
   328  	return LoadPackage(arg, stk)
   329  }
   330  
   331  // dirToImportPath returns the pseudo-import path we use for a package
   332  // outside the Go path. It begins with _/ and then contains the full path
   333  // to the directory. If the package lives in c:\home\gopher\my\pkg then
   334  // the pseudo-import path is _/c_/home/gopher/my/pkg.
   335  // Using a pseudo-import path like this makes the ./ imports no longer
   336  // a special case, so that all the code to deal with ordinary imports works
   337  // automatically.
   338  func dirToImportPath(dir string) string {
   339  	return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
   340  }
   341  
   342  func makeImportValid(r rune) rune {
   343  	// Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
   344  	const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
   345  	if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
   346  		return '_'
   347  	}
   348  	return r
   349  }
   350  
   351  // Mode flags for loadImport and download (in get.go).
   352  const (
   353  	// useVendor means that loadImport should do vendor expansion
   354  	// (provided the vendoring experiment is enabled).
   355  	// That is, useVendor means that the import path came from
   356  	// a source file and has not been vendor-expanded yet.
   357  	// Every import path should be loaded initially with useVendor,
   358  	// and then the expanded version (with the /vendor/ in it) gets
   359  	// recorded as the canonical import path. At that point, future loads
   360  	// of that package must not pass useVendor, because
   361  	// disallowVendor will reject direct use of paths containing /vendor/.
   362  	UseVendor = 1 << iota
   363  
   364  	// getTestDeps is for download (part of "go get") and indicates
   365  	// that test dependencies should be fetched too.
   366  	GetTestDeps
   367  )
   368  
   369  // loadImport scans the directory named by path, which must be an import path,
   370  // but possibly a local import path (an absolute file system path or one beginning
   371  // with ./ or ../). A local relative path is interpreted relative to srcDir.
   372  // It returns a *Package describing the package found in that directory.
   373  func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
   374  	stk.Push(path)
   375  	defer stk.Pop()
   376  
   377  	// Determine canonical identifier for this package.
   378  	// For a local import the identifier is the pseudo-import path
   379  	// we create from the full directory to the package.
   380  	// Otherwise it is the usual import path.
   381  	// For vendored imports, it is the expanded form.
   382  	importPath := path
   383  	origPath := path
   384  	isLocal := build.IsLocalImport(path)
   385  	if isLocal {
   386  		importPath = dirToImportPath(filepath.Join(srcDir, path))
   387  	} else if mode&UseVendor != 0 {
   388  		// We do our own vendor resolution, because we want to
   389  		// find out the key to use in packageCache without the
   390  		// overhead of repeated calls to buildContext.Import.
   391  		// The code is also needed in a few other places anyway.
   392  		path = VendoredImportPath(parent, path)
   393  		importPath = path
   394  	}
   395  
   396  	p := packageCache[importPath]
   397  	if p != nil {
   398  		p = reusePackage(p, stk)
   399  	} else {
   400  		p = new(Package)
   401  		p.Internal.Local = isLocal
   402  		p.ImportPath = importPath
   403  		packageCache[importPath] = p
   404  
   405  		// Load package.
   406  		// Import always returns bp != nil, even if an error occurs,
   407  		// in order to return partial information.
   408  		//
   409  		// TODO: After Go 1, decide when to pass build.AllowBinary here.
   410  		// See issue 3268 for mistakes to avoid.
   411  		buildMode := build.ImportComment
   412  		if mode&UseVendor == 0 || path != origPath {
   413  			// Not vendoring, or we already found the vendored path.
   414  			buildMode |= build.IgnoreVendor
   415  		}
   416  		bp, err := cfg.BuildContext.Import(path, srcDir, buildMode)
   417  		bp.ImportPath = importPath
   418  		if cfg.GOBIN != "" {
   419  			bp.BinDir = cfg.GOBIN
   420  		}
   421  		if err == nil && !isLocal && bp.ImportComment != "" && bp.ImportComment != path &&
   422  			!strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
   423  			err = fmt.Errorf("code in directory %s expects import %q", bp.Dir, bp.ImportComment)
   424  		}
   425  		p.load(stk, bp, err)
   426  		if p.Error != nil && p.Error.Pos == "" {
   427  			p = setErrorPos(p, importPos)
   428  		}
   429  
   430  		if origPath != cleanImport(origPath) {
   431  			p.Error = &PackageError{
   432  				ImportStack: stk.Copy(),
   433  				Err:         fmt.Sprintf("non-canonical import path: %q should be %q", origPath, pathpkg.Clean(origPath)),
   434  			}
   435  			p.Incomplete = true
   436  		}
   437  	}
   438  
   439  	// Checked on every import because the rules depend on the code doing the importing.
   440  	if perr := disallowInternal(srcDir, p, stk); perr != p {
   441  		return setErrorPos(perr, importPos)
   442  	}
   443  	if mode&UseVendor != 0 {
   444  		if perr := disallowVendor(srcDir, origPath, p, stk); perr != p {
   445  			return setErrorPos(perr, importPos)
   446  		}
   447  	}
   448  
   449  	if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
   450  		perr := *p
   451  		perr.Error = &PackageError{
   452  			ImportStack: stk.Copy(),
   453  			Err:         fmt.Sprintf("import %q is a program, not an importable package", path),
   454  		}
   455  		return setErrorPos(&perr, importPos)
   456  	}
   457  
   458  	if p.Internal.Local && parent != nil && !parent.Internal.Local {
   459  		perr := *p
   460  		perr.Error = &PackageError{
   461  			ImportStack: stk.Copy(),
   462  			Err:         fmt.Sprintf("local import %q in non-local package", path),
   463  		}
   464  		return setErrorPos(&perr, importPos)
   465  	}
   466  
   467  	return p
   468  }
   469  
   470  func setErrorPos(p *Package, importPos []token.Position) *Package {
   471  	if len(importPos) > 0 {
   472  		pos := importPos[0]
   473  		pos.Filename = base.ShortPath(pos.Filename)
   474  		p.Error.Pos = pos.String()
   475  	}
   476  	return p
   477  }
   478  
   479  func cleanImport(path string) string {
   480  	orig := path
   481  	path = pathpkg.Clean(path)
   482  	if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
   483  		path = "./" + path
   484  	}
   485  	return path
   486  }
   487  
   488  var isDirCache = map[string]bool{}
   489  
   490  func isDir(path string) bool {
   491  	result, ok := isDirCache[path]
   492  	if ok {
   493  		return result
   494  	}
   495  
   496  	fi, err := os.Stat(path)
   497  	result = err == nil && fi.IsDir()
   498  	isDirCache[path] = result
   499  	return result
   500  }
   501  
   502  // VendoredImportPath returns the expansion of path when it appears in parent.
   503  // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
   504  // x/vendor/path, vendor/path, or else stay path if none of those exist.
   505  // VendoredImportPath returns the expanded path or, if no expansion is found, the original.
   506  func VendoredImportPath(parent *Package, path string) (found string) {
   507  	if parent == nil || parent.Root == "" {
   508  		return path
   509  	}
   510  
   511  	dir := filepath.Clean(parent.Dir)
   512  	root := filepath.Join(parent.Root, "src")
   513  	if !hasFilePathPrefix(dir, root) || parent.ImportPath != "command-line-arguments" && filepath.Join(root, parent.ImportPath) != dir {
   514  		// Look for symlinks before reporting error.
   515  		dir = expandPath(dir)
   516  		root = expandPath(root)
   517  	}
   518  
   519  	if !hasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator || parent.ImportPath != "command-line-arguments" && !parent.Internal.Local && filepath.Join(root, parent.ImportPath) != dir {
   520  		base.Fatalf("unexpected directory layout:\n"+
   521  			"	import path: %s\n"+
   522  			"	root: %s\n"+
   523  			"	dir: %s\n"+
   524  			"	expand root: %s\n"+
   525  			"	expand dir: %s\n"+
   526  			"	separator: %s",
   527  			parent.ImportPath,
   528  			filepath.Join(parent.Root, "src"),
   529  			filepath.Clean(parent.Dir),
   530  			root,
   531  			dir,
   532  			string(filepath.Separator))
   533  	}
   534  
   535  	vpath := "vendor/" + path
   536  	for i := len(dir); i >= len(root); i-- {
   537  		if i < len(dir) && dir[i] != filepath.Separator {
   538  			continue
   539  		}
   540  		// Note: checking for the vendor directory before checking
   541  		// for the vendor/path directory helps us hit the
   542  		// isDir cache more often. It also helps us prepare a more useful
   543  		// list of places we looked, to report when an import is not found.
   544  		if !isDir(filepath.Join(dir[:i], "vendor")) {
   545  			continue
   546  		}
   547  		targ := filepath.Join(dir[:i], vpath)
   548  		if isDir(targ) && hasGoFiles(targ) {
   549  			importPath := parent.ImportPath
   550  			if importPath == "command-line-arguments" {
   551  				// If parent.ImportPath is 'command-line-arguments'.
   552  				// set to relative directory to root (also chopped root directory)
   553  				importPath = dir[len(root)+1:]
   554  			}
   555  			// We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
   556  			// We know the import path for parent's dir.
   557  			// We chopped off some number of path elements and
   558  			// added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
   559  			// Now we want to know the import path for that directory.
   560  			// Construct it by chopping the same number of path elements
   561  			// (actually the same number of bytes) from parent's import path
   562  			// and then append /vendor/path.
   563  			chopped := len(dir) - i
   564  			if chopped == len(importPath)+1 {
   565  				// We walked up from c:\gopath\src\foo\bar
   566  				// and found c:\gopath\src\vendor\path.
   567  				// We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
   568  				// Use "vendor/path" without any prefix.
   569  				return vpath
   570  			}
   571  			return importPath[:len(importPath)-chopped] + "/" + vpath
   572  		}
   573  	}
   574  	return path
   575  }
   576  
   577  // hasGoFiles reports whether dir contains any files with names ending in .go.
   578  // For a vendor check we must exclude directories that contain no .go files.
   579  // Otherwise it is not possible to vendor just a/b/c and still import the
   580  // non-vendored a/b. See golang.org/issue/13832.
   581  func hasGoFiles(dir string) bool {
   582  	fis, _ := ioutil.ReadDir(dir)
   583  	for _, fi := range fis {
   584  		if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
   585  			return true
   586  		}
   587  	}
   588  	return false
   589  }
   590  
   591  // reusePackage reuses package p to satisfy the import at the top
   592  // of the import stack stk. If this use causes an import loop,
   593  // reusePackage updates p's error information to record the loop.
   594  func reusePackage(p *Package, stk *ImportStack) *Package {
   595  	// We use p.Internal.Imports==nil to detect a package that
   596  	// is in the midst of its own loadPackage call
   597  	// (all the recursion below happens before p.Internal.Imports gets set).
   598  	if p.Internal.Imports == nil {
   599  		if p.Error == nil {
   600  			p.Error = &PackageError{
   601  				ImportStack:   stk.Copy(),
   602  				Err:           "import cycle not allowed",
   603  				IsImportCycle: true,
   604  			}
   605  		}
   606  		p.Incomplete = true
   607  	}
   608  	// Don't rewrite the import stack in the error if we have an import cycle.
   609  	// If we do, we'll lose the path that describes the cycle.
   610  	if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
   611  		p.Error.ImportStack = stk.Copy()
   612  	}
   613  	return p
   614  }
   615  
   616  // disallowInternal checks that srcDir is allowed to import p.
   617  // If the import is allowed, disallowInternal returns the original package p.
   618  // If not, it returns a new package containing just an appropriate error.
   619  func disallowInternal(srcDir string, p *Package, stk *ImportStack) *Package {
   620  	// golang.org/s/go14internal:
   621  	// An import of a path containing the element “internal”
   622  	// is disallowed if the importing code is outside the tree
   623  	// rooted at the parent of the “internal” directory.
   624  
   625  	// There was an error loading the package; stop here.
   626  	if p.Error != nil {
   627  		return p
   628  	}
   629  
   630  	// The generated 'testmain' package is allowed to access testing/internal/...,
   631  	// as if it were generated into the testing directory tree
   632  	// (it's actually in a temporary directory outside any Go tree).
   633  	// This cleans up a former kludge in passing functionality to the testing package.
   634  	if strings.HasPrefix(p.ImportPath, "testing/internal") && len(*stk) >= 2 && (*stk)[len(*stk)-2] == "testmain" {
   635  		return p
   636  	}
   637  
   638  	// We can't check standard packages with gccgo.
   639  	if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
   640  		return p
   641  	}
   642  
   643  	// The stack includes p.ImportPath.
   644  	// If that's the only thing on the stack, we started
   645  	// with a name given on the command line, not an
   646  	// import. Anything listed on the command line is fine.
   647  	if len(*stk) == 1 {
   648  		return p
   649  	}
   650  
   651  	// Check for "internal" element: three cases depending on begin of string and/or end of string.
   652  	i, ok := findInternal(p.ImportPath)
   653  	if !ok {
   654  		return p
   655  	}
   656  
   657  	// Internal is present.
   658  	// Map import path back to directory corresponding to parent of internal.
   659  	if i > 0 {
   660  		i-- // rewind over slash in ".../internal"
   661  	}
   662  	parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
   663  	if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
   664  		return p
   665  	}
   666  
   667  	// Look for symlinks before reporting error.
   668  	srcDir = expandPath(srcDir)
   669  	parent = expandPath(parent)
   670  	if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
   671  		return p
   672  	}
   673  
   674  	// Internal is present, and srcDir is outside parent's tree. Not allowed.
   675  	perr := *p
   676  	perr.Error = &PackageError{
   677  		ImportStack: stk.Copy(),
   678  		Err:         "use of internal package not allowed",
   679  	}
   680  	perr.Incomplete = true
   681  	return &perr
   682  }
   683  
   684  // findInternal looks for the final "internal" path element in the given import path.
   685  // If there isn't one, findInternal returns ok=false.
   686  // Otherwise, findInternal returns ok=true and the index of the "internal".
   687  func findInternal(path string) (index int, ok bool) {
   688  	// Three cases, depending on internal at start/end of string or not.
   689  	// The order matters: we must return the index of the final element,
   690  	// because the final one produces the most restrictive requirement
   691  	// on the importer.
   692  	switch {
   693  	case strings.HasSuffix(path, "/internal"):
   694  		return len(path) - len("internal"), true
   695  	case strings.Contains(path, "/internal/"):
   696  		return strings.LastIndex(path, "/internal/") + 1, true
   697  	case path == "internal", strings.HasPrefix(path, "internal/"):
   698  		return 0, true
   699  	}
   700  	return 0, false
   701  }
   702  
   703  // disallowVendor checks that srcDir is allowed to import p as path.
   704  // If the import is allowed, disallowVendor returns the original package p.
   705  // If not, it returns a new package containing just an appropriate error.
   706  func disallowVendor(srcDir, path string, p *Package, stk *ImportStack) *Package {
   707  	// The stack includes p.ImportPath.
   708  	// If that's the only thing on the stack, we started
   709  	// with a name given on the command line, not an
   710  	// import. Anything listed on the command line is fine.
   711  	if len(*stk) == 1 {
   712  		return p
   713  	}
   714  
   715  	if perr := disallowVendorVisibility(srcDir, p, stk); perr != p {
   716  		return perr
   717  	}
   718  
   719  	// Paths like x/vendor/y must be imported as y, never as x/vendor/y.
   720  	if i, ok := FindVendor(path); ok {
   721  		perr := *p
   722  		perr.Error = &PackageError{
   723  			ImportStack: stk.Copy(),
   724  			Err:         "must be imported as " + path[i+len("vendor/"):],
   725  		}
   726  		perr.Incomplete = true
   727  		return &perr
   728  	}
   729  
   730  	return p
   731  }
   732  
   733  // disallowVendorVisibility checks that srcDir is allowed to import p.
   734  // The rules are the same as for /internal/ except that a path ending in /vendor
   735  // is not subject to the rules, only subdirectories of vendor.
   736  // This allows people to have packages and commands named vendor,
   737  // for maximal compatibility with existing source trees.
   738  func disallowVendorVisibility(srcDir string, p *Package, stk *ImportStack) *Package {
   739  	// The stack includes p.ImportPath.
   740  	// If that's the only thing on the stack, we started
   741  	// with a name given on the command line, not an
   742  	// import. Anything listed on the command line is fine.
   743  	if len(*stk) == 1 {
   744  		return p
   745  	}
   746  
   747  	// Check for "vendor" element.
   748  	i, ok := FindVendor(p.ImportPath)
   749  	if !ok {
   750  		return p
   751  	}
   752  
   753  	// Vendor is present.
   754  	// Map import path back to directory corresponding to parent of vendor.
   755  	if i > 0 {
   756  		i-- // rewind over slash in ".../vendor"
   757  	}
   758  	truncateTo := i + len(p.Dir) - len(p.ImportPath)
   759  	if truncateTo < 0 || len(p.Dir) < truncateTo {
   760  		return p
   761  	}
   762  	parent := p.Dir[:truncateTo]
   763  	if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
   764  		return p
   765  	}
   766  
   767  	// Look for symlinks before reporting error.
   768  	srcDir = expandPath(srcDir)
   769  	parent = expandPath(parent)
   770  	if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
   771  		return p
   772  	}
   773  
   774  	// Vendor is present, and srcDir is outside parent's tree. Not allowed.
   775  	perr := *p
   776  	perr.Error = &PackageError{
   777  		ImportStack: stk.Copy(),
   778  		Err:         "use of vendored package not allowed",
   779  	}
   780  	perr.Incomplete = true
   781  	return &perr
   782  }
   783  
   784  // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
   785  // If there isn't one, FindVendor returns ok=false.
   786  // Otherwise, FindVendor returns ok=true and the index of the "vendor".
   787  //
   788  // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
   789  // not the vendored copy of an import "" (the empty import path).
   790  // This will allow people to have packages or commands named vendor.
   791  // This may help reduce breakage, or it may just be confusing. We'll see.
   792  func FindVendor(path string) (index int, ok bool) {
   793  	// Two cases, depending on internal at start of string or not.
   794  	// The order matters: we must return the index of the final element,
   795  	// because the final one is where the effective import path starts.
   796  	switch {
   797  	case strings.Contains(path, "/vendor/"):
   798  		return strings.LastIndex(path, "/vendor/") + 1, true
   799  	case strings.HasPrefix(path, "vendor/"):
   800  		return 0, true
   801  	}
   802  	return 0, false
   803  }
   804  
   805  type targetDir int
   806  
   807  const (
   808  	ToRoot    targetDir = iota // to bin dir inside package root (default)
   809  	ToTool                     // GOROOT/pkg/tool
   810  	StalePath                  // the old import path; fail to build
   811  )
   812  
   813  // goTools is a map of Go program import path to install target directory.
   814  var GoTools = map[string]targetDir{
   815  	"cmd/addr2line": ToTool,
   816  	"cmd/api":       ToTool,
   817  	"cmd/asm":       ToTool,
   818  	"cmd/compile":   ToTool,
   819  	"cmd/cgo":       ToTool,
   820  	"cmd/cover":     ToTool,
   821  	"cmd/dist":      ToTool,
   822  	"cmd/doc":       ToTool,
   823  	"cmd/fix":       ToTool,
   824  	"cmd/link":      ToTool,
   825  	"cmd/newlink":   ToTool,
   826  	"cmd/nm":        ToTool,
   827  	"cmd/objdump":   ToTool,
   828  	"cmd/pack":      ToTool,
   829  	"cmd/pprof":     ToTool,
   830  	"cmd/trace":     ToTool,
   831  	"cmd/vet":       ToTool,
   832  	"code.google.com/p/go.tools/cmd/cover": StalePath,
   833  	"code.google.com/p/go.tools/cmd/godoc": StalePath,
   834  	"code.google.com/p/go.tools/cmd/vet":   StalePath,
   835  }
   836  
   837  var raceExclude = map[string]bool{
   838  	"runtime/race": true,
   839  	"runtime/msan": true,
   840  	"runtime/cgo":  true,
   841  	"cmd/cgo":      true,
   842  	"syscall":      true,
   843  	"errors":       true,
   844  }
   845  
   846  var cgoExclude = map[string]bool{
   847  	"runtime/cgo": true,
   848  }
   849  
   850  var cgoSyscallExclude = map[string]bool{
   851  	"runtime/cgo":  true,
   852  	"runtime/race": true,
   853  	"runtime/msan": true,
   854  }
   855  
   856  var foldPath = make(map[string]string)
   857  
   858  // load populates p using information from bp, err, which should
   859  // be the result of calling build.Context.Import.
   860  func (p *Package) load(stk *ImportStack, bp *build.Package, err error) {
   861  	p.copyBuild(bp)
   862  
   863  	// The localPrefix is the path we interpret ./ imports relative to.
   864  	// Synthesized main packages sometimes override this.
   865  	p.Internal.LocalPrefix = dirToImportPath(p.Dir)
   866  
   867  	if err != nil {
   868  		if _, ok := err.(*build.NoGoError); ok {
   869  			err = &NoGoError{Package: p}
   870  		}
   871  		p.Incomplete = true
   872  		err = base.ExpandScanner(err)
   873  		p.Error = &PackageError{
   874  			ImportStack: stk.Copy(),
   875  			Err:         err.Error(),
   876  		}
   877  		return
   878  	}
   879  
   880  	useBindir := p.Name == "main"
   881  	if !p.Standard {
   882  		switch cfg.BuildBuildmode {
   883  		case "c-archive", "c-shared", "plugin":
   884  			useBindir = false
   885  		}
   886  	}
   887  
   888  	if useBindir {
   889  		// Report an error when the old code.google.com/p/go.tools paths are used.
   890  		if GoTools[p.ImportPath] == StalePath {
   891  			newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
   892  			e := fmt.Sprintf("the %v command has moved; use %v instead.", p.ImportPath, newPath)
   893  			p.Error = &PackageError{Err: e}
   894  			return
   895  		}
   896  		_, elem := filepath.Split(p.Dir)
   897  		full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
   898  		if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
   899  			// Install cross-compiled binaries to subdirectories of bin.
   900  			elem = full
   901  		}
   902  		if p.Internal.Build.BinDir != "" {
   903  			// Install to GOBIN or bin of GOPATH entry.
   904  			p.Internal.Target = filepath.Join(p.Internal.Build.BinDir, elem)
   905  			if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
   906  				// Do not create $GOBIN/goos_goarch/elem.
   907  				p.Internal.Target = ""
   908  				p.Internal.GobinSubdir = true
   909  			}
   910  		}
   911  		if GoTools[p.ImportPath] == ToTool {
   912  			// This is for 'go tool'.
   913  			// Override all the usual logic and force it into the tool directory.
   914  			p.Internal.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
   915  		}
   916  		if p.Internal.Target != "" && cfg.BuildContext.GOOS == "windows" {
   917  			p.Internal.Target += ".exe"
   918  		}
   919  	} else if p.Internal.Local {
   920  		// Local import turned into absolute path.
   921  		// No permanent install target.
   922  		p.Internal.Target = ""
   923  	} else {
   924  		p.Internal.Target = p.Internal.Build.PkgObj
   925  		if cfg.BuildLinkshared {
   926  			shlibnamefile := p.Internal.Target[:len(p.Internal.Target)-2] + ".shlibname"
   927  			shlib, err := ioutil.ReadFile(shlibnamefile)
   928  			if err == nil {
   929  				libname := strings.TrimSpace(string(shlib))
   930  				if cfg.BuildContext.Compiler == "gccgo" {
   931  					p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
   932  				} else {
   933  					p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
   934  
   935  				}
   936  			} else if !os.IsNotExist(err) {
   937  				base.Fatalf("unexpected error reading %s: %v", shlibnamefile, err)
   938  			}
   939  		}
   940  	}
   941  
   942  	importPaths := p.Imports
   943  	// Packages that use cgo import runtime/cgo implicitly.
   944  	// Packages that use cgo also import syscall implicitly,
   945  	// to wrap errno.
   946  	// Exclude certain packages to avoid circular dependencies.
   947  	if len(p.CgoFiles) > 0 && (!p.Standard || !cgoExclude[p.ImportPath]) {
   948  		importPaths = append(importPaths, "runtime/cgo")
   949  	}
   950  	if len(p.CgoFiles) > 0 && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
   951  		importPaths = append(importPaths, "syscall")
   952  	}
   953  
   954  	if cfg.BuildContext.CgoEnabled && p.Name == "main" && !p.Goroot {
   955  		// Currently build modes c-shared, pie (on systems that do not
   956  		// support PIE with internal linking mode (currently all
   957  		// systems: issue #18968)), plugin, and -linkshared force
   958  		// external linking mode, as of course does
   959  		// -ldflags=-linkmode=external. External linking mode forces
   960  		// an import of runtime/cgo.
   961  		pieCgo := cfg.BuildBuildmode == "pie"
   962  		linkmodeExternal := false
   963  		for i, a := range cfg.BuildLdflags {
   964  			if a == "-linkmode=external" {
   965  				linkmodeExternal = true
   966  			}
   967  			if a == "-linkmode" && i+1 < len(cfg.BuildLdflags) && cfg.BuildLdflags[i+1] == "external" {
   968  				linkmodeExternal = true
   969  			}
   970  		}
   971  		if cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal {
   972  			importPaths = append(importPaths, "runtime/cgo")
   973  		}
   974  	}
   975  
   976  	// Everything depends on runtime, except runtime, its internal
   977  	// subpackages, and unsafe.
   978  	if !p.Standard || (p.ImportPath != "runtime" && !strings.HasPrefix(p.ImportPath, "runtime/internal/") && p.ImportPath != "unsafe") {
   979  		importPaths = append(importPaths, "runtime")
   980  		// When race detection enabled everything depends on runtime/race.
   981  		// Exclude certain packages to avoid circular dependencies.
   982  		if cfg.BuildRace && (!p.Standard || !raceExclude[p.ImportPath]) {
   983  			importPaths = append(importPaths, "runtime/race")
   984  		}
   985  		// MSan uses runtime/msan.
   986  		if cfg.BuildMSan && (!p.Standard || !raceExclude[p.ImportPath]) {
   987  			importPaths = append(importPaths, "runtime/msan")
   988  		}
   989  		// On ARM with GOARM=5, everything depends on math for the link.
   990  		if p.Name == "main" && cfg.Goarch == "arm" {
   991  			importPaths = append(importPaths, "math")
   992  		}
   993  	}
   994  
   995  	// Runtime and its internal packages depend on runtime/internal/sys,
   996  	// so that they pick up the generated zversion.go file.
   997  	// This can be an issue particularly for runtime/internal/atomic;
   998  	// see issue 13655.
   999  	if p.Standard && (p.ImportPath == "runtime" || strings.HasPrefix(p.ImportPath, "runtime/internal/")) && p.ImportPath != "runtime/internal/sys" {
  1000  		importPaths = append(importPaths, "runtime/internal/sys")
  1001  	}
  1002  
  1003  	// Build list of full paths to all Go files in the package,
  1004  	// for use by commands like go fmt.
  1005  	p.Internal.GoFiles = str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles)
  1006  	for i := range p.Internal.GoFiles {
  1007  		p.Internal.GoFiles[i] = filepath.Join(p.Dir, p.Internal.GoFiles[i])
  1008  	}
  1009  	sort.Strings(p.Internal.GoFiles)
  1010  
  1011  	p.Internal.SFiles = str.StringList(p.SFiles)
  1012  	for i := range p.Internal.SFiles {
  1013  		p.Internal.SFiles[i] = filepath.Join(p.Dir, p.Internal.SFiles[i])
  1014  	}
  1015  	sort.Strings(p.Internal.SFiles)
  1016  
  1017  	p.Internal.AllGoFiles = str.StringList(p.IgnoredGoFiles)
  1018  	for i := range p.Internal.AllGoFiles {
  1019  		p.Internal.AllGoFiles[i] = filepath.Join(p.Dir, p.Internal.AllGoFiles[i])
  1020  	}
  1021  	p.Internal.AllGoFiles = append(p.Internal.AllGoFiles, p.Internal.GoFiles...)
  1022  	sort.Strings(p.Internal.AllGoFiles)
  1023  
  1024  	// Check for case-insensitive collision of input files.
  1025  	// To avoid problems on case-insensitive files, we reject any package
  1026  	// where two different input files have equal names under a case-insensitive
  1027  	// comparison.
  1028  	f1, f2 := str.FoldDup(str.StringList(
  1029  		p.GoFiles,
  1030  		p.CgoFiles,
  1031  		p.IgnoredGoFiles,
  1032  		p.CFiles,
  1033  		p.CXXFiles,
  1034  		p.MFiles,
  1035  		p.HFiles,
  1036  		p.FFiles,
  1037  		p.SFiles,
  1038  		p.SysoFiles,
  1039  		p.SwigFiles,
  1040  		p.SwigCXXFiles,
  1041  		p.TestGoFiles,
  1042  		p.XTestGoFiles,
  1043  	))
  1044  	if f1 != "" {
  1045  		p.Error = &PackageError{
  1046  			ImportStack: stk.Copy(),
  1047  			Err:         fmt.Sprintf("case-insensitive file name collision: %q and %q", f1, f2),
  1048  		}
  1049  		return
  1050  	}
  1051  
  1052  	// Build list of imported packages and full dependency list.
  1053  	imports := make([]*Package, 0, len(p.Imports))
  1054  	for i, path := range importPaths {
  1055  		if path == "C" {
  1056  			continue
  1057  		}
  1058  		p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], UseVendor)
  1059  		if p.Standard && p.Error == nil && !p1.Standard && p1.Error == nil {
  1060  			p.Error = &PackageError{
  1061  				ImportStack: stk.Copy(),
  1062  				Err:         fmt.Sprintf("non-standard import %q in standard package %q", path, p.ImportPath),
  1063  			}
  1064  			pos := p.Internal.Build.ImportPos[path]
  1065  			if len(pos) > 0 {
  1066  				p.Error.Pos = pos[0].String()
  1067  			}
  1068  		}
  1069  
  1070  		path = p1.ImportPath
  1071  		importPaths[i] = path
  1072  		if i < len(p.Imports) {
  1073  			p.Imports[i] = path
  1074  		}
  1075  
  1076  		imports = append(imports, p1)
  1077  		if p1.Incomplete {
  1078  			p.Incomplete = true
  1079  		}
  1080  	}
  1081  	p.Internal.Imports = imports
  1082  
  1083  	deps := make(map[string]*Package)
  1084  	var q []*Package
  1085  	q = append(q, imports...)
  1086  	for i := 0; i < len(q); i++ {
  1087  		p1 := q[i]
  1088  		path := p1.ImportPath
  1089  		// The same import path could produce an error or not,
  1090  		// depending on what tries to import it.
  1091  		// Prefer to record entries with errors, so we can report them.
  1092  		p0 := deps[path]
  1093  		if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
  1094  			deps[path] = p1
  1095  			for _, p2 := range p1.Internal.Imports {
  1096  				if deps[p2.ImportPath] != p2 {
  1097  					q = append(q, p2)
  1098  				}
  1099  			}
  1100  		}
  1101  	}
  1102  
  1103  	p.Deps = make([]string, 0, len(deps))
  1104  	for dep := range deps {
  1105  		p.Deps = append(p.Deps, dep)
  1106  	}
  1107  	sort.Strings(p.Deps)
  1108  	for _, dep := range p.Deps {
  1109  		p1 := deps[dep]
  1110  		if p1 == nil {
  1111  			panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
  1112  		}
  1113  		if p1.Error != nil {
  1114  			p.DepsErrors = append(p.DepsErrors, p1.Error)
  1115  		}
  1116  	}
  1117  
  1118  	// unsafe is a fake package.
  1119  	if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
  1120  		p.Internal.Target = ""
  1121  	}
  1122  	p.Target = p.Internal.Target
  1123  
  1124  	// If cgo is not enabled, ignore cgo supporting sources
  1125  	// just as we ignore go files containing import "C".
  1126  	if !cfg.BuildContext.CgoEnabled {
  1127  		p.CFiles = nil
  1128  		p.CXXFiles = nil
  1129  		p.MFiles = nil
  1130  		p.SwigFiles = nil
  1131  		p.SwigCXXFiles = nil
  1132  		// Note that SFiles are okay (they go to the Go assembler)
  1133  		// and HFiles are okay (they might be used by the SFiles).
  1134  		// Also Sysofiles are okay (they might not contain object
  1135  		// code; see issue #16050).
  1136  	}
  1137  
  1138  	// The gc toolchain only permits C source files with cgo.
  1139  	if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
  1140  		p.Error = &PackageError{
  1141  			ImportStack: stk.Copy(),
  1142  			Err:         fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")),
  1143  		}
  1144  		return
  1145  	}
  1146  
  1147  	// Check for case-insensitive collisions of import paths.
  1148  	fold := str.ToFold(p.ImportPath)
  1149  	if other := foldPath[fold]; other == "" {
  1150  		foldPath[fold] = p.ImportPath
  1151  	} else if other != p.ImportPath {
  1152  		p.Error = &PackageError{
  1153  			ImportStack: stk.Copy(),
  1154  			Err:         fmt.Sprintf("case-insensitive import collision: %q and %q", p.ImportPath, other),
  1155  		}
  1156  		return
  1157  	}
  1158  
  1159  	if p.BinaryOnly {
  1160  		// For binary-only package, use build ID from supplied package binary.
  1161  		buildID, err := buildid.ReadBuildID(p.Name, p.Target)
  1162  		if err == nil {
  1163  			p.Internal.BuildID = buildID
  1164  		}
  1165  	} else {
  1166  		computeBuildID(p)
  1167  	}
  1168  }
  1169  
  1170  // InternalDeps returns the full dependency list for p,
  1171  // built by traversing p.Internal.Imports, their .Internal.Imports, and so on.
  1172  // It guarantees that the returned list has only one package per ImportPath
  1173  // and that "test" copies of a package are returned in preference to "real" ones.
  1174  func (p *Package) InternalDeps() []*Package {
  1175  	// Note: breadth-first search here to ensure that test-augmented copies
  1176  	// of a package under test are found before the "real" ones
  1177  	// (the real ones are deeper in the import graph).
  1178  	// Since we're building the slice anyway, it doesn't cost anything.
  1179  	all := []*Package{p}
  1180  	have := map[string]bool{p.ImportPath: true, "unsafe": true}
  1181  	// Note: Not a range loop because all is growing during the loop.
  1182  	for i := 0; i < len(all); i++ {
  1183  		for _, p1 := range all[i].Internal.Imports {
  1184  			if !have[p1.ImportPath] {
  1185  				have[p1.ImportPath] = true
  1186  				all = append(all, p1)
  1187  			}
  1188  		}
  1189  	}
  1190  	return all[1:] // slice off p itself
  1191  }
  1192  
  1193  // usesSwig reports whether the package needs to run SWIG.
  1194  func (p *Package) UsesSwig() bool {
  1195  	return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
  1196  }
  1197  
  1198  // usesCgo reports whether the package needs to run cgo
  1199  func (p *Package) UsesCgo() bool {
  1200  	return len(p.CgoFiles) > 0
  1201  }
  1202  
  1203  // packageList returns the list of packages in the dag rooted at roots
  1204  // as visited in a depth-first post-order traversal.
  1205  func PackageList(roots []*Package) []*Package {
  1206  	seen := map[*Package]bool{}
  1207  	all := []*Package{}
  1208  	var walk func(*Package)
  1209  	walk = func(p *Package) {
  1210  		if seen[p] {
  1211  			return
  1212  		}
  1213  		seen[p] = true
  1214  		for _, p1 := range p.Internal.Imports {
  1215  			walk(p1)
  1216  		}
  1217  		all = append(all, p)
  1218  	}
  1219  	for _, root := range roots {
  1220  		walk(root)
  1221  	}
  1222  	return all
  1223  }
  1224  
  1225  // computeStale computes the Stale flag in the package dag that starts
  1226  // at the named pkgs (command-line arguments).
  1227  func ComputeStale(pkgs ...*Package) {
  1228  	for _, p := range PackageList(pkgs) {
  1229  		p.Stale, p.StaleReason = isStale(p)
  1230  	}
  1231  }
  1232  
  1233  // The runtime version string takes one of two forms:
  1234  // "go1.X[.Y]" for Go releases, and "devel +hash" at tip.
  1235  // Determine whether we are in a released copy by
  1236  // inspecting the version.
  1237  var isGoRelease = strings.HasPrefix(runtime.Version(), "go1")
  1238  
  1239  // isStale and computeBuildID
  1240  //
  1241  // Theory of Operation
  1242  //
  1243  // There is an installed copy of the package (or binary).
  1244  // Can we reuse the installed copy, or do we need to build a new one?
  1245  //
  1246  // We can use the installed copy if it matches what we'd get
  1247  // by building a new one. The hard part is predicting that without
  1248  // actually running a build.
  1249  //
  1250  // To start, we must know the set of inputs to the build process that can
  1251  // affect the generated output. At a minimum, that includes the source
  1252  // files for the package and also any compiled packages imported by those
  1253  // source files. The *Package has these, and we use them. One might also
  1254  // argue for including in the input set: the build tags, whether the race
  1255  // detector is in use, the target operating system and architecture, the
  1256  // compiler and linker binaries being used, the additional flags being
  1257  // passed to those, the cgo binary being used, the additional flags cgo
  1258  // passes to the host C compiler, the host C compiler being used, the set
  1259  // of host C include files and installed C libraries, and so on.
  1260  // We include some but not all of this information.
  1261  //
  1262  // Once we have decided on a set of inputs, we must next decide how to
  1263  // tell whether the content of that set has changed since the last build
  1264  // of p. If there have been no changes, then we assume a new build would
  1265  // produce the same result and reuse the installed package or binary.
  1266  // But if there have been changes, then we assume a new build might not
  1267  // produce the same result, so we rebuild.
  1268  //
  1269  // There are two common ways to decide whether the content of the set has
  1270  // changed: modification times and content hashes. We use a mixture of both.
  1271  //
  1272  // The use of modification times (mtimes) was pioneered by make:
  1273  // assuming that a file's mtime is an accurate record of when that file was last written,
  1274  // and assuming that the modification time of an installed package or
  1275  // binary is the time that it was built, if the mtimes of the inputs
  1276  // predate the mtime of the installed object, then the build of that
  1277  // object saw those versions of the files, and therefore a rebuild using
  1278  // those same versions would produce the same object. In contrast, if any
  1279  // mtime of an input is newer than the mtime of the installed object, a
  1280  // change has occurred since the build, and the build should be redone.
  1281  //
  1282  // Modification times are attractive because the logic is easy to
  1283  // understand and the file system maintains the mtimes automatically
  1284  // (less work for us). Unfortunately, there are a variety of ways in
  1285  // which the mtime approach fails to detect a change and reuses a stale
  1286  // object file incorrectly. (Making the opposite mistake, rebuilding
  1287  // unnecessarily, is only a performance problem and not a correctness
  1288  // problem, so we ignore that one.)
  1289  //
  1290  // As a warmup, one problem is that to be perfectly precise, we need to
  1291  // compare the input mtimes against the time at the beginning of the
  1292  // build, but the object file time is the time at the end of the build.
  1293  // If an input file changes after being read but before the object is
  1294  // written, the next build will see an object newer than the input and
  1295  // will incorrectly decide that the object is up to date. We make no
  1296  // attempt to detect or solve this problem.
  1297  //
  1298  // Another problem is that due to file system imprecision, an input and
  1299  // output that are actually ordered in time have the same mtime.
  1300  // This typically happens on file systems with 1-second (or, worse,
  1301  // 2-second) mtime granularity and with automated scripts that write an
  1302  // input and then immediately run a build, or vice versa. If an input and
  1303  // an output have the same mtime, the conservative behavior is to treat
  1304  // the output as out-of-date and rebuild. This can cause one or more
  1305  // spurious rebuilds, but only for 1 second, until the object finally has
  1306  // an mtime later than the input.
  1307  //
  1308  // Another problem is that binary distributions often set the mtime on
  1309  // all files to the same time. If the distribution includes both inputs
  1310  // and cached build outputs, the conservative solution to the previous
  1311  // problem will cause unnecessary rebuilds. Worse, in such a binary
  1312  // distribution, those rebuilds might not even have permission to update
  1313  // the cached build output. To avoid these write errors, if an input and
  1314  // output have the same mtime, we assume the output is up-to-date.
  1315  // This is the opposite of what the previous problem would have us do,
  1316  // but binary distributions are more common than instances of the
  1317  // previous problem.
  1318  //
  1319  // A variant of the last problem is that some binary distributions do not
  1320  // set the mtime on all files to the same time. Instead they let the file
  1321  // system record mtimes as the distribution is unpacked. If the outputs
  1322  // are unpacked before the inputs, they'll be older and a build will try
  1323  // to rebuild them. That rebuild might hit the same write errors as in
  1324  // the last scenario. We don't make any attempt to solve this, and we
  1325  // haven't had many reports of it. Perhaps the only time this happens is
  1326  // when people manually unpack the distribution, and most of the time
  1327  // that's done as the same user who will be using it, so an initial
  1328  // rebuild on first use succeeds quietly.
  1329  //
  1330  // More generally, people and programs change mtimes on files. The last
  1331  // few problems were specific examples of this, but it's a general problem.
  1332  // For example, instead of a binary distribution, copying a home
  1333  // directory from one directory or machine to another might copy files
  1334  // but not preserve mtimes. If the inputs are new than the outputs on the
  1335  // first machine but copied first, they end up older than the outputs on
  1336  // the second machine.
  1337  //
  1338  // Because many other build systems have the same sensitivity to mtimes,
  1339  // most programs manipulating source code take pains not to break the
  1340  // mtime assumptions. For example, Git does not set the mtime of files
  1341  // during a checkout operation, even when checking out an old version of
  1342  // the code. This decision was made specifically to work well with
  1343  // mtime-based build systems.
  1344  //
  1345  // The killer problem, though, for mtime-based build systems is that the
  1346  // build only has access to the mtimes of the inputs that still exist.
  1347  // If it is possible to remove an input without changing any other inputs,
  1348  // a later build will think the object is up-to-date when it is not.
  1349  // This happens for Go because a package is made up of all source
  1350  // files in a directory. If a source file is removed, there is no newer
  1351  // mtime available recording that fact. The mtime on the directory could
  1352  // be used, but it also changes when unrelated files are added to or
  1353  // removed from the directory, so including the directory mtime would
  1354  // cause unnecessary rebuilds, possibly many. It would also exacerbate
  1355  // the problems mentioned earlier, since even programs that are careful
  1356  // to maintain mtimes on files rarely maintain mtimes on directories.
  1357  //
  1358  // A variant of the last problem is when the inputs change for other
  1359  // reasons. For example, Go 1.4 and Go 1.5 both install $GOPATH/src/mypkg
  1360  // into the same target, $GOPATH/pkg/$GOOS_$GOARCH/mypkg.a.
  1361  // If Go 1.4 has built mypkg into mypkg.a, a build using Go 1.5 must
  1362  // rebuild mypkg.a, but from mtimes alone mypkg.a looks up-to-date.
  1363  // If Go 1.5 has just been installed, perhaps the compiler will have a
  1364  // newer mtime; since the compiler is considered an input, that would
  1365  // trigger a rebuild. But only once, and only the last Go 1.4 build of
  1366  // mypkg.a happened before Go 1.5 was installed. If a user has the two
  1367  // versions installed in different locations and flips back and forth,
  1368  // mtimes alone cannot tell what to do. Changing the toolchain is
  1369  // changing the set of inputs, without affecting any mtimes.
  1370  //
  1371  // To detect the set of inputs changing, we turn away from mtimes and to
  1372  // an explicit data comparison. Specifically, we build a list of the
  1373  // inputs to the build, compute its SHA1 hash, and record that as the
  1374  // ``build ID'' in the generated object. At the next build, we can
  1375  // recompute the build ID and compare it to the one in the generated
  1376  // object. If they differ, the list of inputs has changed, so the object
  1377  // is out of date and must be rebuilt.
  1378  //
  1379  // Because this build ID is computed before the build begins, the
  1380  // comparison does not have the race that mtime comparison does.
  1381  //
  1382  // Making the build sensitive to changes in other state is
  1383  // straightforward: include the state in the build ID hash, and if it
  1384  // changes, so does the build ID, triggering a rebuild.
  1385  //
  1386  // To detect changes in toolchain, we include the toolchain version in
  1387  // the build ID hash for package runtime, and then we include the build
  1388  // IDs of all imported packages in the build ID for p.
  1389  //
  1390  // It is natural to think about including build tags in the build ID, but
  1391  // the naive approach of just dumping the tags into the hash would cause
  1392  // spurious rebuilds. For example, 'go install' and 'go install -tags neverusedtag'
  1393  // produce the same binaries (assuming neverusedtag is never used).
  1394  // A more precise approach would be to include only tags that have an
  1395  // effect on the build. But the effect of a tag on the build is to
  1396  // include or exclude a file from the compilation, and that file list is
  1397  // already in the build ID hash. So the build ID is already tag-sensitive
  1398  // in a perfectly precise way. So we do NOT explicitly add build tags to
  1399  // the build ID hash.
  1400  //
  1401  // We do not include as part of the build ID the operating system,
  1402  // architecture, or whether the race detector is enabled, even though all
  1403  // three have an effect on the output, because that information is used
  1404  // to decide the install location. Binaries for linux and binaries for
  1405  // darwin are written to different directory trees; including that
  1406  // information in the build ID is unnecessary (although it would be
  1407  // harmless).
  1408  //
  1409  // TODO(rsc): Investigate the cost of putting source file content into
  1410  // the build ID hash as a replacement for the use of mtimes. Using the
  1411  // file content would avoid all the mtime problems, but it does require
  1412  // reading all the source files, something we avoid today (we read the
  1413  // beginning to find the build tags and the imports, but we stop as soon
  1414  // as we see the import block is over). If the package is stale, the compiler
  1415  // is going to read the files anyway. But if the package is up-to-date, the
  1416  // read is overhead.
  1417  //
  1418  // TODO(rsc): Investigate the complexity of making the build more
  1419  // precise about when individual results are needed. To be fully precise,
  1420  // there are two results of a compilation: the entire .a file used by the link
  1421  // and the subpiece used by later compilations (__.PKGDEF only).
  1422  // If a rebuild is needed but produces the previous __.PKGDEF, then
  1423  // no more recompilation due to the rebuilt package is needed, only
  1424  // relinking. To date, there is nothing in the Go command to express this.
  1425  //
  1426  // Special Cases
  1427  //
  1428  // When the go command makes the wrong build decision and does not
  1429  // rebuild something it should, users fall back to adding the -a flag.
  1430  // Any common use of the -a flag should be considered prima facie evidence
  1431  // that isStale is returning an incorrect false result in some important case.
  1432  // Bugs reported in the behavior of -a itself should prompt the question
  1433  // ``Why is -a being used at all? What bug does that indicate?''
  1434  //
  1435  // There is a long history of changes to isStale to try to make -a into a
  1436  // suitable workaround for bugs in the mtime-based decisions.
  1437  // It is worth recording that history to inform (and, as much as possible, deter) future changes.
  1438  //
  1439  // (1) Before the build IDs were introduced, building with alternate tags
  1440  // would happily reuse installed objects built without those tags.
  1441  // For example, "go build -tags netgo myprog.go" would use the installed
  1442  // copy of package net, even if that copy had been built without netgo.
  1443  // (The netgo tag controls whether package net uses cgo or pure Go for
  1444  // functionality such as name resolution.)
  1445  // Using the installed non-netgo package defeats the purpose.
  1446  //
  1447  // Users worked around this with "go build -tags netgo -a myprog.go".
  1448  //
  1449  // Build IDs have made that workaround unnecessary:
  1450  // "go build -tags netgo myprog.go"
  1451  // cannot use a non-netgo copy of package net.
  1452  //
  1453  // (2) Before the build IDs were introduced, building with different toolchains,
  1454  // especially changing between toolchains, tried to reuse objects stored in
  1455  // $GOPATH/pkg, resulting in link-time errors about object file mismatches.
  1456  //
  1457  // Users worked around this with "go install -a ./...".
  1458  //
  1459  // Build IDs have made that workaround unnecessary:
  1460  // "go install ./..." will rebuild any objects it finds that were built against
  1461  // a different toolchain.
  1462  //
  1463  // (3) The common use of "go install -a ./..." led to reports of problems
  1464  // when the -a forced the rebuild of the standard library, which for some
  1465  // users was not writable. Because we didn't understand that the real
  1466  // problem was the bug -a was working around, we changed -a not to
  1467  // apply to the standard library.
  1468  //
  1469  // (4) The common use of "go build -tags netgo -a myprog.go" broke
  1470  // when we changed -a not to apply to the standard library, because
  1471  // if go build doesn't rebuild package net, it uses the non-netgo version.
  1472  //
  1473  // Users worked around this with "go build -tags netgo -installsuffix barf myprog.go".
  1474  // The -installsuffix here is making the go command look for packages
  1475  // in pkg/$GOOS_$GOARCH_barf instead of pkg/$GOOS_$GOARCH.
  1476  // Since the former presumably doesn't exist, go build decides to rebuild
  1477  // everything, including the standard library. Since go build doesn't
  1478  // install anything it builds, nothing is ever written to pkg/$GOOS_$GOARCH_barf,
  1479  // so repeated invocations continue to work.
  1480  //
  1481  // If the use of -a wasn't a red flag, the use of -installsuffix to point to
  1482  // a non-existent directory in a command that installs nothing should
  1483  // have been.
  1484  //
  1485  // (5) Now that (1) and (2) no longer need -a, we have removed the kludge
  1486  // introduced in (3): once again, -a means ``rebuild everything,'' not
  1487  // ``rebuild everything except the standard library.'' Only Go 1.4 had
  1488  // the restricted meaning.
  1489  //
  1490  // In addition to these cases trying to trigger rebuilds, there are
  1491  // special cases trying NOT to trigger rebuilds. The main one is that for
  1492  // a variety of reasons (see above), the install process for a Go release
  1493  // cannot be relied upon to set the mtimes such that the go command will
  1494  // think the standard library is up to date. So the mtime evidence is
  1495  // ignored for the standard library if we find ourselves in a release
  1496  // version of Go. Build ID-based staleness checks still apply to the
  1497  // standard library, even in release versions. This makes
  1498  // 'go build -tags netgo' work, among other things.
  1499  
  1500  // isStale reports whether package p needs to be rebuilt,
  1501  // along with the reason why.
  1502  func isStale(p *Package) (bool, string) {
  1503  	if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
  1504  		// fake, builtin package
  1505  		return false, "builtin package"
  1506  	}
  1507  	if p.Error != nil {
  1508  		return true, "errors loading package"
  1509  	}
  1510  	if p.Stale {
  1511  		return true, p.StaleReason
  1512  	}
  1513  
  1514  	// If this is a package with no source code, it cannot be rebuilt.
  1515  	// If the binary is missing, we mark the package stale so that
  1516  	// if a rebuild is needed, that rebuild attempt will produce a useful error.
  1517  	// (Some commands, such as 'go list', do not attempt to rebuild.)
  1518  	if p.BinaryOnly {
  1519  		if p.Internal.Target == "" {
  1520  			// Fail if a build is attempted.
  1521  			return true, "no source code for package, but no install target"
  1522  		}
  1523  		if _, err := os.Stat(p.Internal.Target); err != nil {
  1524  			// Fail if a build is attempted.
  1525  			return true, "no source code for package, but cannot access install target: " + err.Error()
  1526  		}
  1527  		return false, "no source code for package"
  1528  	}
  1529  
  1530  	// If the -a flag is given, rebuild everything.
  1531  	if cfg.BuildA {
  1532  		return true, "build -a flag in use"
  1533  	}
  1534  
  1535  	// If there's no install target, we have to rebuild.
  1536  	if p.Internal.Target == "" {
  1537  		return true, "no install target"
  1538  	}
  1539  
  1540  	// Package is stale if completely unbuilt.
  1541  	fi, err := os.Stat(p.Internal.Target)
  1542  	if err != nil {
  1543  		return true, "cannot stat install target"
  1544  	}
  1545  
  1546  	// Package is stale if the expected build ID differs from the
  1547  	// recorded build ID. This catches changes like a source file
  1548  	// being removed from a package directory. See issue 3895.
  1549  	// It also catches changes in build tags that affect the set of
  1550  	// files being compiled. See issue 9369.
  1551  	// It also catches changes in toolchain, like when flipping between
  1552  	// two versions of Go compiling a single GOPATH.
  1553  	// See issue 8290 and issue 10702.
  1554  	targetBuildID, err := buildid.ReadBuildID(p.Name, p.Target)
  1555  	if err == nil && targetBuildID != p.Internal.BuildID {
  1556  		return true, "build ID mismatch"
  1557  	}
  1558  
  1559  	// Package is stale if a dependency is.
  1560  	for _, p1 := range p.Internal.Imports {
  1561  		if p1.Stale {
  1562  			return true, "stale dependency"
  1563  		}
  1564  	}
  1565  
  1566  	// The checks above are content-based staleness.
  1567  	// We assume they are always accurate.
  1568  	//
  1569  	// The checks below are mtime-based staleness.
  1570  	// We hope they are accurate, but we know that they fail in the case of
  1571  	// prebuilt Go installations that don't preserve the build mtimes
  1572  	// (for example, if the pkg/ mtimes are before the src/ mtimes).
  1573  	// See the large comment above isStale for details.
  1574  
  1575  	// If we are running a release copy of Go and didn't find a content-based
  1576  	// reason to rebuild the standard packages, do not rebuild them.
  1577  	// They may not be writable anyway, but they are certainly not changing.
  1578  	// This makes 'go build' skip the standard packages when
  1579  	// using an official release, even when the mtimes have been changed.
  1580  	// See issue 3036, issue 3149, issue 4106, issue 8290.
  1581  	// (If a change to a release tree must be made by hand, the way to force the
  1582  	// install is to run make.bash, which will remove the old package archives
  1583  	// before rebuilding.)
  1584  	if p.Standard && isGoRelease {
  1585  		return false, "standard package in Go release distribution"
  1586  	}
  1587  
  1588  	// Time-based staleness.
  1589  
  1590  	built := fi.ModTime()
  1591  
  1592  	olderThan := func(file string) bool {
  1593  		fi, err := os.Stat(file)
  1594  		return err != nil || fi.ModTime().After(built)
  1595  	}
  1596  
  1597  	// Package is stale if a dependency is, or if a dependency is newer.
  1598  	for _, p1 := range p.Internal.Imports {
  1599  		if p1.Internal.Target != "" && olderThan(p1.Internal.Target) {
  1600  			return true, "newer dependency"
  1601  		}
  1602  	}
  1603  
  1604  	// As a courtesy to developers installing new versions of the compiler
  1605  	// frequently, define that packages are stale if they are
  1606  	// older than the compiler, and commands if they are older than
  1607  	// the linker. This heuristic will not work if the binaries are
  1608  	// back-dated, as some binary distributions may do, but it does handle
  1609  	// a very common case.
  1610  	// See issue 3036.
  1611  	// Exclude $GOROOT, under the assumption that people working on
  1612  	// the compiler may want to control when everything gets rebuilt,
  1613  	// and people updating the Go repository will run make.bash or all.bash
  1614  	// and get a full rebuild anyway.
  1615  	// Excluding $GOROOT used to also fix issue 4106, but that's now
  1616  	// taken care of above (at least when the installed Go is a released version).
  1617  	if p.Root != cfg.GOROOT {
  1618  		if olderThan(cfg.BuildToolchainCompiler()) {
  1619  			return true, "newer compiler"
  1620  		}
  1621  		if p.Internal.Build.IsCommand() && olderThan(cfg.BuildToolchainLinker()) {
  1622  			return true, "newer linker"
  1623  		}
  1624  	}
  1625  
  1626  	// Note: Until Go 1.5, we had an additional shortcut here.
  1627  	// We built a list of the workspace roots ($GOROOT, each $GOPATH)
  1628  	// containing targets directly named on the command line,
  1629  	// and if p were not in any of those, it would be treated as up-to-date
  1630  	// as long as it is built. The goal was to avoid rebuilding a system-installed
  1631  	// $GOROOT, unless something from $GOROOT were explicitly named
  1632  	// on the command line (like go install math).
  1633  	// That's now handled by the isGoRelease clause above.
  1634  	// The other effect of the shortcut was to isolate different entries in
  1635  	// $GOPATH from each other. This had the unfortunate effect that
  1636  	// if you had (say), GOPATH listing two entries, one for commands
  1637  	// and one for libraries, and you did a 'git pull' in the library one
  1638  	// and then tried 'go install commands/...', it would build the new libraries
  1639  	// during the first build (because they wouldn't have been installed at all)
  1640  	// but then subsequent builds would not rebuild the libraries, even if the
  1641  	// mtimes indicate they are stale, because the different GOPATH entries
  1642  	// were treated differently. This behavior was confusing when using
  1643  	// non-trivial GOPATHs, which were particularly common with some
  1644  	// code management conventions, like the original godep.
  1645  	// Since the $GOROOT case (the original motivation) is handled separately,
  1646  	// we no longer put a barrier between the different $GOPATH entries.
  1647  	//
  1648  	// One implication of this is that if there is a system directory for
  1649  	// non-standard Go packages that is included in $GOPATH, the mtimes
  1650  	// on those compiled packages must be no earlier than the mtimes
  1651  	// on the source files. Since most distributions use the same mtime
  1652  	// for all files in a tree, they will be unaffected. People using plain
  1653  	// tar x to extract system-installed packages will need to adjust mtimes,
  1654  	// but it's better to force them to get the mtimes right than to ignore
  1655  	// the mtimes and thereby do the wrong thing in common use cases.
  1656  	//
  1657  	// So there is no GOPATH vs GOPATH shortcut here anymore.
  1658  	//
  1659  	// If something needs to come back here, we could try writing a dummy
  1660  	// file with a random name to the $GOPATH/pkg directory (and removing it)
  1661  	// to test for write access, and then skip GOPATH roots we don't have write
  1662  	// access to. But hopefully we can just use the mtimes always.
  1663  
  1664  	srcs := str.StringList(p.GoFiles, p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.CgoFiles, p.SysoFiles, p.SwigFiles, p.SwigCXXFiles)
  1665  	for _, src := range srcs {
  1666  		if olderThan(filepath.Join(p.Dir, src)) {
  1667  			return true, "newer source file"
  1668  		}
  1669  	}
  1670  
  1671  	return false, ""
  1672  }
  1673  
  1674  // computeBuildID computes the build ID for p, leaving it in p.Internal.BuildID.
  1675  // Build ID is a hash of the information we want to detect changes in.
  1676  // See the long comment in isStale for details.
  1677  func computeBuildID(p *Package) {
  1678  	h := sha1.New()
  1679  
  1680  	// Include the list of files compiled as part of the package.
  1681  	// This lets us detect removed files. See issue 3895.
  1682  	inputFiles := str.StringList(
  1683  		p.GoFiles,
  1684  		p.CgoFiles,
  1685  		p.CFiles,
  1686  		p.CXXFiles,
  1687  		p.FFiles,
  1688  		p.MFiles,
  1689  		p.HFiles,
  1690  		p.SFiles,
  1691  		p.SysoFiles,
  1692  		p.SwigFiles,
  1693  		p.SwigCXXFiles,
  1694  	)
  1695  	for _, file := range inputFiles {
  1696  		fmt.Fprintf(h, "file %s\n", file)
  1697  	}
  1698  
  1699  	// Include the content of runtime/internal/sys/zversion.go in the hash
  1700  	// for package runtime. This will give package runtime a
  1701  	// different build ID in each Go release.
  1702  	if p.Standard && p.ImportPath == "runtime/internal/sys" && cfg.BuildContext.Compiler != "gccgo" {
  1703  		data, err := ioutil.ReadFile(filepath.Join(p.Dir, "zversion.go"))
  1704  		if os.IsNotExist(err) {
  1705  			p.Stale = true
  1706  			p.StaleReason = fmt.Sprintf("missing zversion.go")
  1707  		} else if err != nil {
  1708  			base.Fatalf("go: %s", err)
  1709  		}
  1710  		fmt.Fprintf(h, "zversion %q\n", string(data))
  1711  
  1712  		// Add environment variables that affect code generation.
  1713  		switch cfg.BuildContext.GOARCH {
  1714  		case "arm":
  1715  			fmt.Fprintf(h, "GOARM=%s\n", cfg.GOARM)
  1716  		case "386":
  1717  			fmt.Fprintf(h, "GO386=%s\n", cfg.GO386)
  1718  		}
  1719  	}
  1720  
  1721  	// Include the build IDs of any dependencies in the hash.
  1722  	// This, combined with the runtime/zversion content,
  1723  	// will cause packages to have different build IDs when
  1724  	// compiled with different Go releases.
  1725  	// This helps the go command know to recompile when
  1726  	// people use the same GOPATH but switch between
  1727  	// different Go releases. See issue 10702.
  1728  	// This is also a better fix for issue 8290.
  1729  	for _, p1 := range p.Internal.Imports {
  1730  		fmt.Fprintf(h, "dep %s %s\n", p1.ImportPath, p1.Internal.BuildID)
  1731  	}
  1732  
  1733  	p.Internal.BuildID = fmt.Sprintf("%x", h.Sum(nil))
  1734  }
  1735  
  1736  var cmdCache = map[string]*Package{}
  1737  
  1738  func ClearCmdCache() {
  1739  	for name := range cmdCache {
  1740  		delete(cmdCache, name)
  1741  	}
  1742  }
  1743  
  1744  // loadPackage is like loadImport but is used for command-line arguments,
  1745  // not for paths found in import statements. In addition to ordinary import paths,
  1746  // loadPackage accepts pseudo-paths beginning with cmd/ to denote commands
  1747  // in the Go command directory, as well as paths to those directories.
  1748  func LoadPackage(arg string, stk *ImportStack) *Package {
  1749  	if build.IsLocalImport(arg) {
  1750  		dir := arg
  1751  		if !filepath.IsAbs(dir) {
  1752  			if abs, err := filepath.Abs(dir); err == nil {
  1753  				// interpret relative to current directory
  1754  				dir = abs
  1755  			}
  1756  		}
  1757  		if sub, ok := hasSubdir(cfg.GOROOTsrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") {
  1758  			arg = sub
  1759  		}
  1760  	}
  1761  	if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") {
  1762  		if p := cmdCache[arg]; p != nil {
  1763  			return p
  1764  		}
  1765  		stk.Push(arg)
  1766  		defer stk.Pop()
  1767  
  1768  		bp, err := cfg.BuildContext.ImportDir(filepath.Join(cfg.GOROOTsrc, arg), 0)
  1769  		bp.ImportPath = arg
  1770  		bp.Goroot = true
  1771  		bp.BinDir = cfg.GOROOTbin
  1772  		if cfg.GOROOTbin != "" {
  1773  			bp.BinDir = cfg.GOROOTbin
  1774  		}
  1775  		bp.Root = cfg.GOROOT
  1776  		bp.SrcRoot = cfg.GOROOTsrc
  1777  		p := new(Package)
  1778  		cmdCache[arg] = p
  1779  		p.load(stk, bp, err)
  1780  		if p.Error == nil && p.Name != "main" {
  1781  			p.Error = &PackageError{
  1782  				ImportStack: stk.Copy(),
  1783  				Err:         fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir),
  1784  			}
  1785  		}
  1786  		return p
  1787  	}
  1788  
  1789  	// Wasn't a command; must be a package.
  1790  	// If it is a local import path but names a standard package,
  1791  	// we treat it as if the user specified the standard package.
  1792  	// This lets you run go test ./ioutil in package io and be
  1793  	// referring to io/ioutil rather than a hypothetical import of
  1794  	// "./ioutil".
  1795  	if build.IsLocalImport(arg) {
  1796  		bp, _ := cfg.BuildContext.ImportDir(filepath.Join(base.Cwd, arg), build.FindOnly)
  1797  		if bp.ImportPath != "" && bp.ImportPath != "." {
  1798  			arg = bp.ImportPath
  1799  		}
  1800  	}
  1801  
  1802  	return LoadImport(arg, base.Cwd, nil, stk, nil, 0)
  1803  }
  1804  
  1805  // packages returns the packages named by the
  1806  // command line arguments 'args'. If a named package
  1807  // cannot be loaded at all (for example, if the directory does not exist),
  1808  // then packages prints an error and does not include that
  1809  // package in the results. However, if errors occur trying
  1810  // to load dependencies of a named package, the named
  1811  // package is still returned, with p.Incomplete = true
  1812  // and details in p.DepsErrors.
  1813  func Packages(args []string) []*Package {
  1814  	var pkgs []*Package
  1815  	for _, pkg := range PackagesAndErrors(args) {
  1816  		if pkg.Error != nil {
  1817  			base.Errorf("can't load package: %s", pkg.Error)
  1818  			continue
  1819  		}
  1820  		pkgs = append(pkgs, pkg)
  1821  	}
  1822  	return pkgs
  1823  }
  1824  
  1825  // packagesAndErrors is like 'packages' but returns a
  1826  // *Package for every argument, even the ones that
  1827  // cannot be loaded at all.
  1828  // The packages that fail to load will have p.Error != nil.
  1829  func PackagesAndErrors(args []string) []*Package {
  1830  	if len(args) > 0 && strings.HasSuffix(args[0], ".go") {
  1831  		return []*Package{GoFilesPackage(args)}
  1832  	}
  1833  
  1834  	args = ImportPaths(args)
  1835  	var (
  1836  		pkgs    []*Package
  1837  		stk     ImportStack
  1838  		seenArg = make(map[string]bool)
  1839  		seenPkg = make(map[*Package]bool)
  1840  	)
  1841  
  1842  	for _, arg := range args {
  1843  		if seenArg[arg] {
  1844  			continue
  1845  		}
  1846  		seenArg[arg] = true
  1847  		pkg := LoadPackage(arg, &stk)
  1848  		if seenPkg[pkg] {
  1849  			continue
  1850  		}
  1851  		seenPkg[pkg] = true
  1852  		pkgs = append(pkgs, pkg)
  1853  	}
  1854  	ComputeStale(pkgs...)
  1855  
  1856  	return pkgs
  1857  }
  1858  
  1859  // packagesForBuild is like 'packages' but fails if any of
  1860  // the packages or their dependencies have errors
  1861  // (cannot be built).
  1862  func PackagesForBuild(args []string) []*Package {
  1863  	pkgs := PackagesAndErrors(args)
  1864  	printed := map[*PackageError]bool{}
  1865  	for _, pkg := range pkgs {
  1866  		if pkg.Error != nil {
  1867  			base.Errorf("can't load package: %s", pkg.Error)
  1868  		}
  1869  		for _, err := range pkg.DepsErrors {
  1870  			// Since these are errors in dependencies,
  1871  			// the same error might show up multiple times,
  1872  			// once in each package that depends on it.
  1873  			// Only print each once.
  1874  			if !printed[err] {
  1875  				printed[err] = true
  1876  				base.Errorf("%s", err)
  1877  			}
  1878  		}
  1879  	}
  1880  	base.ExitIfErrors()
  1881  
  1882  	// Check for duplicate loads of the same package.
  1883  	// That should be impossible, but if it does happen then
  1884  	// we end up trying to build the same package twice,
  1885  	// usually in parallel overwriting the same files,
  1886  	// which doesn't work very well.
  1887  	seen := map[string]bool{}
  1888  	reported := map[string]bool{}
  1889  	for _, pkg := range PackageList(pkgs) {
  1890  		if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
  1891  			reported[pkg.ImportPath] = true
  1892  			base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
  1893  		}
  1894  		seen[pkg.ImportPath] = true
  1895  	}
  1896  	base.ExitIfErrors()
  1897  
  1898  	return pkgs
  1899  }
  1900  
  1901  // GoFilesPackage creates a package for building a collection of Go files
  1902  // (typically named on the command line). The target is named p.a for
  1903  // package p or named after the first Go file for package main.
  1904  func GoFilesPackage(gofiles []string) *Package {
  1905  	// TODO: Remove this restriction.
  1906  	for _, f := range gofiles {
  1907  		if !strings.HasSuffix(f, ".go") {
  1908  			base.Fatalf("named files must be .go files")
  1909  		}
  1910  	}
  1911  
  1912  	var stk ImportStack
  1913  	ctxt := cfg.BuildContext
  1914  	ctxt.UseAllFiles = true
  1915  
  1916  	// Synthesize fake "directory" that only shows the named files,
  1917  	// to make it look like this is a standard package or
  1918  	// command directory. So that local imports resolve
  1919  	// consistently, the files must all be in the same directory.
  1920  	var dirent []os.FileInfo
  1921  	var dir string
  1922  	for _, file := range gofiles {
  1923  		fi, err := os.Stat(file)
  1924  		if err != nil {
  1925  			base.Fatalf("%s", err)
  1926  		}
  1927  		if fi.IsDir() {
  1928  			base.Fatalf("%s is a directory, should be a Go file", file)
  1929  		}
  1930  		dir1, _ := filepath.Split(file)
  1931  		if dir1 == "" {
  1932  			dir1 = "./"
  1933  		}
  1934  		if dir == "" {
  1935  			dir = dir1
  1936  		} else if dir != dir1 {
  1937  			base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
  1938  		}
  1939  		dirent = append(dirent, fi)
  1940  	}
  1941  	ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
  1942  
  1943  	var err error
  1944  	if dir == "" {
  1945  		dir = base.Cwd
  1946  	}
  1947  	dir, err = filepath.Abs(dir)
  1948  	if err != nil {
  1949  		base.Fatalf("%s", err)
  1950  	}
  1951  
  1952  	bp, err := ctxt.ImportDir(dir, 0)
  1953  	pkg := new(Package)
  1954  	pkg.Internal.Local = true
  1955  	pkg.Internal.Cmdline = true
  1956  	stk.Push("main")
  1957  	pkg.load(&stk, bp, err)
  1958  	stk.Pop()
  1959  	pkg.Internal.LocalPrefix = dirToImportPath(dir)
  1960  	pkg.ImportPath = "command-line-arguments"
  1961  	pkg.Internal.Target = ""
  1962  
  1963  	if pkg.Name == "main" {
  1964  		_, elem := filepath.Split(gofiles[0])
  1965  		exe := elem[:len(elem)-len(".go")] + cfg.ExeSuffix
  1966  		if cfg.BuildO == "" {
  1967  			cfg.BuildO = exe
  1968  		}
  1969  		if cfg.GOBIN != "" {
  1970  			pkg.Internal.Target = filepath.Join(cfg.GOBIN, exe)
  1971  		}
  1972  	}
  1973  
  1974  	pkg.Target = pkg.Internal.Target
  1975  	pkg.Stale = true
  1976  	pkg.StaleReason = "files named on command line"
  1977  
  1978  	ComputeStale(pkg)
  1979  	return pkg
  1980  }