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.
5 // Package load loads packages.
20 "cmd/go/internal/base"
25 var IgnoreImports bool // control whether we ignore imports in packages
27 // A Package describes a single package found in a directory.
29 PackagePublic // visible in 'go list'
30 Internal PackageInternal // for use inside go command only
33 type PackagePublic struct {
34 // Note: These fields are part of the go command's public API.
35 // See list.go. It is okay to add fields, but not to change or
36 // remove existing ones. Keep in sync with list.go
37 Dir string `json:",omitempty"` // directory containing package sources
38 ImportPath string `json:",omitempty"` // import path of package in dir
39 ImportComment string `json:",omitempty"` // path in import comment on package statement
40 Name string `json:",omitempty"` // package name
41 Doc string `json:",omitempty"` // package documentation string
42 Target string `json:",omitempty"` // installed target for this package (may be executable)
43 Shlib string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
44 Goroot bool `json:",omitempty"` // is this package found in the Go root?
45 Standard bool `json:",omitempty"` // is this package part of the standard Go library?
46 Root string `json:",omitempty"` // Go root or Go path dir containing this package
47 ConflictDir string `json:",omitempty"` // Dir is hidden by this other directory
48 BinaryOnly bool `json:",omitempty"` // package cannot be recompiled
50 // Stale and StaleReason remain here *only* for the list command.
51 // They are only initialized in preparation for list execution.
52 // The regular build determines staleness on the fly during action execution.
53 Stale bool `json:",omitempty"` // would 'go install' do anything for this package?
54 StaleReason string `json:",omitempty"` // why is Stale true?
57 GoFiles []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
58 CgoFiles []string `json:",omitempty"` // .go sources files that import "C"
59 IgnoredGoFiles []string `json:",omitempty"` // .go sources ignored due to build constraints
60 CFiles []string `json:",omitempty"` // .c source files
61 CXXFiles []string `json:",omitempty"` // .cc, .cpp and .cxx source files
62 MFiles []string `json:",omitempty"` // .m source files
63 HFiles []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
64 FFiles []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
65 SFiles []string `json:",omitempty"` // .s source files
66 SwigFiles []string `json:",omitempty"` // .swig files
67 SwigCXXFiles []string `json:",omitempty"` // .swigcxx files
68 SysoFiles []string `json:",omitempty"` // .syso system object files added to package
71 CgoCFLAGS []string `json:",omitempty"` // cgo: flags for C compiler
72 CgoCPPFLAGS []string `json:",omitempty"` // cgo: flags for C preprocessor
73 CgoCXXFLAGS []string `json:",omitempty"` // cgo: flags for C++ compiler
74 CgoFFLAGS []string `json:",omitempty"` // cgo: flags for Fortran compiler
75 CgoLDFLAGS []string `json:",omitempty"` // cgo: flags for linker
76 CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
78 // Dependency information
79 Imports []string `json:",omitempty"` // import paths used by this package
80 Deps []string `json:",omitempty"` // all (recursively) imported dependencies
83 Incomplete bool `json:",omitempty"` // was there an error loading this package or dependencies?
84 Error *PackageError `json:",omitempty"` // error loading this package (not dependencies)
85 DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
88 TestGoFiles []string `json:",omitempty"` // _test.go files in package
89 TestImports []string `json:",omitempty"` // imports from TestGoFiles
90 XTestGoFiles []string `json:",omitempty"` // _test.go files outside package
91 XTestImports []string `json:",omitempty"` // imports from XTestGoFiles
94 type PackageInternal struct {
95 // Unexported fields are not part of the public API.
97 Imports []*Package // this package's direct imports
98 RawImports []string // this package's original imports as they appear in the text of the program
99 ForceLibrary bool // this package is a library (even if named "main")
100 CmdlineFiles bool // package built from files listed on command line
101 CmdlinePkg bool // package listed on command line
102 Local bool // imported via local path (./ or ../)
103 LocalPrefix string // interpret ./ and ../ imports relative to this prefix
104 ExeName string // desired name for temporary executable
105 CoverMode string // preprocess Go source files with the coverage tool in this mode
106 CoverVars map[string]*CoverVar // variables created by coverage analysis
107 OmitDebug bool // tell linker not to write debug information
108 GobinSubdir bool // install target would be subdir of GOBIN
110 Asmflags []string // -asmflags for this package
111 Gcflags []string // -gcflags for this package
112 Ldflags []string // -ldflags for this package
113 Gccgoflags []string // -gccgoflags for this package
116 type NoGoError struct {
120 func (e *NoGoError) Error() string {
121 // Count files beginning with _ and ., which we will pretend don't exist at all.
123 for _, name := range e.Package.IgnoredGoFiles {
124 if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
129 if len(e.Package.IgnoredGoFiles) > dummy {
130 // Go files exist, but they were ignored due to build constraints.
131 return "build constraints exclude all Go files in " + e.Package.Dir
133 if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
134 // Test Go files exist, but we're not interested in them.
135 // The double-negative is unfortunate but we want e.Package.Dir
136 // to appear at the end of error message.
137 return "no non-test Go files in " + e.Package.Dir
139 return "no Go files in " + e.Package.Dir
142 // Vendored returns the vendor-resolved version of imports,
143 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
144 // The imports in p.TestImports and p.XTestImports are not recursively
145 // loaded during the initial load of p, so they list the imports found in
146 // the source file, but most processing should be over the vendor-resolved
147 // import paths. We do this resolution lazily both to avoid file system work
148 // and because the eventual real load of the test imports (during 'go test')
149 // can produce better error messages if it starts with the original paths.
150 // The initial load of p loads all the non-test imports and rewrites
151 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
152 func (p *Package) Vendored(imports []string) []string {
153 if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
154 panic("internal error: p.vendored(p.Imports) called")
156 seen := make(map[string]bool)
158 for _, path := range imports {
159 path = VendoredImportPath(p, path)
162 all = append(all, path)
169 // CoverVar holds the name of the generated coverage variables targeting the named file.
170 type CoverVar struct {
171 File string // local file name
172 Var string // name of count struct
175 func (p *Package) copyBuild(pp *build.Package) {
176 p.Internal.Build = pp
178 if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
179 old := pp.PkgTargetRoot
180 pp.PkgRoot = cfg.BuildPkgdir
181 pp.PkgTargetRoot = cfg.BuildPkgdir
182 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
186 p.ImportPath = pp.ImportPath
187 p.ImportComment = pp.ImportComment
191 p.ConflictDir = pp.ConflictDir
192 p.BinaryOnly = pp.BinaryOnly
196 p.Standard = p.Goroot && p.ImportPath != "" && isStandardImportPath(p.ImportPath)
197 p.GoFiles = pp.GoFiles
198 p.CgoFiles = pp.CgoFiles
199 p.IgnoredGoFiles = pp.IgnoredGoFiles
201 p.CXXFiles = pp.CXXFiles
206 p.SwigFiles = pp.SwigFiles
207 p.SwigCXXFiles = pp.SwigCXXFiles
208 p.SysoFiles = pp.SysoFiles
210 // There's no way for .syso files to be built both with and without
211 // support for memory sanitizer. Assume they are built without,
215 p.CgoCFLAGS = pp.CgoCFLAGS
216 p.CgoCPPFLAGS = pp.CgoCPPFLAGS
217 p.CgoCXXFLAGS = pp.CgoCXXFLAGS
218 p.CgoFFLAGS = pp.CgoFFLAGS
219 p.CgoLDFLAGS = pp.CgoLDFLAGS
220 p.CgoPkgConfig = pp.CgoPkgConfig
221 // We modify p.Imports in place, so make copy now.
222 p.Imports = make([]string, len(pp.Imports))
223 copy(p.Imports, pp.Imports)
224 p.Internal.RawImports = pp.Imports
225 p.TestGoFiles = pp.TestGoFiles
226 p.TestImports = pp.TestImports
227 p.XTestGoFiles = pp.XTestGoFiles
228 p.XTestImports = pp.XTestImports
236 // isStandardImportPath reports whether $GOROOT/src/path should be considered
237 // part of the standard distribution. For historical reasons we allow people to add
238 // their own code to $GOROOT instead of using $GOPATH, but we assume that
239 // code will start with a domain name (dot in the first element).
240 func isStandardImportPath(path string) bool {
241 i := strings.Index(path, "/")
246 return !strings.Contains(elem, ".")
249 // A PackageError describes an error loading information about a package.
250 type PackageError struct {
251 ImportStack []string // shortest path from package named on command line to this one
252 Pos string // position of error
253 Err string // the error itself
254 IsImportCycle bool `json:"-"` // the error is an import cycle
255 Hard bool `json:"-"` // whether the error is soft or hard; soft errors are ignored in some places
258 func (p *PackageError) Error() string {
259 // Import cycles deserve special treatment.
261 return fmt.Sprintf("%s\npackage %s\n", p.Err, strings.Join(p.ImportStack, "\n\timports "))
264 // Omit import stack. The full path to the file where the error
265 // is the most important thing.
266 return p.Pos + ": " + p.Err
268 if len(p.ImportStack) == 0 {
271 return "package " + strings.Join(p.ImportStack, "\n\timports ") + ": " + p.Err
274 // An ImportStack is a stack of import paths.
275 type ImportStack []string
277 func (s *ImportStack) Push(p string) {
281 func (s *ImportStack) Pop() {
282 *s = (*s)[0 : len(*s)-1]
285 func (s *ImportStack) Copy() []string {
286 return append([]string{}, *s...)
289 // shorterThan reports whether sp is shorter than t.
290 // We use this to record the shortest import sequence
291 // that leads to a particular package.
292 func (sp *ImportStack) shorterThan(t []string) bool {
294 if len(s) != len(t) {
295 return len(s) < len(t)
297 // If they are the same length, settle ties using string ordering.
303 return false // they are equal
306 // packageCache is a lookup cache for loadPackage,
307 // so that if we look up a package multiple times
308 // we return the same pointer each time.
309 var packageCache = map[string]*Package{}
311 func ClearPackageCache() {
312 for name := range packageCache {
313 delete(packageCache, name)
317 func ClearPackageCachePartial(args []string) {
318 for _, arg := range args {
319 p := packageCache[arg]
321 delete(packageCache, p.Dir)
322 delete(packageCache, p.ImportPath)
327 // reloadPackage is like loadPackage but makes sure
328 // not to use the package cache.
329 func ReloadPackage(arg string, stk *ImportStack) *Package {
330 p := packageCache[arg]
332 delete(packageCache, p.Dir)
333 delete(packageCache, p.ImportPath)
335 return LoadPackage(arg, stk)
338 // dirToImportPath returns the pseudo-import path we use for a package
339 // outside the Go path. It begins with _/ and then contains the full path
340 // to the directory. If the package lives in c:\home\gopher\my\pkg then
341 // the pseudo-import path is _/c_/home/gopher/my/pkg.
342 // Using a pseudo-import path like this makes the ./ imports no longer
343 // a special case, so that all the code to deal with ordinary imports works
345 func dirToImportPath(dir string) string {
346 return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
349 func makeImportValid(r rune) rune {
350 // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
351 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
352 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
358 // Mode flags for loadImport and download (in get.go).
360 // UseVendor means that loadImport should do vendor expansion
361 // (provided the vendoring experiment is enabled).
362 // That is, useVendor means that the import path came from
363 // a source file and has not been vendor-expanded yet.
364 // Every import path should be loaded initially with useVendor,
365 // and then the expanded version (with the /vendor/ in it) gets
366 // recorded as the canonical import path. At that point, future loads
367 // of that package must not pass useVendor, because
368 // disallowVendor will reject direct use of paths containing /vendor/.
369 UseVendor = 1 << iota
371 // GetTestDeps is for download (part of "go get") and indicates
372 // that test dependencies should be fetched too.
376 // LoadImport scans the directory named by path, which must be an import path,
377 // but possibly a local import path (an absolute file system path or one beginning
378 // with ./ or ../). A local relative path is interpreted relative to srcDir.
379 // It returns a *Package describing the package found in that directory.
380 func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
384 // Determine canonical identifier for this package.
385 // For a local import the identifier is the pseudo-import path
386 // we create from the full directory to the package.
387 // Otherwise it is the usual import path.
388 // For vendored imports, it is the expanded form.
391 isLocal := build.IsLocalImport(path)
392 var debugDeprecatedImportcfgDir string
394 importPath = dirToImportPath(filepath.Join(srcDir, path))
395 } else if DebugDeprecatedImportcfg.enabled {
396 if d, i := DebugDeprecatedImportcfg.lookup(parent, path); d != "" {
397 debugDeprecatedImportcfgDir = d
400 } else if mode&UseVendor != 0 {
401 // We do our own vendor resolution, because we want to
402 // find out the key to use in packageCache without the
403 // overhead of repeated calls to buildContext.Import.
404 // The code is also needed in a few other places anyway.
405 path = VendoredImportPath(parent, path)
409 p := packageCache[importPath]
411 p = reusePackage(p, stk)
414 p.Internal.Local = isLocal
415 p.ImportPath = importPath
416 packageCache[importPath] = p
419 // Import always returns bp != nil, even if an error occurs,
420 // in order to return partial information.
421 var bp *build.Package
423 if debugDeprecatedImportcfgDir != "" {
424 bp, err = cfg.BuildContext.ImportDir(debugDeprecatedImportcfgDir, 0)
426 buildMode := build.ImportComment
427 if mode&UseVendor == 0 || path != origPath {
428 // Not vendoring, or we already found the vendored path.
429 buildMode |= build.IgnoreVendor
431 bp, err = cfg.BuildContext.Import(path, srcDir, buildMode)
433 bp.ImportPath = importPath
435 bp.BinDir = cfg.GOBIN
437 if debugDeprecatedImportcfgDir == "" && err == nil && !isLocal && bp.ImportComment != "" && bp.ImportComment != path &&
438 !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
439 err = fmt.Errorf("code in directory %s expects import %q", bp.Dir, bp.ImportComment)
442 if p.Error != nil && p.Error.Pos == "" {
443 p = setErrorPos(p, importPos)
446 if debugDeprecatedImportcfgDir == "" && origPath != cleanImport(origPath) {
447 p.Error = &PackageError{
448 ImportStack: stk.Copy(),
449 Err: fmt.Sprintf("non-canonical import path: %q should be %q", origPath, pathpkg.Clean(origPath)),
455 // Checked on every import because the rules depend on the code doing the importing.
456 if perr := disallowInternal(srcDir, p, stk); perr != p {
457 return setErrorPos(perr, importPos)
459 if mode&UseVendor != 0 {
460 if perr := disallowVendor(srcDir, origPath, p, stk); perr != p {
461 return setErrorPos(perr, importPos)
465 if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
467 perr.Error = &PackageError{
468 ImportStack: stk.Copy(),
469 Err: fmt.Sprintf("import %q is a program, not an importable package", path),
471 return setErrorPos(&perr, importPos)
474 if p.Internal.Local && parent != nil && !parent.Internal.Local {
476 perr.Error = &PackageError{
477 ImportStack: stk.Copy(),
478 Err: fmt.Sprintf("local import %q in non-local package", path),
480 return setErrorPos(&perr, importPos)
486 func setErrorPos(p *Package, importPos []token.Position) *Package {
487 if len(importPos) > 0 {
489 pos.Filename = base.ShortPath(pos.Filename)
490 p.Error.Pos = pos.String()
495 func cleanImport(path string) string {
497 path = pathpkg.Clean(path)
498 if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
504 var isDirCache = map[string]bool{}
506 func isDir(path string) bool {
507 result, ok := isDirCache[path]
512 fi, err := os.Stat(path)
513 result = err == nil && fi.IsDir()
514 isDirCache[path] = result
518 // VendoredImportPath returns the expansion of path when it appears in parent.
519 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
520 // x/vendor/path, vendor/path, or else stay path if none of those exist.
521 // VendoredImportPath returns the expanded path or, if no expansion is found, the original.
522 func VendoredImportPath(parent *Package, path string) (found string) {
523 if parent == nil || parent.Root == "" {
527 dir := filepath.Clean(parent.Dir)
528 root := filepath.Join(parent.Root, "src")
529 if !hasFilePathPrefix(dir, root) || parent.ImportPath != "command-line-arguments" && filepath.Join(root, parent.ImportPath) != dir {
530 // Look for symlinks before reporting error.
531 dir = expandPath(dir)
532 root = expandPath(root)
535 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 {
536 base.Fatalf("unexpected directory layout:\n"+
537 " import path: %s\n"+
540 " expand root: %s\n"+
544 filepath.Join(parent.Root, "src"),
545 filepath.Clean(parent.Dir),
548 string(filepath.Separator))
551 vpath := "vendor/" + path
552 for i := len(dir); i >= len(root); i-- {
553 if i < len(dir) && dir[i] != filepath.Separator {
556 // Note: checking for the vendor directory before checking
557 // for the vendor/path directory helps us hit the
558 // isDir cache more often. It also helps us prepare a more useful
559 // list of places we looked, to report when an import is not found.
560 if !isDir(filepath.Join(dir[:i], "vendor")) {
563 targ := filepath.Join(dir[:i], vpath)
564 if isDir(targ) && hasGoFiles(targ) {
565 importPath := parent.ImportPath
566 if importPath == "command-line-arguments" {
567 // If parent.ImportPath is 'command-line-arguments'.
568 // set to relative directory to root (also chopped root directory)
569 importPath = dir[len(root)+1:]
571 // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
572 // We know the import path for parent's dir.
573 // We chopped off some number of path elements and
574 // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
575 // Now we want to know the import path for that directory.
576 // Construct it by chopping the same number of path elements
577 // (actually the same number of bytes) from parent's import path
578 // and then append /vendor/path.
579 chopped := len(dir) - i
580 if chopped == len(importPath)+1 {
581 // We walked up from c:\gopath\src\foo\bar
582 // and found c:\gopath\src\vendor\path.
583 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
584 // Use "vendor/path" without any prefix.
587 return importPath[:len(importPath)-chopped] + "/" + vpath
593 // hasGoFiles reports whether dir contains any files with names ending in .go.
594 // For a vendor check we must exclude directories that contain no .go files.
595 // Otherwise it is not possible to vendor just a/b/c and still import the
596 // non-vendored a/b. See golang.org/issue/13832.
597 func hasGoFiles(dir string) bool {
598 fis, _ := ioutil.ReadDir(dir)
599 for _, fi := range fis {
600 if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
607 // reusePackage reuses package p to satisfy the import at the top
608 // of the import stack stk. If this use causes an import loop,
609 // reusePackage updates p's error information to record the loop.
610 func reusePackage(p *Package, stk *ImportStack) *Package {
611 // We use p.Internal.Imports==nil to detect a package that
612 // is in the midst of its own loadPackage call
613 // (all the recursion below happens before p.Internal.Imports gets set).
614 if p.Internal.Imports == nil {
616 p.Error = &PackageError{
617 ImportStack: stk.Copy(),
618 Err: "import cycle not allowed",
624 // Don't rewrite the import stack in the error if we have an import cycle.
625 // If we do, we'll lose the path that describes the cycle.
626 if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
627 p.Error.ImportStack = stk.Copy()
632 // disallowInternal checks that srcDir is allowed to import p.
633 // If the import is allowed, disallowInternal returns the original package p.
634 // If not, it returns a new package containing just an appropriate error.
635 func disallowInternal(srcDir string, p *Package, stk *ImportStack) *Package {
636 // golang.org/s/go14internal:
637 // An import of a path containing the element “internal”
638 // is disallowed if the importing code is outside the tree
639 // rooted at the parent of the “internal” directory.
641 // There was an error loading the package; stop here.
646 // The generated 'testmain' package is allowed to access testing/internal/...,
647 // as if it were generated into the testing directory tree
648 // (it's actually in a temporary directory outside any Go tree).
649 // This cleans up a former kludge in passing functionality to the testing package.
650 if strings.HasPrefix(p.ImportPath, "testing/internal") && len(*stk) >= 2 && (*stk)[len(*stk)-2] == "testmain" {
654 // We can't check standard packages with gccgo.
655 if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
659 // The stack includes p.ImportPath.
660 // If that's the only thing on the stack, we started
661 // with a name given on the command line, not an
662 // import. Anything listed on the command line is fine.
667 // Check for "internal" element: three cases depending on begin of string and/or end of string.
668 i, ok := findInternal(p.ImportPath)
673 // Internal is present.
674 // Map import path back to directory corresponding to parent of internal.
676 i-- // rewind over slash in ".../internal"
678 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
679 if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
683 // Look for symlinks before reporting error.
684 srcDir = expandPath(srcDir)
685 parent = expandPath(parent)
686 if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
690 // Internal is present, and srcDir is outside parent's tree. Not allowed.
692 perr.Error = &PackageError{
693 ImportStack: stk.Copy(),
694 Err: "use of internal package not allowed",
696 perr.Incomplete = true
700 // findInternal looks for the final "internal" path element in the given import path.
701 // If there isn't one, findInternal returns ok=false.
702 // Otherwise, findInternal returns ok=true and the index of the "internal".
703 func findInternal(path string) (index int, ok bool) {
704 // Three cases, depending on internal at start/end of string or not.
705 // The order matters: we must return the index of the final element,
706 // because the final one produces the most restrictive requirement
709 case strings.HasSuffix(path, "/internal"):
710 return len(path) - len("internal"), true
711 case strings.Contains(path, "/internal/"):
712 return strings.LastIndex(path, "/internal/") + 1, true
713 case path == "internal", strings.HasPrefix(path, "internal/"):
719 // disallowVendor checks that srcDir is allowed to import p as path.
720 // If the import is allowed, disallowVendor returns the original package p.
721 // If not, it returns a new package containing just an appropriate error.
722 func disallowVendor(srcDir, path string, p *Package, stk *ImportStack) *Package {
723 // The stack includes p.ImportPath.
724 // If that's the only thing on the stack, we started
725 // with a name given on the command line, not an
726 // import. Anything listed on the command line is fine.
731 if perr := disallowVendorVisibility(srcDir, p, stk); perr != p {
735 // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
736 if i, ok := FindVendor(path); ok {
738 perr.Error = &PackageError{
739 ImportStack: stk.Copy(),
740 Err: "must be imported as " + path[i+len("vendor/"):],
742 perr.Incomplete = true
749 // disallowVendorVisibility checks that srcDir is allowed to import p.
750 // The rules are the same as for /internal/ except that a path ending in /vendor
751 // is not subject to the rules, only subdirectories of vendor.
752 // This allows people to have packages and commands named vendor,
753 // for maximal compatibility with existing source trees.
754 func disallowVendorVisibility(srcDir string, p *Package, stk *ImportStack) *Package {
755 // The stack includes p.ImportPath.
756 // If that's the only thing on the stack, we started
757 // with a name given on the command line, not an
758 // import. Anything listed on the command line is fine.
763 // Check for "vendor" element.
764 i, ok := FindVendor(p.ImportPath)
769 // Vendor is present.
770 // Map import path back to directory corresponding to parent of vendor.
772 i-- // rewind over slash in ".../vendor"
774 truncateTo := i + len(p.Dir) - len(p.ImportPath)
775 if truncateTo < 0 || len(p.Dir) < truncateTo {
778 parent := p.Dir[:truncateTo]
779 if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
783 // Look for symlinks before reporting error.
784 srcDir = expandPath(srcDir)
785 parent = expandPath(parent)
786 if hasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
790 // Vendor is present, and srcDir is outside parent's tree. Not allowed.
792 perr.Error = &PackageError{
793 ImportStack: stk.Copy(),
794 Err: "use of vendored package not allowed",
796 perr.Incomplete = true
800 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
801 // If there isn't one, FindVendor returns ok=false.
802 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
804 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
805 // not the vendored copy of an import "" (the empty import path).
806 // This will allow people to have packages or commands named vendor.
807 // This may help reduce breakage, or it may just be confusing. We'll see.
808 func FindVendor(path string) (index int, ok bool) {
809 // Two cases, depending on internal at start of string or not.
810 // The order matters: we must return the index of the final element,
811 // because the final one is where the effective import path starts.
813 case strings.Contains(path, "/vendor/"):
814 return strings.LastIndex(path, "/vendor/") + 1, true
815 case strings.HasPrefix(path, "vendor/"):
824 ToTool TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
825 ToBin // to bin dir inside package root (default for non-cmd/*)
826 StalePath // an old import path; fail to build
829 // InstallTargetDir reports the target directory for installing the command p.
830 func InstallTargetDir(p *Package) TargetDir {
831 if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
834 if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
835 switch p.ImportPath {
836 case "cmd/go", "cmd/gofmt":
844 var cgoExclude = map[string]bool{
848 var cgoSyscallExclude = map[string]bool{
850 "runtime/race": true,
851 "runtime/msan": true,
854 var foldPath = make(map[string]string)
856 // load populates p using information from bp, err, which should
857 // be the result of calling build.Context.Import.
858 func (p *Package) load(stk *ImportStack, bp *build.Package, err error) {
861 // Decide whether p was listed on the command line.
862 // Given that load is called while processing the command line,
863 // you might think we could simply pass a flag down into load
864 // saying whether we are loading something named on the command
865 // line or something to satisfy an import. But the first load of a
866 // package named on the command line may be as a dependency
867 // of an earlier package named on the command line, not when we
868 // get to that package during command line processing.
869 // For example "go test fmt reflect" will load reflect as a dependency
870 // of fmt before it attempts to load as a command-line argument.
871 // Because loads are cached, the later load will be a no-op,
872 // so it is important that the first load can fill in CmdlinePkg correctly.
873 // Hence the call to an explicit matching check here.
874 p.Internal.CmdlinePkg = isCmdlinePkg(p)
876 p.Internal.Asmflags = BuildAsmflags.For(p)
877 p.Internal.Gcflags = BuildGcflags.For(p)
878 p.Internal.Ldflags = BuildLdflags.For(p)
879 p.Internal.Gccgoflags = BuildGccgoflags.For(p)
881 // The localPrefix is the path we interpret ./ imports relative to.
882 // Synthesized main packages sometimes override this.
883 if p.Internal.Local {
884 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
888 if _, ok := err.(*build.NoGoError); ok {
889 err = &NoGoError{Package: p}
892 err = base.ExpandScanner(err)
893 p.Error = &PackageError{
894 ImportStack: stk.Copy(),
900 useBindir := p.Name == "main"
902 switch cfg.BuildBuildmode {
903 case "c-archive", "c-shared", "plugin":
909 // Report an error when the old code.google.com/p/go.tools paths are used.
910 if InstallTargetDir(p) == StalePath {
911 newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
912 e := fmt.Sprintf("the %v command has moved; use %v instead.", p.ImportPath, newPath)
913 p.Error = &PackageError{Err: e}
916 _, elem := filepath.Split(p.Dir)
917 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
918 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
919 // Install cross-compiled binaries to subdirectories of bin.
922 if p.Internal.Build.BinDir != "" {
923 // Install to GOBIN or bin of GOPATH entry.
924 p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
925 if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
926 // Do not create $GOBIN/goos_goarch/elem.
928 p.Internal.GobinSubdir = true
931 if InstallTargetDir(p) == ToTool {
932 // This is for 'go tool'.
933 // Override all the usual logic and force it into the tool directory.
934 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
936 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
939 } else if p.Internal.Local {
940 // Local import turned into absolute path.
941 // No permanent install target.
944 p.Target = p.Internal.Build.PkgObj
945 if cfg.BuildLinkshared {
946 shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
947 shlib, err := ioutil.ReadFile(shlibnamefile)
948 if err != nil && !os.IsNotExist(err) {
949 base.Fatalf("reading shlibname: %v", err)
952 libname := strings.TrimSpace(string(shlib))
953 if cfg.BuildContext.Compiler == "gccgo" {
954 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
956 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
962 // Build augmented import list to add implicit dependencies.
963 // Be careful not to add imports twice, just to avoid confusion.
964 importPaths := p.Imports
965 addImport := func(path string) {
966 for _, p := range importPaths {
971 importPaths = append(importPaths, path)
974 // Cgo translation adds imports of "runtime/cgo" and "syscall",
975 // except for certain packages, to avoid circular dependencies.
976 if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) {
977 addImport("runtime/cgo")
979 if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
983 // SWIG adds imports of some standard packages.
985 addImport("runtime/cgo")
989 // TODO: The .swig and .swigcxx files can use
990 // %go_import directives to import other packages.
993 // The linker loads implicit dependencies.
994 if p.Name == "main" && !p.Internal.ForceLibrary {
995 for _, dep := range LinkerDeps(p) {
1000 // Check for case-insensitive collision of input files.
1001 // To avoid problems on case-insensitive files, we reject any package
1002 // where two different input files have equal names under a case-insensitive
1004 f1, f2 := str.FoldDup(str.StringList(
1021 p.Error = &PackageError{
1022 ImportStack: stk.Copy(),
1023 Err: fmt.Sprintf("case-insensitive file name collision: %q and %q", f1, f2),
1028 // Build list of imported packages and full dependency list.
1029 imports := make([]*Package, 0, len(p.Imports))
1030 for i, path := range importPaths {
1034 p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], UseVendor)
1035 if p.Standard && p.Error == nil && !p1.Standard && p1.Error == nil {
1036 p.Error = &PackageError{
1037 ImportStack: stk.Copy(),
1038 Err: fmt.Sprintf("non-standard import %q in standard package %q", path, p.ImportPath),
1040 pos := p.Internal.Build.ImportPos[path]
1042 p.Error.Pos = pos[0].String()
1046 path = p1.ImportPath
1047 importPaths[i] = path
1048 if i < len(p.Imports) {
1052 imports = append(imports, p1)
1057 p.Internal.Imports = imports
1059 deps := make(map[string]*Package)
1061 q = append(q, imports...)
1062 for i := 0; i < len(q); i++ {
1064 path := p1.ImportPath
1065 // The same import path could produce an error or not,
1066 // depending on what tries to import it.
1067 // Prefer to record entries with errors, so we can report them.
1069 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
1071 for _, p2 := range p1.Internal.Imports {
1072 if deps[p2.ImportPath] != p2 {
1079 p.Deps = make([]string, 0, len(deps))
1080 for dep := range deps {
1081 p.Deps = append(p.Deps, dep)
1083 sort.Strings(p.Deps)
1084 for _, dep := range p.Deps {
1087 panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
1089 if p1.Error != nil {
1090 p.DepsErrors = append(p.DepsErrors, p1.Error)
1094 // unsafe is a fake package.
1095 if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1099 // If cgo is not enabled, ignore cgo supporting sources
1100 // just as we ignore go files containing import "C".
1101 if !cfg.BuildContext.CgoEnabled {
1106 p.SwigCXXFiles = nil
1107 // Note that SFiles are okay (they go to the Go assembler)
1108 // and HFiles are okay (they might be used by the SFiles).
1109 // Also Sysofiles are okay (they might not contain object
1110 // code; see issue #16050).
1113 setError := func(msg string) {
1114 p.Error = &PackageError{
1115 ImportStack: stk.Copy(),
1120 // The gc toolchain only permits C source files with cgo or SWIG.
1121 if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1122 setError(fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1126 // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1127 // regardless of toolchain.
1128 if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1129 setError(fmt.Sprintf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1132 if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1133 setError(fmt.Sprintf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1136 if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1137 setError(fmt.Sprintf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1141 // Check for case-insensitive collisions of import paths.
1142 fold := str.ToFold(p.ImportPath)
1143 if other := foldPath[fold]; other == "" {
1144 foldPath[fold] = p.ImportPath
1145 } else if other != p.ImportPath {
1146 setError(fmt.Sprintf("case-insensitive import collision: %q and %q", p.ImportPath, other))
1151 // LinkerDeps returns the list of linker-induced dependencies for main package p.
1152 func LinkerDeps(p *Package) []string {
1153 // Everything links runtime.
1154 deps := []string{"runtime"}
1156 // External linking mode forces an import of runtime/cgo.
1157 if externalLinkingForced(p) {
1158 deps = append(deps, "runtime/cgo")
1160 // On ARM with GOARM=5, it forces an import of math, for soft floating point.
1161 if cfg.Goarch == "arm" {
1162 deps = append(deps, "math")
1164 // Using the race detector forces an import of runtime/race.
1166 deps = append(deps, "runtime/race")
1168 // Using memory sanitizer forces an import of runtime/msan.
1170 deps = append(deps, "runtime/msan")
1176 // externalLinkingForced reports whether external linking is being
1177 // forced even for programs that do not use cgo.
1178 func externalLinkingForced(p *Package) bool {
1179 // Some targets must use external linking even inside GOROOT.
1180 switch cfg.BuildContext.GOOS {
1184 switch cfg.BuildContext.GOARCH {
1185 case "arm", "arm64":
1190 if !cfg.BuildContext.CgoEnabled {
1193 // Currently build modes c-shared, pie (on systems that do not
1194 // support PIE with internal linking mode (currently all
1195 // systems: issue #18968)), plugin, and -linkshared force
1196 // external linking mode, as of course does
1197 // -ldflags=-linkmode=external. External linking mode forces
1198 // an import of runtime/cgo.
1199 pieCgo := cfg.BuildBuildmode == "pie"
1200 linkmodeExternal := false
1202 ldflags := BuildLdflags.For(p)
1203 for i, a := range ldflags {
1204 if a == "-linkmode=external" {
1205 linkmodeExternal = true
1207 if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
1208 linkmodeExternal = true
1213 return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
1216 // mkAbs rewrites list, which must be paths relative to p.Dir,
1217 // into a sorted list of absolute paths. It edits list in place but for
1218 // convenience also returns list back to its caller.
1219 func (p *Package) mkAbs(list []string) []string {
1220 for i, f := range list {
1221 list[i] = filepath.Join(p.Dir, f)
1227 // InternalGoFiles returns the list of Go files being built for the package,
1228 // using absolute paths.
1229 func (p *Package) InternalGoFiles() []string {
1230 return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
1233 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
1234 // using absolute paths. "Possibly relevant" means that files are not excluded
1235 // due to build tags, but files with names beginning with . or _ are still excluded.
1236 func (p *Package) InternalAllGoFiles() []string {
1238 for _, f := range p.IgnoredGoFiles {
1239 if f != "" && f[0] != '.' || f[0] != '_' {
1240 extra = append(extra, f)
1243 return p.mkAbs(str.StringList(extra, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
1246 // usesSwig reports whether the package needs to run SWIG.
1247 func (p *Package) UsesSwig() bool {
1248 return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
1251 // usesCgo reports whether the package needs to run cgo
1252 func (p *Package) UsesCgo() bool {
1253 return len(p.CgoFiles) > 0
1256 // packageList returns the list of packages in the dag rooted at roots
1257 // as visited in a depth-first post-order traversal.
1258 func PackageList(roots []*Package) []*Package {
1259 seen := map[*Package]bool{}
1261 var walk func(*Package)
1262 walk = func(p *Package) {
1267 for _, p1 := range p.Internal.Imports {
1270 all = append(all, p)
1272 for _, root := range roots {
1278 var cmdCache = map[string]*Package{}
1280 func ClearCmdCache() {
1281 for name := range cmdCache {
1282 delete(cmdCache, name)
1286 // loadPackage is like loadImport but is used for command-line arguments,
1287 // not for paths found in import statements. In addition to ordinary import paths,
1288 // loadPackage accepts pseudo-paths beginning with cmd/ to denote commands
1289 // in the Go command directory, as well as paths to those directories.
1290 func LoadPackage(arg string, stk *ImportStack) *Package {
1291 if build.IsLocalImport(arg) {
1293 if !filepath.IsAbs(dir) {
1294 if abs, err := filepath.Abs(dir); err == nil {
1295 // interpret relative to current directory
1299 if sub, ok := hasSubdir(cfg.GOROOTsrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") {
1303 if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") {
1304 if p := cmdCache[arg]; p != nil {
1310 bp, err := cfg.BuildContext.ImportDir(filepath.Join(cfg.GOROOTsrc, arg), 0)
1313 bp.BinDir = cfg.GOROOTbin
1314 if cfg.GOROOTbin != "" {
1315 bp.BinDir = cfg.GOROOTbin
1317 bp.Root = cfg.GOROOT
1318 bp.SrcRoot = cfg.GOROOTsrc
1321 p.load(stk, bp, err)
1322 if p.Error == nil && p.Name != "main" {
1323 p.Error = &PackageError{
1324 ImportStack: stk.Copy(),
1325 Err: fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir),
1331 // Wasn't a command; must be a package.
1332 // If it is a local import path but names a standard package,
1333 // we treat it as if the user specified the standard package.
1334 // This lets you run go test ./ioutil in package io and be
1335 // referring to io/ioutil rather than a hypothetical import of
1337 if build.IsLocalImport(arg) {
1338 bp, _ := cfg.BuildContext.ImportDir(filepath.Join(base.Cwd, arg), build.FindOnly)
1339 if bp.ImportPath != "" && bp.ImportPath != "." {
1344 return LoadImport(arg, base.Cwd, nil, stk, nil, 0)
1347 // packages returns the packages named by the
1348 // command line arguments 'args'. If a named package
1349 // cannot be loaded at all (for example, if the directory does not exist),
1350 // then packages prints an error and does not include that
1351 // package in the results. However, if errors occur trying
1352 // to load dependencies of a named package, the named
1353 // package is still returned, with p.Incomplete = true
1354 // and details in p.DepsErrors.
1355 func Packages(args []string) []*Package {
1357 for _, pkg := range PackagesAndErrors(args) {
1358 if pkg.Error != nil {
1359 base.Errorf("can't load package: %s", pkg.Error)
1362 pkgs = append(pkgs, pkg)
1367 // packagesAndErrors is like 'packages' but returns a
1368 // *Package for every argument, even the ones that
1369 // cannot be loaded at all.
1370 // The packages that fail to load will have p.Error != nil.
1371 func PackagesAndErrors(args []string) []*Package {
1372 if len(args) > 0 && strings.HasSuffix(args[0], ".go") {
1373 return []*Package{GoFilesPackage(args)}
1376 args = ImportPaths(args)
1380 seenArg = make(map[string]bool)
1381 seenPkg = make(map[*Package]bool)
1384 for _, arg := range args {
1389 pkg := LoadPackage(arg, &stk)
1394 pkgs = append(pkgs, pkg)
1400 // packagesForBuild is like 'packages' but fails if any of
1401 // the packages or their dependencies have errors
1402 // (cannot be built).
1403 func PackagesForBuild(args []string) []*Package {
1404 pkgs := PackagesAndErrors(args)
1405 printed := map[*PackageError]bool{}
1406 for _, pkg := range pkgs {
1407 if pkg.Error != nil {
1408 base.Errorf("can't load package: %s", pkg.Error)
1410 for _, err := range pkg.DepsErrors {
1411 // Since these are errors in dependencies,
1412 // the same error might show up multiple times,
1413 // once in each package that depends on it.
1414 // Only print each once.
1417 base.Errorf("%s", err)
1423 // Check for duplicate loads of the same package.
1424 // That should be impossible, but if it does happen then
1425 // we end up trying to build the same package twice,
1426 // usually in parallel overwriting the same files,
1427 // which doesn't work very well.
1428 seen := map[string]bool{}
1429 reported := map[string]bool{}
1430 for _, pkg := range PackageList(pkgs) {
1431 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
1432 reported[pkg.ImportPath] = true
1433 base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
1435 seen[pkg.ImportPath] = true
1442 // GoFilesPackage creates a package for building a collection of Go files
1443 // (typically named on the command line). The target is named p.a for
1444 // package p or named after the first Go file for package main.
1445 func GoFilesPackage(gofiles []string) *Package {
1446 // TODO: Remove this restriction.
1447 for _, f := range gofiles {
1448 if !strings.HasSuffix(f, ".go") {
1449 base.Fatalf("named files must be .go files")
1454 ctxt := cfg.BuildContext
1455 ctxt.UseAllFiles = true
1457 // Synthesize fake "directory" that only shows the named files,
1458 // to make it look like this is a standard package or
1459 // command directory. So that local imports resolve
1460 // consistently, the files must all be in the same directory.
1461 var dirent []os.FileInfo
1463 for _, file := range gofiles {
1464 fi, err := os.Stat(file)
1466 base.Fatalf("%s", err)
1469 base.Fatalf("%s is a directory, should be a Go file", file)
1471 dir1, _ := filepath.Split(file)
1477 } else if dir != dir1 {
1478 base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
1480 dirent = append(dirent, fi)
1482 ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
1488 dir, err = filepath.Abs(dir)
1490 base.Fatalf("%s", err)
1493 bp, err := ctxt.ImportDir(dir, 0)
1495 pkg.Internal.Local = true
1496 pkg.Internal.CmdlineFiles = true
1498 pkg.load(&stk, bp, err)
1500 pkg.Internal.LocalPrefix = dirToImportPath(dir)
1501 pkg.ImportPath = "command-line-arguments"
1504 if pkg.Name == "main" {
1505 _, elem := filepath.Split(gofiles[0])
1506 exe := elem[:len(elem)-len(".go")] + cfg.ExeSuffix
1507 if cfg.BuildO == "" {
1510 if cfg.GOBIN != "" {
1511 pkg.Target = filepath.Join(cfg.GOBIN, exe)