github.com/gocuntian/go@v0.0.0-20160610041250-fee02d270bf8/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  		p.SysoFiles = nil
  1026  		// Note that SFiles are okay (they go to the Go assembler)
  1027  		// and HFiles are okay (they might be used by the SFiles).
  1028  	}
  1029  
  1030  	// The gc toolchain only permits C source files with cgo.
  1031  	if len(p.CFiles) > 0 && !p.usesCgo() && !p.usesSwig() && buildContext.Compiler == "gc" {
  1032  		p.Error = &PackageError{
  1033  			ImportStack: stk.copy(),
  1034  			Err:         fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")),
  1035  		}
  1036  		return p
  1037  	}
  1038  
  1039  	// In the absence of errors lower in the dependency tree,
  1040  	// check for case-insensitive collisions of import paths.
  1041  	if len(p.DepsErrors) == 0 {
  1042  		dep1, dep2 := foldDup(p.Deps)
  1043  		if dep1 != "" {
  1044  			p.Error = &PackageError{
  1045  				ImportStack: stk.copy(),
  1046  				Err:         fmt.Sprintf("case-insensitive import collision: %q and %q", dep1, dep2),
  1047  			}
  1048  			return p
  1049  		}
  1050  	}
  1051  
  1052  	if p.BinaryOnly {
  1053  		// For binary-only package, use build ID from supplied package binary.
  1054  		buildID, err := readBuildID(p)
  1055  		if err == nil {
  1056  			p.buildID = buildID
  1057  		}
  1058  	} else {
  1059  		computeBuildID(p)
  1060  	}
  1061  	return p
  1062  }
  1063  
  1064  // usesSwig reports whether the package needs to run SWIG.
  1065  func (p *Package) usesSwig() bool {
  1066  	return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
  1067  }
  1068  
  1069  // usesCgo reports whether the package needs to run cgo
  1070  func (p *Package) usesCgo() bool {
  1071  	return len(p.CgoFiles) > 0
  1072  }
  1073  
  1074  // packageList returns the list of packages in the dag rooted at roots
  1075  // as visited in a depth-first post-order traversal.
  1076  func packageList(roots []*Package) []*Package {
  1077  	seen := map[*Package]bool{}
  1078  	all := []*Package{}
  1079  	var walk func(*Package)
  1080  	walk = func(p *Package) {
  1081  		if seen[p] {
  1082  			return
  1083  		}
  1084  		seen[p] = true
  1085  		for _, p1 := range p.imports {
  1086  			walk(p1)
  1087  		}
  1088  		all = append(all, p)
  1089  	}
  1090  	for _, root := range roots {
  1091  		walk(root)
  1092  	}
  1093  	return all
  1094  }
  1095  
  1096  // computeStale computes the Stale flag in the package dag that starts
  1097  // at the named pkgs (command-line arguments).
  1098  func computeStale(pkgs ...*Package) {
  1099  	for _, p := range packageList(pkgs) {
  1100  		p.Stale, p.StaleReason = isStale(p)
  1101  	}
  1102  }
  1103  
  1104  // The runtime version string takes one of two forms:
  1105  // "go1.X[.Y]" for Go releases, and "devel +hash" at tip.
  1106  // Determine whether we are in a released copy by
  1107  // inspecting the version.
  1108  var isGoRelease = strings.HasPrefix(runtime.Version(), "go1")
  1109  
  1110  // isStale and computeBuildID
  1111  //
  1112  // Theory of Operation
  1113  //
  1114  // There is an installed copy of the package (or binary).
  1115  // Can we reuse the installed copy, or do we need to build a new one?
  1116  //
  1117  // We can use the installed copy if it matches what we'd get
  1118  // by building a new one. The hard part is predicting that without
  1119  // actually running a build.
  1120  //
  1121  // To start, we must know the set of inputs to the build process that can
  1122  // affect the generated output. At a minimum, that includes the source
  1123  // files for the package and also any compiled packages imported by those
  1124  // source files. The *Package has these, and we use them. One might also
  1125  // argue for including in the input set: the build tags, whether the race
  1126  // detector is in use, the target operating system and architecture, the
  1127  // compiler and linker binaries being used, the additional flags being
  1128  // passed to those, the cgo binary being used, the additional flags cgo
  1129  // passes to the host C compiler, the host C compiler being used, the set
  1130  // of host C include files and installed C libraries, and so on.
  1131  // We include some but not all of this information.
  1132  //
  1133  // Once we have decided on a set of inputs, we must next decide how to
  1134  // tell whether the content of that set has changed since the last build
  1135  // of p. If there have been no changes, then we assume a new build would
  1136  // produce the same result and reuse the installed package or binary.
  1137  // But if there have been changes, then we assume a new build might not
  1138  // produce the same result, so we rebuild.
  1139  //
  1140  // There are two common ways to decide whether the content of the set has
  1141  // changed: modification times and content hashes. We use a mixture of both.
  1142  //
  1143  // The use of modification times (mtimes) was pioneered by make:
  1144  // assuming that a file's mtime is an accurate record of when that file was last written,
  1145  // and assuming that the modification time of an installed package or
  1146  // binary is the time that it was built, if the mtimes of the inputs
  1147  // predate the mtime of the installed object, then the build of that
  1148  // object saw those versions of the files, and therefore a rebuild using
  1149  // those same versions would produce the same object. In contrast, if any
  1150  // mtime of an input is newer than the mtime of the installed object, a
  1151  // change has occurred since the build, and the build should be redone.
  1152  //
  1153  // Modification times are attractive because the logic is easy to
  1154  // understand and the file system maintains the mtimes automatically
  1155  // (less work for us). Unfortunately, there are a variety of ways in
  1156  // which the mtime approach fails to detect a change and reuses a stale
  1157  // object file incorrectly. (Making the opposite mistake, rebuilding
  1158  // unnecessarily, is only a performance problem and not a correctness
  1159  // problem, so we ignore that one.)
  1160  //
  1161  // As a warmup, one problem is that to be perfectly precise, we need to
  1162  // compare the input mtimes against the time at the beginning of the
  1163  // build, but the object file time is the time at the end of the build.
  1164  // If an input file changes after being read but before the object is
  1165  // written, the next build will see an object newer than the input and
  1166  // will incorrectly decide that the object is up to date. We make no
  1167  // attempt to detect or solve this problem.
  1168  //
  1169  // Another problem is that due to file system imprecision, an input and
  1170  // output that are actually ordered in time have the same mtime.
  1171  // This typically happens on file systems with 1-second (or, worse,
  1172  // 2-second) mtime granularity and with automated scripts that write an
  1173  // input and then immediately run a build, or vice versa. If an input and
  1174  // an output have the same mtime, the conservative behavior is to treat
  1175  // the output as out-of-date and rebuild. This can cause one or more
  1176  // spurious rebuilds, but only for 1 second, until the object finally has
  1177  // an mtime later than the input.
  1178  //
  1179  // Another problem is that binary distributions often set the mtime on
  1180  // all files to the same time. If the distribution includes both inputs
  1181  // and cached build outputs, the conservative solution to the previous
  1182  // problem will cause unnecessary rebuilds. Worse, in such a binary
  1183  // distribution, those rebuilds might not even have permission to update
  1184  // the cached build output. To avoid these write errors, if an input and
  1185  // output have the same mtime, we assume the output is up-to-date.
  1186  // This is the opposite of what the previous problem would have us do,
  1187  // but binary distributions are more common than instances of the
  1188  // previous problem.
  1189  //
  1190  // A variant of the last problem is that some binary distributions do not
  1191  // set the mtime on all files to the same time. Instead they let the file
  1192  // system record mtimes as the distribution is unpacked. If the outputs
  1193  // are unpacked before the inputs, they'll be older and a build will try
  1194  // to rebuild them. That rebuild might hit the same write errors as in
  1195  // the last scenario. We don't make any attempt to solve this, and we
  1196  // haven't had many reports of it. Perhaps the only time this happens is
  1197  // when people manually unpack the distribution, and most of the time
  1198  // that's done as the same user who will be using it, so an initial
  1199  // rebuild on first use succeeds quietly.
  1200  //
  1201  // More generally, people and programs change mtimes on files. The last
  1202  // few problems were specific examples of this, but it's a general problem.
  1203  // For example, instead of a binary distribution, copying a home
  1204  // directory from one directory or machine to another might copy files
  1205  // but not preserve mtimes. If the inputs are new than the outputs on the
  1206  // first machine but copied first, they end up older than the outputs on
  1207  // the second machine.
  1208  //
  1209  // Because many other build systems have the same sensitivity to mtimes,
  1210  // most programs manipulating source code take pains not to break the
  1211  // mtime assumptions. For example, Git does not set the mtime of files
  1212  // during a checkout operation, even when checking out an old version of
  1213  // the code. This decision was made specifically to work well with
  1214  // mtime-based build systems.
  1215  //
  1216  // The killer problem, though, for mtime-based build systems is that the
  1217  // build only has access to the mtimes of the inputs that still exist.
  1218  // If it is possible to remove an input without changing any other inputs,
  1219  // a later build will think the object is up-to-date when it is not.
  1220  // This happens for Go because a package is made up of all source
  1221  // files in a directory. If a source file is removed, there is no newer
  1222  // mtime available recording that fact. The mtime on the directory could
  1223  // be used, but it also changes when unrelated files are added to or
  1224  // removed from the directory, so including the directory mtime would
  1225  // cause unnecessary rebuilds, possibly many. It would also exacerbate
  1226  // the problems mentioned earlier, since even programs that are careful
  1227  // to maintain mtimes on files rarely maintain mtimes on directories.
  1228  //
  1229  // A variant of the last problem is when the inputs change for other
  1230  // reasons. For example, Go 1.4 and Go 1.5 both install $GOPATH/src/mypkg
  1231  // into the same target, $GOPATH/pkg/$GOOS_$GOARCH/mypkg.a.
  1232  // If Go 1.4 has built mypkg into mypkg.a, a build using Go 1.5 must
  1233  // rebuild mypkg.a, but from mtimes alone mypkg.a looks up-to-date.
  1234  // If Go 1.5 has just been installed, perhaps the compiler will have a
  1235  // newer mtime; since the compiler is considered an input, that would
  1236  // trigger a rebuild. But only once, and only the last Go 1.4 build of
  1237  // mypkg.a happened before Go 1.5 was installed. If a user has the two
  1238  // versions installed in different locations and flips back and forth,
  1239  // mtimes alone cannot tell what to do. Changing the toolchain is
  1240  // changing the set of inputs, without affecting any mtimes.
  1241  //
  1242  // To detect the set of inputs changing, we turn away from mtimes and to
  1243  // an explicit data comparison. Specifically, we build a list of the
  1244  // inputs to the build, compute its SHA1 hash, and record that as the
  1245  // ``build ID'' in the generated object. At the next build, we can
  1246  // recompute the build ID and compare it to the one in the generated
  1247  // object. If they differ, the list of inputs has changed, so the object
  1248  // is out of date and must be rebuilt.
  1249  //
  1250  // Because this build ID is computed before the build begins, the
  1251  // comparison does not have the race that mtime comparison does.
  1252  //
  1253  // Making the build sensitive to changes in other state is
  1254  // straightforward: include the state in the build ID hash, and if it
  1255  // changes, so does the build ID, triggering a rebuild.
  1256  //
  1257  // To detect changes in toolchain, we include the toolchain version in
  1258  // the build ID hash for package runtime, and then we include the build
  1259  // IDs of all imported packages in the build ID for p.
  1260  //
  1261  // It is natural to think about including build tags in the build ID, but
  1262  // the naive approach of just dumping the tags into the hash would cause
  1263  // spurious rebuilds. For example, 'go install' and 'go install -tags neverusedtag'
  1264  // produce the same binaries (assuming neverusedtag is never used).
  1265  // A more precise approach would be to include only tags that have an
  1266  // effect on the build. But the effect of a tag on the build is to
  1267  // include or exclude a file from the compilation, and that file list is
  1268  // already in the build ID hash. So the build ID is already tag-sensitive
  1269  // in a perfectly precise way. So we do NOT explicitly add build tags to
  1270  // the build ID hash.
  1271  //
  1272  // We do not include as part of the build ID the operating system,
  1273  // architecture, or whether the race detector is enabled, even though all
  1274  // three have an effect on the output, because that information is used
  1275  // to decide the install location. Binaries for linux and binaries for
  1276  // darwin are written to different directory trees; including that
  1277  // information in the build ID is unnecessary (although it would be
  1278  // harmless).
  1279  //
  1280  // TODO(rsc): Investigate the cost of putting source file content into
  1281  // the build ID hash as a replacement for the use of mtimes. Using the
  1282  // file content would avoid all the mtime problems, but it does require
  1283  // reading all the source files, something we avoid today (we read the
  1284  // beginning to find the build tags and the imports, but we stop as soon
  1285  // as we see the import block is over). If the package is stale, the compiler
  1286  // is going to read the files anyway. But if the package is up-to-date, the
  1287  // read is overhead.
  1288  //
  1289  // TODO(rsc): Investigate the complexity of making the build more
  1290  // precise about when individual results are needed. To be fully precise,
  1291  // there are two results of a compilation: the entire .a file used by the link
  1292  // and the subpiece used by later compilations (__.PKGDEF only).
  1293  // If a rebuild is needed but produces the previous __.PKGDEF, then
  1294  // no more recompilation due to the rebuilt package is needed, only
  1295  // relinking. To date, there is nothing in the Go command to express this.
  1296  //
  1297  // Special Cases
  1298  //
  1299  // When the go command makes the wrong build decision and does not
  1300  // rebuild something it should, users fall back to adding the -a flag.
  1301  // Any common use of the -a flag should be considered prima facie evidence
  1302  // that isStale is returning an incorrect false result in some important case.
  1303  // Bugs reported in the behavior of -a itself should prompt the question
  1304  // ``Why is -a being used at all? What bug does that indicate?''
  1305  //
  1306  // There is a long history of changes to isStale to try to make -a into a
  1307  // suitable workaround for bugs in the mtime-based decisions.
  1308  // It is worth recording that history to inform (and, as much as possible, deter) future changes.
  1309  //
  1310  // (1) Before the build IDs were introduced, building with alternate tags
  1311  // would happily reuse installed objects built without those tags.
  1312  // For example, "go build -tags netgo myprog.go" would use the installed
  1313  // copy of package net, even if that copy had been built without netgo.
  1314  // (The netgo tag controls whether package net uses cgo or pure Go for
  1315  // functionality such as name resolution.)
  1316  // Using the installed non-netgo package defeats the purpose.
  1317  //
  1318  // Users worked around this with "go build -tags netgo -a myprog.go".
  1319  //
  1320  // Build IDs have made that workaround unnecessary:
  1321  // "go build -tags netgo myprog.go"
  1322  // cannot use a non-netgo copy of package net.
  1323  //
  1324  // (2) Before the build IDs were introduced, building with different toolchains,
  1325  // especially changing between toolchains, tried to reuse objects stored in
  1326  // $GOPATH/pkg, resulting in link-time errors about object file mismatches.
  1327  //
  1328  // Users worked around this with "go install -a ./...".
  1329  //
  1330  // Build IDs have made that workaround unnecessary:
  1331  // "go install ./..." will rebuild any objects it finds that were built against
  1332  // a different toolchain.
  1333  //
  1334  // (3) The common use of "go install -a ./..." led to reports of problems
  1335  // when the -a forced the rebuild of the standard library, which for some
  1336  // users was not writable. Because we didn't understand that the real
  1337  // problem was the bug -a was working around, we changed -a not to
  1338  // apply to the standard library.
  1339  //
  1340  // (4) The common use of "go build -tags netgo -a myprog.go" broke
  1341  // when we changed -a not to apply to the standard library, because
  1342  // if go build doesn't rebuild package net, it uses the non-netgo version.
  1343  //
  1344  // Users worked around this with "go build -tags netgo -installsuffix barf myprog.go".
  1345  // The -installsuffix here is making the go command look for packages
  1346  // in pkg/$GOOS_$GOARCH_barf instead of pkg/$GOOS_$GOARCH.
  1347  // Since the former presumably doesn't exist, go build decides to rebuild
  1348  // everything, including the standard library. Since go build doesn't
  1349  // install anything it builds, nothing is ever written to pkg/$GOOS_$GOARCH_barf,
  1350  // so repeated invocations continue to work.
  1351  //
  1352  // If the use of -a wasn't a red flag, the use of -installsuffix to point to
  1353  // a non-existent directory in a command that installs nothing should
  1354  // have been.
  1355  //
  1356  // (5) Now that (1) and (2) no longer need -a, we have removed the kludge
  1357  // introduced in (3): once again, -a means ``rebuild everything,'' not
  1358  // ``rebuild everything except the standard library.'' Only Go 1.4 had
  1359  // the restricted meaning.
  1360  //
  1361  // In addition to these cases trying to trigger rebuilds, there are
  1362  // special cases trying NOT to trigger rebuilds. The main one is that for
  1363  // a variety of reasons (see above), the install process for a Go release
  1364  // cannot be relied upon to set the mtimes such that the go command will
  1365  // think the standard library is up to date. So the mtime evidence is
  1366  // ignored for the standard library if we find ourselves in a release
  1367  // version of Go. Build ID-based staleness checks still apply to the
  1368  // standard library, even in release versions. This makes
  1369  // 'go build -tags netgo' work, among other things.
  1370  
  1371  // isStale reports whether package p needs to be rebuilt,
  1372  // along with the reason why.
  1373  func isStale(p *Package) (bool, string) {
  1374  	if p.Standard && (p.ImportPath == "unsafe" || buildContext.Compiler == "gccgo") {
  1375  		// fake, builtin package
  1376  		return false, "builtin package"
  1377  	}
  1378  	if p.Error != nil {
  1379  		return true, "errors loading package"
  1380  	}
  1381  	if p.Stale {
  1382  		return true, p.StaleReason
  1383  	}
  1384  
  1385  	// If this is a package with no source code, it cannot be rebuilt.
  1386  	// If the binary is missing, we mark the package stale so that
  1387  	// if a rebuild is needed, that rebuild attempt will produce a useful error.
  1388  	// (Some commands, such as 'go list', do not attempt to rebuild.)
  1389  	if p.BinaryOnly {
  1390  		if p.target == "" {
  1391  			// Fail if a build is attempted.
  1392  			return true, "no source code for package, but no install target"
  1393  		}
  1394  		if _, err := os.Stat(p.target); err != nil {
  1395  			// Fail if a build is attempted.
  1396  			return true, "no source code for package, but cannot access install target: " + err.Error()
  1397  		}
  1398  		return false, "no source code for package"
  1399  	}
  1400  
  1401  	// If the -a flag is given, rebuild everything.
  1402  	if buildA {
  1403  		return true, "build -a flag in use"
  1404  	}
  1405  
  1406  	// If there's no install target, we have to rebuild.
  1407  	if p.target == "" {
  1408  		return true, "no install target"
  1409  	}
  1410  
  1411  	// Package is stale if completely unbuilt.
  1412  	fi, err := os.Stat(p.target)
  1413  	if err != nil {
  1414  		return true, "cannot stat install target"
  1415  	}
  1416  
  1417  	// Package is stale if the expected build ID differs from the
  1418  	// recorded build ID. This catches changes like a source file
  1419  	// being removed from a package directory. See issue 3895.
  1420  	// It also catches changes in build tags that affect the set of
  1421  	// files being compiled. See issue 9369.
  1422  	// It also catches changes in toolchain, like when flipping between
  1423  	// two versions of Go compiling a single GOPATH.
  1424  	// See issue 8290 and issue 10702.
  1425  	targetBuildID, err := readBuildID(p)
  1426  	if err == nil && targetBuildID != p.buildID {
  1427  		return true, "build ID mismatch"
  1428  	}
  1429  
  1430  	// Package is stale if a dependency is.
  1431  	for _, p1 := range p.deps {
  1432  		if p1.Stale {
  1433  			return true, "stale dependency"
  1434  		}
  1435  	}
  1436  
  1437  	// The checks above are content-based staleness.
  1438  	// We assume they are always accurate.
  1439  	//
  1440  	// The checks below are mtime-based staleness.
  1441  	// We hope they are accurate, but we know that they fail in the case of
  1442  	// prebuilt Go installations that don't preserve the build mtimes
  1443  	// (for example, if the pkg/ mtimes are before the src/ mtimes).
  1444  	// See the large comment above isStale for details.
  1445  
  1446  	// If we are running a release copy of Go and didn't find a content-based
  1447  	// reason to rebuild the standard packages, do not rebuild them.
  1448  	// They may not be writable anyway, but they are certainly not changing.
  1449  	// This makes 'go build' skip the standard packages when
  1450  	// using an official release, even when the mtimes have been changed.
  1451  	// See issue 3036, issue 3149, issue 4106, issue 8290.
  1452  	// (If a change to a release tree must be made by hand, the way to force the
  1453  	// install is to run make.bash, which will remove the old package archives
  1454  	// before rebuilding.)
  1455  	if p.Standard && isGoRelease {
  1456  		return false, "standard package in Go release distribution"
  1457  	}
  1458  
  1459  	// Time-based staleness.
  1460  
  1461  	built := fi.ModTime()
  1462  
  1463  	olderThan := func(file string) bool {
  1464  		fi, err := os.Stat(file)
  1465  		return err != nil || fi.ModTime().After(built)
  1466  	}
  1467  
  1468  	// Package is stale if a dependency is, or if a dependency is newer.
  1469  	for _, p1 := range p.deps {
  1470  		if p1.target != "" && olderThan(p1.target) {
  1471  			return true, "newer dependency"
  1472  		}
  1473  	}
  1474  
  1475  	// As a courtesy to developers installing new versions of the compiler
  1476  	// frequently, define that packages are stale if they are
  1477  	// older than the compiler, and commands if they are older than
  1478  	// the linker. This heuristic will not work if the binaries are
  1479  	// back-dated, as some binary distributions may do, but it does handle
  1480  	// a very common case.
  1481  	// See issue 3036.
  1482  	// Exclude $GOROOT, under the assumption that people working on
  1483  	// the compiler may want to control when everything gets rebuilt,
  1484  	// and people updating the Go repository will run make.bash or all.bash
  1485  	// and get a full rebuild anyway.
  1486  	// Excluding $GOROOT used to also fix issue 4106, but that's now
  1487  	// taken care of above (at least when the installed Go is a released version).
  1488  	if p.Root != goroot {
  1489  		if olderThan(buildToolchain.compiler()) {
  1490  			return true, "newer compiler"
  1491  		}
  1492  		if p.build.IsCommand() && olderThan(buildToolchain.linker()) {
  1493  			return true, "newer linker"
  1494  		}
  1495  	}
  1496  
  1497  	// Note: Until Go 1.5, we had an additional shortcut here.
  1498  	// We built a list of the workspace roots ($GOROOT, each $GOPATH)
  1499  	// containing targets directly named on the command line,
  1500  	// and if p were not in any of those, it would be treated as up-to-date
  1501  	// as long as it is built. The goal was to avoid rebuilding a system-installed
  1502  	// $GOROOT, unless something from $GOROOT were explicitly named
  1503  	// on the command line (like go install math).
  1504  	// That's now handled by the isGoRelease clause above.
  1505  	// The other effect of the shortcut was to isolate different entries in
  1506  	// $GOPATH from each other. This had the unfortunate effect that
  1507  	// if you had (say), GOPATH listing two entries, one for commands
  1508  	// and one for libraries, and you did a 'git pull' in the library one
  1509  	// and then tried 'go install commands/...', it would build the new libraries
  1510  	// during the first build (because they wouldn't have been installed at all)
  1511  	// but then subsequent builds would not rebuild the libraries, even if the
  1512  	// mtimes indicate they are stale, because the different GOPATH entries
  1513  	// were treated differently. This behavior was confusing when using
  1514  	// non-trivial GOPATHs, which were particularly common with some
  1515  	// code management conventions, like the original godep.
  1516  	// Since the $GOROOT case (the original motivation) is handled separately,
  1517  	// we no longer put a barrier between the different $GOPATH entries.
  1518  	//
  1519  	// One implication of this is that if there is a system directory for
  1520  	// non-standard Go packages that is included in $GOPATH, the mtimes
  1521  	// on those compiled packages must be no earlier than the mtimes
  1522  	// on the source files. Since most distributions use the same mtime
  1523  	// for all files in a tree, they will be unaffected. People using plain
  1524  	// tar x to extract system-installed packages will need to adjust mtimes,
  1525  	// but it's better to force them to get the mtimes right than to ignore
  1526  	// the mtimes and thereby do the wrong thing in common use cases.
  1527  	//
  1528  	// So there is no GOPATH vs GOPATH shortcut here anymore.
  1529  	//
  1530  	// If something needs to come back here, we could try writing a dummy
  1531  	// file with a random name to the $GOPATH/pkg directory (and removing it)
  1532  	// to test for write access, and then skip GOPATH roots we don't have write
  1533  	// access to. But hopefully we can just use the mtimes always.
  1534  
  1535  	srcs := stringList(p.GoFiles, p.CFiles, p.CXXFiles, p.MFiles, p.HFiles, p.FFiles, p.SFiles, p.CgoFiles, p.SysoFiles, p.SwigFiles, p.SwigCXXFiles)
  1536  	for _, src := range srcs {
  1537  		if olderThan(filepath.Join(p.Dir, src)) {
  1538  			return true, "newer source file"
  1539  		}
  1540  	}
  1541  
  1542  	return false, ""
  1543  }
  1544  
  1545  // computeBuildID computes the build ID for p, leaving it in p.buildID.
  1546  // Build ID is a hash of the information we want to detect changes in.
  1547  // See the long comment in isStale for details.
  1548  func computeBuildID(p *Package) {
  1549  	h := sha1.New()
  1550  
  1551  	// Include the list of files compiled as part of the package.
  1552  	// This lets us detect removed files. See issue 3895.
  1553  	inputFiles := stringList(
  1554  		p.GoFiles,
  1555  		p.CgoFiles,
  1556  		p.CFiles,
  1557  		p.CXXFiles,
  1558  		p.MFiles,
  1559  		p.HFiles,
  1560  		p.SFiles,
  1561  		p.SysoFiles,
  1562  		p.SwigFiles,
  1563  		p.SwigCXXFiles,
  1564  	)
  1565  	for _, file := range inputFiles {
  1566  		fmt.Fprintf(h, "file %s\n", file)
  1567  	}
  1568  
  1569  	// Include the content of runtime/internal/sys/zversion.go in the hash
  1570  	// for package runtime. This will give package runtime a
  1571  	// different build ID in each Go release.
  1572  	if p.Standard && p.ImportPath == "runtime/internal/sys" {
  1573  		data, err := ioutil.ReadFile(filepath.Join(p.Dir, "zversion.go"))
  1574  		if err != nil {
  1575  			fatalf("go: %s", err)
  1576  		}
  1577  		fmt.Fprintf(h, "zversion %q\n", string(data))
  1578  	}
  1579  
  1580  	// Include the build IDs of any dependencies in the hash.
  1581  	// This, combined with the runtime/zversion content,
  1582  	// will cause packages to have different build IDs when
  1583  	// compiled with different Go releases.
  1584  	// This helps the go command know to recompile when
  1585  	// people use the same GOPATH but switch between
  1586  	// different Go releases. See issue 10702.
  1587  	// This is also a better fix for issue 8290.
  1588  	for _, p1 := range p.deps {
  1589  		fmt.Fprintf(h, "dep %s %s\n", p1.ImportPath, p1.buildID)
  1590  	}
  1591  
  1592  	p.buildID = fmt.Sprintf("%x", h.Sum(nil))
  1593  }
  1594  
  1595  var cwd, _ = os.Getwd()
  1596  
  1597  var cmdCache = map[string]*Package{}
  1598  
  1599  // loadPackage is like loadImport but is used for command-line arguments,
  1600  // not for paths found in import statements. In addition to ordinary import paths,
  1601  // loadPackage accepts pseudo-paths beginning with cmd/ to denote commands
  1602  // in the Go command directory, as well as paths to those directories.
  1603  func loadPackage(arg string, stk *importStack) *Package {
  1604  	if build.IsLocalImport(arg) {
  1605  		dir := arg
  1606  		if !filepath.IsAbs(dir) {
  1607  			if abs, err := filepath.Abs(dir); err == nil {
  1608  				// interpret relative to current directory
  1609  				dir = abs
  1610  			}
  1611  		}
  1612  		if sub, ok := hasSubdir(gorootSrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") {
  1613  			arg = sub
  1614  		}
  1615  	}
  1616  	if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") {
  1617  		if p := cmdCache[arg]; p != nil {
  1618  			return p
  1619  		}
  1620  		stk.push(arg)
  1621  		defer stk.pop()
  1622  
  1623  		bp, err := buildContext.ImportDir(filepath.Join(gorootSrc, arg), 0)
  1624  		bp.ImportPath = arg
  1625  		bp.Goroot = true
  1626  		bp.BinDir = gorootBin
  1627  		if gobin != "" {
  1628  			bp.BinDir = gobin
  1629  		}
  1630  		bp.Root = goroot
  1631  		bp.SrcRoot = gorootSrc
  1632  		p := new(Package)
  1633  		cmdCache[arg] = p
  1634  		p.load(stk, bp, err)
  1635  		if p.Error == nil && p.Name != "main" {
  1636  			p.Error = &PackageError{
  1637  				ImportStack: stk.copy(),
  1638  				Err:         fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir),
  1639  			}
  1640  		}
  1641  		return p
  1642  	}
  1643  
  1644  	// Wasn't a command; must be a package.
  1645  	// If it is a local import path but names a standard package,
  1646  	// we treat it as if the user specified the standard package.
  1647  	// This lets you run go test ./ioutil in package io and be
  1648  	// referring to io/ioutil rather than a hypothetical import of
  1649  	// "./ioutil".
  1650  	if build.IsLocalImport(arg) {
  1651  		bp, _ := buildContext.ImportDir(filepath.Join(cwd, arg), build.FindOnly)
  1652  		if bp.ImportPath != "" && bp.ImportPath != "." {
  1653  			arg = bp.ImportPath
  1654  		}
  1655  	}
  1656  
  1657  	return loadImport(arg, cwd, nil, stk, nil, 0)
  1658  }
  1659  
  1660  // packages returns the packages named by the
  1661  // command line arguments 'args'.  If a named package
  1662  // cannot be loaded at all (for example, if the directory does not exist),
  1663  // then packages prints an error and does not include that
  1664  // package in the results. However, if errors occur trying
  1665  // to load dependencies of a named package, the named
  1666  // package is still returned, with p.Incomplete = true
  1667  // and details in p.DepsErrors.
  1668  func packages(args []string) []*Package {
  1669  	var pkgs []*Package
  1670  	for _, pkg := range packagesAndErrors(args) {
  1671  		if pkg.Error != nil {
  1672  			errorf("can't load package: %s", pkg.Error)
  1673  			continue
  1674  		}
  1675  		pkgs = append(pkgs, pkg)
  1676  	}
  1677  	return pkgs
  1678  }
  1679  
  1680  // packagesAndErrors is like 'packages' but returns a
  1681  // *Package for every argument, even the ones that
  1682  // cannot be loaded at all.
  1683  // The packages that fail to load will have p.Error != nil.
  1684  func packagesAndErrors(args []string) []*Package {
  1685  	if len(args) > 0 && strings.HasSuffix(args[0], ".go") {
  1686  		return []*Package{goFilesPackage(args)}
  1687  	}
  1688  
  1689  	args = importPaths(args)
  1690  	var (
  1691  		pkgs    []*Package
  1692  		stk     importStack
  1693  		seenArg = make(map[string]bool)
  1694  		seenPkg = make(map[*Package]bool)
  1695  	)
  1696  
  1697  	for _, arg := range args {
  1698  		if seenArg[arg] {
  1699  			continue
  1700  		}
  1701  		seenArg[arg] = true
  1702  		pkg := loadPackage(arg, &stk)
  1703  		if seenPkg[pkg] {
  1704  			continue
  1705  		}
  1706  		seenPkg[pkg] = true
  1707  		pkgs = append(pkgs, pkg)
  1708  	}
  1709  	computeStale(pkgs...)
  1710  
  1711  	return pkgs
  1712  }
  1713  
  1714  // packagesForBuild is like 'packages' but fails if any of
  1715  // the packages or their dependencies have errors
  1716  // (cannot be built).
  1717  func packagesForBuild(args []string) []*Package {
  1718  	pkgs := packagesAndErrors(args)
  1719  	printed := map[*PackageError]bool{}
  1720  	for _, pkg := range pkgs {
  1721  		if pkg.Error != nil {
  1722  			errorf("can't load package: %s", pkg.Error)
  1723  		}
  1724  		for _, err := range pkg.DepsErrors {
  1725  			// Since these are errors in dependencies,
  1726  			// the same error might show up multiple times,
  1727  			// once in each package that depends on it.
  1728  			// Only print each once.
  1729  			if !printed[err] {
  1730  				printed[err] = true
  1731  				errorf("%s", err)
  1732  			}
  1733  		}
  1734  	}
  1735  	exitIfErrors()
  1736  
  1737  	// Check for duplicate loads of the same package.
  1738  	// That should be impossible, but if it does happen then
  1739  	// we end up trying to build the same package twice,
  1740  	// usually in parallel overwriting the same files,
  1741  	// which doesn't work very well.
  1742  	seen := map[string]bool{}
  1743  	reported := map[string]bool{}
  1744  	for _, pkg := range packageList(pkgs) {
  1745  		if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
  1746  			reported[pkg.ImportPath] = true
  1747  			errorf("internal error: duplicate loads of %s", pkg.ImportPath)
  1748  		}
  1749  		seen[pkg.ImportPath] = true
  1750  	}
  1751  	exitIfErrors()
  1752  
  1753  	return pkgs
  1754  }
  1755  
  1756  // hasSubdir reports whether dir is a subdirectory of
  1757  // (possibly multiple levels below) root.
  1758  // If so, it sets rel to the path fragment that must be
  1759  // appended to root to reach dir.
  1760  func hasSubdir(root, dir string) (rel string, ok bool) {
  1761  	if p, err := filepath.EvalSymlinks(root); err == nil {
  1762  		root = p
  1763  	}
  1764  	if p, err := filepath.EvalSymlinks(dir); err == nil {
  1765  		dir = p
  1766  	}
  1767  	const sep = string(filepath.Separator)
  1768  	root = filepath.Clean(root)
  1769  	if !strings.HasSuffix(root, sep) {
  1770  		root += sep
  1771  	}
  1772  	dir = filepath.Clean(dir)
  1773  	if !strings.HasPrefix(dir, root) {
  1774  		return "", false
  1775  	}
  1776  	return filepath.ToSlash(dir[len(root):]), true
  1777  }
  1778  
  1779  var (
  1780  	errBuildIDToolchain = fmt.Errorf("build ID only supported in gc toolchain")
  1781  	errBuildIDMalformed = fmt.Errorf("malformed object file")
  1782  	errBuildIDUnknown   = fmt.Errorf("lost build ID")
  1783  )
  1784  
  1785  var (
  1786  	bangArch = []byte("!<arch>")
  1787  	pkgdef   = []byte("__.PKGDEF")
  1788  	goobject = []byte("go object ")
  1789  	buildid  = []byte("build id ")
  1790  )
  1791  
  1792  // readBuildID reads the build ID from an archive or binary.
  1793  // It only supports the gc toolchain.
  1794  // Other toolchain maintainers should adjust this function.
  1795  func readBuildID(p *Package) (id string, err error) {
  1796  	if buildToolchain != (gcToolchain{}) {
  1797  		return "", errBuildIDToolchain
  1798  	}
  1799  
  1800  	// For commands, read build ID directly from binary.
  1801  	if p.Name == "main" {
  1802  		return ReadBuildIDFromBinary(p.Target)
  1803  	}
  1804  
  1805  	// Otherwise, we expect to have an archive (.a) file,
  1806  	// and we can read the build ID from the Go export data.
  1807  	if !strings.HasSuffix(p.Target, ".a") {
  1808  		return "", &os.PathError{Op: "parse", Path: p.Target, Err: errBuildIDUnknown}
  1809  	}
  1810  
  1811  	// Read just enough of the target to fetch the build ID.
  1812  	// The archive is expected to look like:
  1813  	//
  1814  	//	!<arch>
  1815  	//	__.PKGDEF       0           0     0     644     7955      `
  1816  	//	go object darwin amd64 devel X:none
  1817  	//	build id "b41e5c45250e25c9fd5e9f9a1de7857ea0d41224"
  1818  	//
  1819  	// The variable-sized strings are GOOS, GOARCH, and the experiment list (X:none).
  1820  	// Reading the first 1024 bytes should be plenty.
  1821  	f, err := os.Open(p.Target)
  1822  	if err != nil {
  1823  		return "", err
  1824  	}
  1825  	data := make([]byte, 1024)
  1826  	n, err := io.ReadFull(f, data)
  1827  	f.Close()
  1828  
  1829  	if err != nil && n == 0 {
  1830  		return "", err
  1831  	}
  1832  
  1833  	bad := func() (string, error) {
  1834  		return "", &os.PathError{Op: "parse", Path: p.Target, Err: errBuildIDMalformed}
  1835  	}
  1836  
  1837  	// Archive header.
  1838  	for i := 0; ; i++ { // returns during i==3
  1839  		j := bytes.IndexByte(data, '\n')
  1840  		if j < 0 {
  1841  			return bad()
  1842  		}
  1843  		line := data[:j]
  1844  		data = data[j+1:]
  1845  		switch i {
  1846  		case 0:
  1847  			if !bytes.Equal(line, bangArch) {
  1848  				return bad()
  1849  			}
  1850  		case 1:
  1851  			if !bytes.HasPrefix(line, pkgdef) {
  1852  				return bad()
  1853  			}
  1854  		case 2:
  1855  			if !bytes.HasPrefix(line, goobject) {
  1856  				return bad()
  1857  			}
  1858  		case 3:
  1859  			if !bytes.HasPrefix(line, buildid) {
  1860  				// Found the object header, just doesn't have a build id line.
  1861  				// Treat as successful, with empty build id.
  1862  				return "", nil
  1863  			}
  1864  			id, err := strconv.Unquote(string(line[len(buildid):]))
  1865  			if err != nil {
  1866  				return bad()
  1867  			}
  1868  			return id, nil
  1869  		}
  1870  	}
  1871  }
  1872  
  1873  var (
  1874  	goBuildPrefix = []byte("\xff Go build ID: \"")
  1875  	goBuildEnd    = []byte("\"\n \xff")
  1876  
  1877  	elfPrefix = []byte("\x7fELF")
  1878  
  1879  	machoPrefixes = [][]byte{
  1880  		{0xfe, 0xed, 0xfa, 0xce},
  1881  		{0xfe, 0xed, 0xfa, 0xcf},
  1882  		{0xce, 0xfa, 0xed, 0xfe},
  1883  		{0xcf, 0xfa, 0xed, 0xfe},
  1884  	}
  1885  )
  1886  
  1887  var BuildIDReadSize = 32 * 1024 // changed for testing
  1888  
  1889  // ReadBuildIDFromBinary reads the build ID from a binary.
  1890  //
  1891  // ELF binaries store the build ID in a proper PT_NOTE section.
  1892  //
  1893  // Other binary formats are not so flexible. For those, the linker
  1894  // stores the build ID as non-instruction bytes at the very beginning
  1895  // of the text segment, which should appear near the beginning
  1896  // of the file. This is clumsy but fairly portable. Custom locations
  1897  // can be added for other binary types as needed, like we did for ELF.
  1898  func ReadBuildIDFromBinary(filename string) (id string, err error) {
  1899  	if filename == "" {
  1900  		return "", &os.PathError{Op: "parse", Path: filename, Err: errBuildIDUnknown}
  1901  	}
  1902  
  1903  	// Read the first 32 kB of the binary file.
  1904  	// That should be enough to find the build ID.
  1905  	// In ELF files, the build ID is in the leading headers,
  1906  	// which are typically less than 4 kB, not to mention 32 kB.
  1907  	// In Mach-O files, there's no limit, so we have to parse the file.
  1908  	// On other systems, we're trying to read enough that
  1909  	// we get the beginning of the text segment in the read.
  1910  	// The offset where the text segment begins in a hello
  1911  	// world compiled for each different object format today:
  1912  	//
  1913  	//	Plan 9: 0x20
  1914  	//	Windows: 0x600
  1915  	//
  1916  	f, err := os.Open(filename)
  1917  	if err != nil {
  1918  		return "", err
  1919  	}
  1920  	defer f.Close()
  1921  
  1922  	data := make([]byte, BuildIDReadSize)
  1923  	_, err = io.ReadFull(f, data)
  1924  	if err == io.ErrUnexpectedEOF {
  1925  		err = nil
  1926  	}
  1927  	if err != nil {
  1928  		return "", err
  1929  	}
  1930  
  1931  	if bytes.HasPrefix(data, elfPrefix) {
  1932  		return readELFGoBuildID(filename, f, data)
  1933  	}
  1934  	for _, m := range machoPrefixes {
  1935  		if bytes.HasPrefix(data, m) {
  1936  			return readMachoGoBuildID(filename, f, data)
  1937  		}
  1938  	}
  1939  
  1940  	return readRawGoBuildID(filename, data)
  1941  }
  1942  
  1943  // readRawGoBuildID finds the raw build ID stored in text segment data.
  1944  func readRawGoBuildID(filename string, data []byte) (id string, err error) {
  1945  	i := bytes.Index(data, goBuildPrefix)
  1946  	if i < 0 {
  1947  		// Missing. Treat as successful but build ID empty.
  1948  		return "", nil
  1949  	}
  1950  
  1951  	j := bytes.Index(data[i+len(goBuildPrefix):], goBuildEnd)
  1952  	if j < 0 {
  1953  		return "", &os.PathError{Op: "parse", Path: filename, Err: errBuildIDMalformed}
  1954  	}
  1955  
  1956  	quoted := data[i+len(goBuildPrefix)-1 : i+len(goBuildPrefix)+j+1]
  1957  	id, err = strconv.Unquote(string(quoted))
  1958  	if err != nil {
  1959  		return "", &os.PathError{Op: "parse", Path: filename, Err: errBuildIDMalformed}
  1960  	}
  1961  
  1962  	return id, nil
  1963  }