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