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