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