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