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