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.
23 "cmd/go/internal/base"
25 "cmd/go/internal/modinfo"
26 "cmd/go/internal/search"
31 // module initialization hook; never nil, no-op if module use is disabled
34 // module hooks; nil if module use is disabled
35 ModBinDir func() string // return effective bin directory
36 ModLookup func(path string) (dir, realPath string, err error) // lookup effective meaning of import
37 ModPackageModuleInfo func(path string) *modinfo.ModulePublic // return module info for Package struct
38 ModImportPaths func(args []string) []*search.Match // expand import paths
39 ModPackageBuildInfo func(main string, deps []string) string // return module info to embed in binary
40 ModInfoProg func(info string) []byte // wrap module info in .go code for binary
41 ModImportFromFiles func([]string) // update go.mod to add modules for imports in these files
42 ModDirImportPath func(string) string // return effective import path for directory
45 var IgnoreImports bool // control whether we ignore imports in packages
47 // A Package describes a single package found in a directory.
49 PackagePublic // visible in 'go list'
50 Internal PackageInternal // for use inside go command only
53 type PackagePublic struct {
54 // Note: These fields are part of the go command's public API.
55 // See list.go. It is okay to add fields, but not to change or
56 // remove existing ones. Keep in sync with list.go
57 Dir string `json:",omitempty"` // directory containing package sources
58 ImportPath string `json:",omitempty"` // import path of package in dir
59 ImportComment string `json:",omitempty"` // path in import comment on package statement
60 Name string `json:",omitempty"` // package name
61 Doc string `json:",omitempty"` // package documentation string
62 Target string `json:",omitempty"` // installed target for this package (may be executable)
63 Shlib string `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
64 Root string `json:",omitempty"` // Go root or Go path dir containing this package
65 ConflictDir string `json:",omitempty"` // Dir is hidden by this other directory
66 ForTest string `json:",omitempty"` // package is only for use in named test
67 Export string `json:",omitempty"` // file containing export data (set by go list -export)
68 Module *modinfo.ModulePublic `json:",omitempty"` // info about package's module, if any
69 Match []string `json:",omitempty"` // command-line patterns matching this package
70 Goroot bool `json:",omitempty"` // is this package found in the Go root?
71 Standard bool `json:",omitempty"` // is this package part of the standard Go library?
72 DepOnly bool `json:",omitempty"` // package is only as a dependency, not explicitly listed
73 BinaryOnly bool `json:",omitempty"` // package cannot be recompiled
74 Incomplete bool `json:",omitempty"` // was there an error loading this package or dependencies?
76 // Stale and StaleReason remain here *only* for the list command.
77 // They are only initialized in preparation for list execution.
78 // The regular build determines staleness on the fly during action execution.
79 Stale bool `json:",omitempty"` // would 'go install' do anything for this package?
80 StaleReason string `json:",omitempty"` // why is Stale true?
83 // If you add to this list you MUST add to p.AllFiles (below) too.
84 // Otherwise file name security lists will not apply to any new additions.
85 GoFiles []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
86 CgoFiles []string `json:",omitempty"` // .go source files that import "C"
87 CompiledGoFiles []string `json:",omitempty"` // .go output from running cgo on CgoFiles
88 IgnoredGoFiles []string `json:",omitempty"` // .go source files ignored due to build constraints
89 CFiles []string `json:",omitempty"` // .c source files
90 CXXFiles []string `json:",omitempty"` // .cc, .cpp and .cxx source files
91 MFiles []string `json:",omitempty"` // .m source files
92 HFiles []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
93 FFiles []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
94 SFiles []string `json:",omitempty"` // .s source files
95 SwigFiles []string `json:",omitempty"` // .swig files
96 SwigCXXFiles []string `json:",omitempty"` // .swigcxx files
97 SysoFiles []string `json:",omitempty"` // .syso system object files added to package
100 CgoCFLAGS []string `json:",omitempty"` // cgo: flags for C compiler
101 CgoCPPFLAGS []string `json:",omitempty"` // cgo: flags for C preprocessor
102 CgoCXXFLAGS []string `json:",omitempty"` // cgo: flags for C++ compiler
103 CgoFFLAGS []string `json:",omitempty"` // cgo: flags for Fortran compiler
104 CgoLDFLAGS []string `json:",omitempty"` // cgo: flags for linker
105 CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
107 // Dependency information
108 Imports []string `json:",omitempty"` // import paths used by this package
109 ImportMap map[string]string `json:",omitempty"` // map from source import to ImportPath (identity entries omitted)
110 Deps []string `json:",omitempty"` // all (recursively) imported dependencies
113 // Incomplete is above, packed into the other bools
114 Error *PackageError `json:",omitempty"` // error loading this package (not dependencies)
115 DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
118 // If you add to this list you MUST add to p.AllFiles (below) too.
119 // Otherwise file name security lists will not apply to any new additions.
120 TestGoFiles []string `json:",omitempty"` // _test.go files in package
121 TestImports []string `json:",omitempty"` // imports from TestGoFiles
122 XTestGoFiles []string `json:",omitempty"` // _test.go files outside package
123 XTestImports []string `json:",omitempty"` // imports from XTestGoFiles
126 // AllFiles returns the names of all the files considered for the package.
127 // This is used for sanity and security checks, so we include all files,
128 // even IgnoredGoFiles, because some subcommands consider them.
129 // The go/build package filtered others out (like foo_wrongGOARCH.s)
131 func (p *Package) AllFiles() []string {
132 return str.StringList(
135 // no p.CompiledGoFiles, because they are from GoFiles or generated by us
151 // Desc returns the package "description", for use in b.showOutput.
152 func (p *Package) Desc() string {
154 return p.ImportPath + " [" + p.ForTest + ".test]"
159 type PackageInternal struct {
160 // Unexported fields are not part of the public API.
162 Imports []*Package // this package's direct imports
163 CompiledImports []string // additional Imports necessary when using CompiledGoFiles (all from standard library)
164 RawImports []string // this package's original imports as they appear in the text of the program
165 ForceLibrary bool // this package is a library (even if named "main")
166 CmdlineFiles bool // package built from files listed on command line
167 CmdlinePkg bool // package listed on command line
168 CmdlinePkgLiteral bool // package listed as literal on command line (not via wildcard)
169 Local bool // imported via local path (./ or ../)
170 LocalPrefix string // interpret ./ and ../ imports relative to this prefix
171 ExeName string // desired name for temporary executable
172 CoverMode string // preprocess Go source files with the coverage tool in this mode
173 CoverVars map[string]*CoverVar // variables created by coverage analysis
174 OmitDebug bool // tell linker not to write debug information
175 GobinSubdir bool // install target would be subdir of GOBIN
176 BuildInfo string // add this info to package main
177 TestmainGo *[]byte // content for _testmain.go
179 Asmflags []string // -asmflags for this package
180 Gcflags []string // -gcflags for this package
181 Ldflags []string // -ldflags for this package
182 Gccgoflags []string // -gccgoflags for this package
185 type NoGoError struct {
189 func (e *NoGoError) Error() string {
190 // Count files beginning with _ and ., which we will pretend don't exist at all.
192 for _, name := range e.Package.IgnoredGoFiles {
193 if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
198 if len(e.Package.IgnoredGoFiles) > dummy {
199 // Go files exist, but they were ignored due to build constraints.
200 return "build constraints exclude all Go files in " + e.Package.Dir
202 if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
203 // Test Go files exist, but we're not interested in them.
204 // The double-negative is unfortunate but we want e.Package.Dir
205 // to appear at the end of error message.
206 return "no non-test Go files in " + e.Package.Dir
208 return "no Go files in " + e.Package.Dir
211 // Resolve returns the resolved version of imports,
212 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
213 // The imports in p.TestImports and p.XTestImports are not recursively
214 // loaded during the initial load of p, so they list the imports found in
215 // the source file, but most processing should be over the vendor-resolved
216 // import paths. We do this resolution lazily both to avoid file system work
217 // and because the eventual real load of the test imports (during 'go test')
218 // can produce better error messages if it starts with the original paths.
219 // The initial load of p loads all the non-test imports and rewrites
220 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
221 func (p *Package) Resolve(imports []string) []string {
222 if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
223 panic("internal error: p.Resolve(p.Imports) called")
225 seen := make(map[string]bool)
227 for _, path := range imports {
228 path = ResolveImportPath(p, path)
231 all = append(all, path)
238 // CoverVar holds the name of the generated coverage variables targeting the named file.
239 type CoverVar struct {
240 File string // local file name
241 Var string // name of count struct
244 func (p *Package) copyBuild(pp *build.Package) {
245 p.Internal.Build = pp
247 if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
248 old := pp.PkgTargetRoot
249 pp.PkgRoot = cfg.BuildPkgdir
250 pp.PkgTargetRoot = cfg.BuildPkgdir
251 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
255 p.ImportPath = pp.ImportPath
256 p.ImportComment = pp.ImportComment
260 p.ConflictDir = pp.ConflictDir
261 p.BinaryOnly = pp.BinaryOnly
265 p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath)
266 p.GoFiles = pp.GoFiles
267 p.CgoFiles = pp.CgoFiles
268 p.IgnoredGoFiles = pp.IgnoredGoFiles
270 p.CXXFiles = pp.CXXFiles
275 p.SwigFiles = pp.SwigFiles
276 p.SwigCXXFiles = pp.SwigCXXFiles
277 p.SysoFiles = pp.SysoFiles
279 // There's no way for .syso files to be built both with and without
280 // support for memory sanitizer. Assume they are built without,
284 p.CgoCFLAGS = pp.CgoCFLAGS
285 p.CgoCPPFLAGS = pp.CgoCPPFLAGS
286 p.CgoCXXFLAGS = pp.CgoCXXFLAGS
287 p.CgoFFLAGS = pp.CgoFFLAGS
288 p.CgoLDFLAGS = pp.CgoLDFLAGS
289 p.CgoPkgConfig = pp.CgoPkgConfig
290 // We modify p.Imports in place, so make copy now.
291 p.Imports = make([]string, len(pp.Imports))
292 copy(p.Imports, pp.Imports)
293 p.Internal.RawImports = pp.Imports
294 p.TestGoFiles = pp.TestGoFiles
295 p.TestImports = pp.TestImports
296 p.XTestGoFiles = pp.XTestGoFiles
297 p.XTestImports = pp.XTestImports
300 p.Internal.RawImports = nil
306 // A PackageError describes an error loading information about a package.
307 type PackageError struct {
308 ImportStack []string // shortest path from package named on command line to this one
309 Pos string // position of error
310 Err string // the error itself
311 IsImportCycle bool `json:"-"` // the error is an import cycle
312 Hard bool `json:"-"` // whether the error is soft or hard; soft errors are ignored in some places
315 func (p *PackageError) Error() string {
316 // Import cycles deserve special treatment.
318 return fmt.Sprintf("%s\npackage %s\n", p.Err, strings.Join(p.ImportStack, "\n\timports "))
321 // Omit import stack. The full path to the file where the error
322 // is the most important thing.
323 return p.Pos + ": " + p.Err
325 if len(p.ImportStack) == 0 {
328 return "package " + strings.Join(p.ImportStack, "\n\timports ") + ": " + p.Err
331 // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended.
332 // The import path of a test package is the import path of the corresponding
333 // non-test package with the suffix "_test" added.
334 type ImportStack []string
336 func (s *ImportStack) Push(p string) {
340 func (s *ImportStack) Pop() {
341 *s = (*s)[0 : len(*s)-1]
344 func (s *ImportStack) Copy() []string {
345 return append([]string{}, *s...)
348 // shorterThan reports whether sp is shorter than t.
349 // We use this to record the shortest import sequence
350 // that leads to a particular package.
351 func (sp *ImportStack) shorterThan(t []string) bool {
353 if len(s) != len(t) {
354 return len(s) < len(t)
356 // If they are the same length, settle ties using string ordering.
362 return false // they are equal
365 // packageCache is a lookup cache for loadPackage,
366 // so that if we look up a package multiple times
367 // we return the same pointer each time.
368 var packageCache = map[string]*Package{}
370 func ClearPackageCache() {
371 for name := range packageCache {
372 delete(packageCache, name)
376 func ClearPackageCachePartial(args []string) {
377 for _, arg := range args {
378 p := packageCache[arg]
380 delete(packageCache, p.Dir)
381 delete(packageCache, p.ImportPath)
386 // ReloadPackageNoFlags is like LoadPackageNoFlags but makes sure
387 // not to use the package cache.
388 // It is only for use by GOPATH-based "go get".
389 // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
390 func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package {
391 p := packageCache[arg]
393 delete(packageCache, p.Dir)
394 delete(packageCache, p.ImportPath)
396 return LoadPackageNoFlags(arg, stk)
399 // dirToImportPath returns the pseudo-import path we use for a package
400 // outside the Go path. It begins with _/ and then contains the full path
401 // to the directory. If the package lives in c:\home\gopher\my\pkg then
402 // the pseudo-import path is _/c_/home/gopher/my/pkg.
403 // Using a pseudo-import path like this makes the ./ imports no longer
404 // a special case, so that all the code to deal with ordinary imports works
406 func dirToImportPath(dir string) string {
407 return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
410 func makeImportValid(r rune) rune {
411 // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
412 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
413 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
419 // Mode flags for loadImport and download (in get.go).
421 // ResolveImport means that loadImport should do import path expansion.
422 // That is, ResolveImport means that the import path came from
423 // a source file and has not been expanded yet to account for
424 // vendoring or possible module adjustment.
425 // Every import path should be loaded initially with ResolveImport,
426 // and then the expanded version (for example with the /vendor/ in it)
427 // gets recorded as the canonical import path. At that point, future loads
428 // of that package must not pass ResolveImport, because
429 // disallowVendor will reject direct use of paths containing /vendor/.
430 ResolveImport = 1 << iota
432 // ResolveModule is for download (part of "go get") and indicates
433 // that the module adjustment should be done, but not vendor adjustment.
436 // GetTestDeps is for download (part of "go get") and indicates
437 // that test dependencies should be fetched too.
441 // LoadImport scans the directory named by path, which must be an import path,
442 // but possibly a local import path (an absolute file system path or one beginning
443 // with ./ or ../). A local relative path is interpreted relative to srcDir.
444 // It returns a *Package describing the package found in that directory.
445 // LoadImport does not set tool flags and should only be used by
446 // this package, as part of a bigger load operation, and by GOPATH-based "go get".
447 // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
448 func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
450 panic("LoadImport called with empty package path")
456 if strings.HasPrefix(path, "mod/") {
457 // Paths beginning with "mod/" might accidentally
458 // look in the module cache directory tree in $GOPATH/pkg/mod/.
459 // This prefix is owned by the Go core for possible use in the
460 // standard library (since it does not begin with a domain name),
461 // so it's OK to disallow entirely.
463 PackagePublic: PackagePublic{
465 Error: &PackageError{
466 ImportStack: stk.Copy(),
467 Err: fmt.Sprintf("disallowed import path %q", path),
473 if strings.Contains(path, "@") {
475 if cfg.ModulesEnabled {
476 text = "can only use path@version syntax with 'go get'"
478 text = "cannot use path@version syntax in GOPATH mode"
481 PackagePublic: PackagePublic{
483 Error: &PackageError{
484 ImportStack: stk.Copy(),
493 parentPath = parent.ImportPath
496 // Determine canonical identifier for this package.
497 // For a local import the identifier is the pseudo-import path
498 // we create from the full directory to the package.
499 // Otherwise it is the usual import path.
500 // For vendored imports, it is the expanded form.
503 isLocal := build.IsLocalImport(path)
507 importPath = dirToImportPath(filepath.Join(srcDir, path))
508 } else if cfg.ModulesEnabled {
510 modDir, p, modErr = ModLookup(path)
514 } else if mode&ResolveImport != 0 {
515 // We do our own path resolution, because we want to
516 // find out the key to use in packageCache without the
517 // overhead of repeated calls to buildContext.Import.
518 // The code is also needed in a few other places anyway.
519 path = ResolveImportPath(parent, path)
521 } else if mode&ResolveModule != 0 {
522 path = ModuleImportPath(parent, path)
526 p := packageCache[importPath]
528 p = reusePackage(p, stk)
531 p.Internal.Local = isLocal
532 p.ImportPath = importPath
533 packageCache[importPath] = p
536 // Import always returns bp != nil, even if an error occurs,
537 // in order to return partial information.
538 var bp *build.Package
541 bp, err = cfg.BuildContext.ImportDir(modDir, 0)
542 } else if modErr != nil {
543 bp = new(build.Package)
544 err = fmt.Errorf("unknown import path %q: %v", importPath, modErr)
545 } else if cfg.ModulesEnabled && path != "unsafe" {
546 bp = new(build.Package)
547 err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", importPath)
549 buildMode := build.ImportComment
550 if mode&ResolveImport == 0 || path != origPath {
551 // Not vendoring, or we already found the vendored path.
552 buildMode |= build.IgnoreVendor
554 bp, err = cfg.BuildContext.Import(path, srcDir, buildMode)
556 bp.ImportPath = importPath
558 bp.BinDir = cfg.GOBIN
559 } else if cfg.ModulesEnabled {
560 bp.BinDir = ModBinDir()
562 if modDir == "" && err == nil && !isLocal && bp.ImportComment != "" && bp.ImportComment != path &&
563 !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
564 err = fmt.Errorf("code in directory %s expects import %q", bp.Dir, bp.ImportComment)
567 if p.Error != nil && p.Error.Pos == "" {
568 p = setErrorPos(p, importPos)
571 if modDir == "" && origPath != cleanImport(origPath) {
572 p.Error = &PackageError{
573 ImportStack: stk.Copy(),
574 Err: fmt.Sprintf("non-canonical import path: %q should be %q", origPath, pathpkg.Clean(origPath)),
580 // Checked on every import because the rules depend on the code doing the importing.
581 if perr := disallowInternal(srcDir, parent, parentPath, p, stk); perr != p {
582 return setErrorPos(perr, importPos)
584 if mode&ResolveImport != 0 {
585 if perr := disallowVendor(srcDir, parent, parentPath, origPath, p, stk); perr != p {
586 return setErrorPos(perr, importPos)
590 if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
592 perr.Error = &PackageError{
593 ImportStack: stk.Copy(),
594 Err: fmt.Sprintf("import %q is a program, not an importable package", path),
596 return setErrorPos(&perr, importPos)
599 if p.Internal.Local && parent != nil && !parent.Internal.Local {
601 perr.Error = &PackageError{
602 ImportStack: stk.Copy(),
603 Err: fmt.Sprintf("local import %q in non-local package", path),
605 return setErrorPos(&perr, importPos)
611 func setErrorPos(p *Package, importPos []token.Position) *Package {
612 if len(importPos) > 0 {
614 pos.Filename = base.ShortPath(pos.Filename)
615 p.Error.Pos = pos.String()
620 func cleanImport(path string) string {
622 path = pathpkg.Clean(path)
623 if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
629 var isDirCache = map[string]bool{}
631 func isDir(path string) bool {
632 result, ok := isDirCache[path]
637 fi, err := os.Stat(path)
638 result = err == nil && fi.IsDir()
639 isDirCache[path] = result
643 // ResolveImportPath returns the true meaning of path when it appears in parent.
644 // There are two different resolutions applied.
645 // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
646 // If vendor expansion doesn't trigger, then the path is also subject to
647 // Go 1.11 module legacy conversion (golang.org/issue/25069).
648 func ResolveImportPath(parent *Package, path string) (found string) {
649 if cfg.ModulesEnabled {
650 if _, p, e := ModLookup(path); e == nil {
655 found = VendoredImportPath(parent, path)
659 return ModuleImportPath(parent, path)
662 // dirAndRoot returns the source directory and workspace root
663 // for the package p, guaranteeing that root is a path prefix of dir.
664 func dirAndRoot(p *Package) (dir, root string) {
665 dir = filepath.Clean(p.Dir)
666 root = filepath.Join(p.Root, "src")
667 if !str.HasFilePathPrefix(dir, root) || p.ImportPath != "command-line-arguments" && filepath.Join(root, p.ImportPath) != dir {
668 // Look for symlinks before reporting error.
669 dir = expandPath(dir)
670 root = expandPath(root)
673 if !str.HasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator || p.ImportPath != "command-line-arguments" && !p.Internal.Local && filepath.Join(root, p.ImportPath) != dir {
674 base.Fatalf("unexpected directory layout:\n"+
675 " import path: %s\n"+
678 " expand root: %s\n"+
682 filepath.Join(p.Root, "src"),
683 filepath.Clean(p.Dir),
686 string(filepath.Separator))
692 // VendoredImportPath returns the vendor-expansion of path when it appears in parent.
693 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
694 // x/vendor/path, vendor/path, or else stay path if none of those exist.
695 // VendoredImportPath returns the expanded path or, if no expansion is found, the original.
696 func VendoredImportPath(parent *Package, path string) (found string) {
697 if parent == nil || parent.Root == "" {
701 dir, root := dirAndRoot(parent)
703 vpath := "vendor/" + path
704 for i := len(dir); i >= len(root); i-- {
705 if i < len(dir) && dir[i] != filepath.Separator {
708 // Note: checking for the vendor directory before checking
709 // for the vendor/path directory helps us hit the
710 // isDir cache more often. It also helps us prepare a more useful
711 // list of places we looked, to report when an import is not found.
712 if !isDir(filepath.Join(dir[:i], "vendor")) {
715 targ := filepath.Join(dir[:i], vpath)
716 if isDir(targ) && hasGoFiles(targ) {
717 importPath := parent.ImportPath
718 if importPath == "command-line-arguments" {
719 // If parent.ImportPath is 'command-line-arguments'.
720 // set to relative directory to root (also chopped root directory)
721 importPath = dir[len(root)+1:]
723 // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
724 // We know the import path for parent's dir.
725 // We chopped off some number of path elements and
726 // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
727 // Now we want to know the import path for that directory.
728 // Construct it by chopping the same number of path elements
729 // (actually the same number of bytes) from parent's import path
730 // and then append /vendor/path.
731 chopped := len(dir) - i
732 if chopped == len(importPath)+1 {
733 // We walked up from c:\gopath\src\foo\bar
734 // and found c:\gopath\src\vendor\path.
735 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
736 // Use "vendor/path" without any prefix.
739 return importPath[:len(importPath)-chopped] + "/" + vpath
746 modulePrefix = []byte("\nmodule ")
747 goModPathCache = make(map[string]string)
750 // goModPath returns the module path in the go.mod in dir, if any.
751 func goModPath(dir string) (path string) {
752 path, ok := goModPathCache[dir]
757 goModPathCache[dir] = path
760 data, err := ioutil.ReadFile(filepath.Join(dir, "go.mod"))
765 if bytes.HasPrefix(data, modulePrefix[1:]) {
768 i = bytes.Index(data, modulePrefix)
776 // Cut line at \n, drop trailing \r if present.
777 if j := bytes.IndexByte(line, '\n'); j >= 0 {
780 if line[len(line)-1] == '\r' {
781 line = line[:len(line)-1]
783 line = line[len("module "):]
785 // If quoted, unquote.
786 path = strings.TrimSpace(string(line))
787 if path != "" && path[0] == '"' {
788 s, err := strconv.Unquote(path)
797 // findVersionElement returns the slice indices of the final version element /vN in path.
798 // If there is no such element, it returns -1, -1.
799 func findVersionElement(path string) (i, j int) {
801 for i = len(path) - 1; i >= 0; i-- {
803 if isVersionElement(path[i:j]) {
812 // isVersionElement reports whether s is a well-formed path version element:
813 // v2, v3, v10, etc, but not v0, v05, v1.
814 func isVersionElement(s string) bool {
815 if len(s) < 3 || s[0] != '/' || s[1] != 'v' || s[2] == '0' || s[2] == '1' && len(s) == 3 {
818 for i := 2; i < len(s); i++ {
819 if s[i] < '0' || '9' < s[i] {
826 // ModuleImportPath translates import paths found in go modules
827 // back down to paths that can be resolved in ordinary builds.
829 // Define “new” code as code with a go.mod file in the same directory
830 // or a parent directory. If an import in new code says x/y/v2/z but
831 // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
832 // then go build will read the import as x/y/z instead.
833 // See golang.org/issue/25069.
834 func ModuleImportPath(parent *Package, path string) (found string) {
835 if parent == nil || parent.Root == "" {
839 // If there are no vN elements in path, leave it alone.
840 // (The code below would do the same, but only after
841 // some other file system accesses that we can avoid
842 // here by returning early.)
843 if i, _ := findVersionElement(path); i < 0 {
847 dir, root := dirAndRoot(parent)
849 // Consider dir and parents, up to and including root.
850 for i := len(dir); i >= len(root); i-- {
851 if i < len(dir) && dir[i] != filepath.Separator {
854 if goModPath(dir[:i]) != "" {
858 // This code is not in a tree with a go.mod,
859 // so apply no changes to the path.
863 // This import is in a tree with a go.mod.
864 // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
865 // if GOPATH/src/x/y/go.mod says module "x/y/v2",
867 // If x/y/v2/z exists, use it unmodified.
868 if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
872 // Otherwise look for a go.mod supplying a version element.
873 // Some version-like elements may appear in paths but not
874 // be module versions; we skip over those to look for module
875 // versions. For example the module m/v2 might have a
876 // package m/v2/api/v1/foo.
879 i, j := findVersionElement(path[:limit])
883 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
884 if mpath := goModPath(bp.Dir); mpath != "" {
885 // Found a valid go.mod file, so we're stopping the search.
886 // If the path is m/v2/p and we found m/go.mod that says
887 // "module m/v2", then we return "m/p".
888 if mpath == path[:j] {
889 return path[:i] + path[j:]
891 // Otherwise just return the original path.
892 // We didn't find anything worth rewriting,
893 // and the go.mod indicates that we should
894 // not consider parent directories.
903 // hasGoFiles reports whether dir contains any files with names ending in .go.
904 // For a vendor check we must exclude directories that contain no .go files.
905 // Otherwise it is not possible to vendor just a/b/c and still import the
906 // non-vendored a/b. See golang.org/issue/13832.
907 func hasGoFiles(dir string) bool {
908 fis, _ := ioutil.ReadDir(dir)
909 for _, fi := range fis {
910 if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
917 // reusePackage reuses package p to satisfy the import at the top
918 // of the import stack stk. If this use causes an import loop,
919 // reusePackage updates p's error information to record the loop.
920 func reusePackage(p *Package, stk *ImportStack) *Package {
921 // We use p.Internal.Imports==nil to detect a package that
922 // is in the midst of its own loadPackage call
923 // (all the recursion below happens before p.Internal.Imports gets set).
924 if p.Internal.Imports == nil {
926 p.Error = &PackageError{
927 ImportStack: stk.Copy(),
928 Err: "import cycle not allowed",
934 // Don't rewrite the import stack in the error if we have an import cycle.
935 // If we do, we'll lose the path that describes the cycle.
936 if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
937 p.Error.ImportStack = stk.Copy()
942 // disallowInternal checks that srcDir (containing package importerPath, if non-empty)
943 // is allowed to import p.
944 // If the import is allowed, disallowInternal returns the original package p.
945 // If not, it returns a new package containing just an appropriate error.
946 func disallowInternal(srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *Package {
947 // golang.org/s/go14internal:
948 // An import of a path containing the element “internal”
949 // is disallowed if the importing code is outside the tree
950 // rooted at the parent of the “internal” directory.
952 // There was an error loading the package; stop here.
957 // The generated 'testmain' package is allowed to access testing/internal/...,
958 // as if it were generated into the testing directory tree
959 // (it's actually in a temporary directory outside any Go tree).
960 // This cleans up a former kludge in passing functionality to the testing package.
961 if strings.HasPrefix(p.ImportPath, "testing/internal") && len(*stk) >= 2 && (*stk)[len(*stk)-2] == "testmain" {
965 // We can't check standard packages with gccgo.
966 if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
970 // The stack includes p.ImportPath.
971 // If that's the only thing on the stack, we started
972 // with a name given on the command line, not an
973 // import. Anything listed on the command line is fine.
978 // Check for "internal" element: three cases depending on begin of string and/or end of string.
979 i, ok := findInternal(p.ImportPath)
984 // Internal is present.
985 // Map import path back to directory corresponding to parent of internal.
987 i-- // rewind over slash in ".../internal"
991 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
993 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
997 // Look for symlinks before reporting error.
998 srcDir = expandPath(srcDir)
999 parent = expandPath(parent)
1000 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1004 // p is in a module, so make it available based on the importer's import path instead
1005 // of the file path (https://golang.org/issue/23970).
1006 if importer.Internal.CmdlineFiles {
1007 // The importer is a list of command-line files.
1008 // Pretend that the import path is the import path of the
1009 // directory containing them.
1010 // If the directory is outside the main module, this will resolve to ".",
1011 // which is not a prefix of any valid module.
1012 importerPath = ModDirImportPath(importer.Dir)
1014 parentOfInternal := p.ImportPath[:i]
1015 if str.HasPathPrefix(importerPath, parentOfInternal) {
1020 // Internal is present, and srcDir is outside parent's tree. Not allowed.
1022 perr.Error = &PackageError{
1023 ImportStack: stk.Copy(),
1024 Err: "use of internal package " + p.ImportPath + " not allowed",
1026 perr.Incomplete = true
1030 // findInternal looks for the final "internal" path element in the given import path.
1031 // If there isn't one, findInternal returns ok=false.
1032 // Otherwise, findInternal returns ok=true and the index of the "internal".
1033 func findInternal(path string) (index int, ok bool) {
1034 // Three cases, depending on internal at start/end of string or not.
1035 // The order matters: we must return the index of the final element,
1036 // because the final one produces the most restrictive requirement
1039 case strings.HasSuffix(path, "/internal"):
1040 return len(path) - len("internal"), true
1041 case strings.Contains(path, "/internal/"):
1042 return strings.LastIndex(path, "/internal/") + 1, true
1043 case path == "internal", strings.HasPrefix(path, "internal/"):
1049 // disallowVendor checks that srcDir (containing package importerPath, if non-empty)
1050 // is allowed to import p as path.
1051 // If the import is allowed, disallowVendor returns the original package p.
1052 // If not, it returns a new package containing just an appropriate error.
1053 func disallowVendor(srcDir string, importer *Package, importerPath, path string, p *Package, stk *ImportStack) *Package {
1054 // The stack includes p.ImportPath.
1055 // If that's the only thing on the stack, we started
1056 // with a name given on the command line, not an
1057 // import. Anything listed on the command line is fine.
1062 if perr := disallowVendorVisibility(srcDir, p, stk); perr != p {
1066 // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
1067 if i, ok := FindVendor(path); ok {
1069 perr.Error = &PackageError{
1070 ImportStack: stk.Copy(),
1071 Err: "must be imported as " + path[i+len("vendor/"):],
1073 perr.Incomplete = true
1080 // disallowVendorVisibility checks that srcDir is allowed to import p.
1081 // The rules are the same as for /internal/ except that a path ending in /vendor
1082 // is not subject to the rules, only subdirectories of vendor.
1083 // This allows people to have packages and commands named vendor,
1084 // for maximal compatibility with existing source trees.
1085 func disallowVendorVisibility(srcDir string, p *Package, stk *ImportStack) *Package {
1086 // The stack includes p.ImportPath.
1087 // If that's the only thing on the stack, we started
1088 // with a name given on the command line, not an
1089 // import. Anything listed on the command line is fine.
1094 // Check for "vendor" element.
1095 i, ok := FindVendor(p.ImportPath)
1100 // Vendor is present.
1101 // Map import path back to directory corresponding to parent of vendor.
1103 i-- // rewind over slash in ".../vendor"
1105 truncateTo := i + len(p.Dir) - len(p.ImportPath)
1106 if truncateTo < 0 || len(p.Dir) < truncateTo {
1109 parent := p.Dir[:truncateTo]
1110 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1114 // Look for symlinks before reporting error.
1115 srcDir = expandPath(srcDir)
1116 parent = expandPath(parent)
1117 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1121 // Vendor is present, and srcDir is outside parent's tree. Not allowed.
1123 perr.Error = &PackageError{
1124 ImportStack: stk.Copy(),
1125 Err: "use of vendored package not allowed",
1127 perr.Incomplete = true
1131 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
1132 // If there isn't one, FindVendor returns ok=false.
1133 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
1135 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
1136 // not the vendored copy of an import "" (the empty import path).
1137 // This will allow people to have packages or commands named vendor.
1138 // This may help reduce breakage, or it may just be confusing. We'll see.
1139 func FindVendor(path string) (index int, ok bool) {
1140 // Two cases, depending on internal at start of string or not.
1141 // The order matters: we must return the index of the final element,
1142 // because the final one is where the effective import path starts.
1144 case strings.Contains(path, "/vendor/"):
1145 return strings.LastIndex(path, "/vendor/") + 1, true
1146 case strings.HasPrefix(path, "vendor/"):
1155 ToTool TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
1156 ToBin // to bin dir inside package root (default for non-cmd/*)
1157 StalePath // an old import path; fail to build
1160 // InstallTargetDir reports the target directory for installing the command p.
1161 func InstallTargetDir(p *Package) TargetDir {
1162 if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
1165 if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1166 switch p.ImportPath {
1167 case "cmd/go", "cmd/gofmt":
1175 var cgoExclude = map[string]bool{
1176 "runtime/cgo": true,
1179 var cgoSyscallExclude = map[string]bool{
1180 "runtime/cgo": true,
1181 "runtime/race": true,
1182 "runtime/msan": true,
1185 var foldPath = make(map[string]string)
1187 // load populates p using information from bp, err, which should
1188 // be the result of calling build.Context.Import.
1189 func (p *Package) load(stk *ImportStack, bp *build.Package, err error) {
1192 // The localPrefix is the path we interpret ./ imports relative to.
1193 // Synthesized main packages sometimes override this.
1194 if p.Internal.Local {
1195 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1199 if _, ok := err.(*build.NoGoError); ok {
1200 err = &NoGoError{Package: p}
1203 err = base.ExpandScanner(err)
1204 p.Error = &PackageError{
1205 ImportStack: stk.Copy(),
1211 useBindir := p.Name == "main"
1213 switch cfg.BuildBuildmode {
1214 case "c-archive", "c-shared", "plugin":
1220 // Report an error when the old code.google.com/p/go.tools paths are used.
1221 if InstallTargetDir(p) == StalePath {
1222 newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
1223 e := fmt.Sprintf("the %v command has moved; use %v instead.", p.ImportPath, newPath)
1224 p.Error = &PackageError{Err: e}
1227 _, elem := filepath.Split(p.Dir)
1228 if cfg.ModulesEnabled {
1229 // NOTE(rsc): Using p.ImportPath instead of p.Dir
1230 // makes sure we install a package in the root of a
1231 // cached module directory as that package name
1233 // Using p.ImportPath instead of p.Dir
1234 // is probably correct all the time,
1235 // even for non-module-enabled code,
1236 // but I'm not brave enough to change the
1237 // non-module behavior this late in the
1238 // release cycle. Maybe for Go 1.12.
1239 // See golang.org/issue/26869.
1240 _, elem = pathpkg.Split(p.ImportPath)
1242 // If this is example.com/mycmd/v2, it's more useful to install it as mycmd than as v2.
1243 // See golang.org/issue/24667.
1244 isVersion := func(v string) bool {
1245 if len(v) < 2 || v[0] != 'v' || v[1] < '1' || '9' < v[1] {
1248 for i := 2; i < len(v); i++ {
1249 if c := v[i]; c < '0' || '9' < c {
1255 if isVersion(elem) {
1256 _, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath))
1259 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
1260 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
1261 // Install cross-compiled binaries to subdirectories of bin.
1264 if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
1265 p.Internal.Build.BinDir = ModBinDir()
1267 if p.Internal.Build.BinDir != "" {
1268 // Install to GOBIN or bin of GOPATH entry.
1269 p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1270 if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
1271 // Do not create $GOBIN/goos_goarch/elem.
1273 p.Internal.GobinSubdir = true
1276 if InstallTargetDir(p) == ToTool {
1277 // This is for 'go tool'.
1278 // Override all the usual logic and force it into the tool directory.
1279 if cfg.BuildToolchainName == "gccgo" {
1280 p.Target = filepath.Join(base.ToolDir, elem)
1282 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1285 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
1288 } else if p.Internal.Local {
1289 // Local import turned into absolute path.
1290 // No permanent install target.
1293 p.Target = p.Internal.Build.PkgObj
1294 if cfg.BuildLinkshared {
1295 shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
1296 shlib, err := ioutil.ReadFile(shlibnamefile)
1297 if err != nil && !os.IsNotExist(err) {
1298 base.Fatalf("reading shlibname: %v", err)
1301 libname := strings.TrimSpace(string(shlib))
1302 if cfg.BuildContext.Compiler == "gccgo" {
1303 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1305 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1311 // Build augmented import list to add implicit dependencies.
1312 // Be careful not to add imports twice, just to avoid confusion.
1313 importPaths := p.Imports
1314 addImport := func(path string, forCompiler bool) {
1315 for _, p := range importPaths {
1320 importPaths = append(importPaths, path)
1322 p.Internal.CompiledImports = append(p.Internal.CompiledImports, path)
1326 // Cgo translation adds imports of "unsafe", "runtime/cgo" and "syscall",
1327 // except for certain packages, to avoid circular dependencies.
1329 addImport("unsafe", true)
1331 if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1332 addImport("runtime/cgo", true)
1334 if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1335 addImport("syscall", true)
1338 // SWIG adds imports of some standard packages.
1340 addImport("unsafe", true)
1341 if cfg.BuildContext.Compiler != "gccgo" {
1342 addImport("runtime/cgo", true)
1344 addImport("syscall", true)
1345 addImport("sync", true)
1347 // TODO: The .swig and .swigcxx files can use
1348 // %go_import directives to import other packages.
1351 // The linker loads implicit dependencies.
1352 if p.Name == "main" && !p.Internal.ForceLibrary {
1353 for _, dep := range LinkerDeps(p) {
1354 addImport(dep, false)
1358 // Check for case-insensitive collision of input files.
1359 // To avoid problems on case-insensitive files, we reject any package
1360 // where two different input files have equal names under a case-insensitive
1362 inputs := p.AllFiles()
1363 f1, f2 := str.FoldDup(inputs)
1365 p.Error = &PackageError{
1366 ImportStack: stk.Copy(),
1367 Err: fmt.Sprintf("case-insensitive file name collision: %q and %q", f1, f2),
1372 // If first letter of input file is ASCII, it must be alphanumeric.
1373 // This avoids files turning into flags when invoking commands,
1374 // and other problems we haven't thought of yet.
1375 // Also, _cgo_ files must be generated by us, not supplied.
1376 // They are allowed to have //go:cgo_ldflag directives.
1377 // The directory scan ignores files beginning with _,
1378 // so we shouldn't see any _cgo_ files anyway, but just be safe.
1379 for _, file := range inputs {
1380 if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
1381 p.Error = &PackageError{
1382 ImportStack: stk.Copy(),
1383 Err: fmt.Sprintf("invalid input file name %q", file),
1388 if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
1389 p.Error = &PackageError{
1390 ImportStack: stk.Copy(),
1391 Err: fmt.Sprintf("invalid input directory name %q", name),
1395 if !SafeArg(p.ImportPath) {
1396 p.Error = &PackageError{
1397 ImportStack: stk.Copy(),
1398 Err: fmt.Sprintf("invalid import path %q", p.ImportPath),
1403 // Build list of imported packages and full dependency list.
1404 imports := make([]*Package, 0, len(p.Imports))
1405 for i, path := range importPaths {
1409 p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1410 if p.Standard && p.Error == nil && !p1.Standard && p1.Error == nil {
1411 p.Error = &PackageError{
1412 ImportStack: stk.Copy(),
1413 Err: fmt.Sprintf("non-standard import %q in standard package %q", path, p.ImportPath),
1415 pos := p.Internal.Build.ImportPos[path]
1417 p.Error.Pos = pos[0].String()
1421 path = p1.ImportPath
1422 importPaths[i] = path
1423 if i < len(p.Imports) {
1427 imports = append(imports, p1)
1432 p.Internal.Imports = imports
1434 deps := make(map[string]*Package)
1436 q = append(q, imports...)
1437 for i := 0; i < len(q); i++ {
1439 path := p1.ImportPath
1440 // The same import path could produce an error or not,
1441 // depending on what tries to import it.
1442 // Prefer to record entries with errors, so we can report them.
1444 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
1446 for _, p2 := range p1.Internal.Imports {
1447 if deps[p2.ImportPath] != p2 {
1454 p.Deps = make([]string, 0, len(deps))
1455 for dep := range deps {
1456 p.Deps = append(p.Deps, dep)
1458 sort.Strings(p.Deps)
1459 for _, dep := range p.Deps {
1462 panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
1464 if p1.Error != nil {
1465 p.DepsErrors = append(p.DepsErrors, p1.Error)
1469 // unsafe is a fake package.
1470 if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1474 // If cgo is not enabled, ignore cgo supporting sources
1475 // just as we ignore go files containing import "C".
1476 if !cfg.BuildContext.CgoEnabled {
1481 p.SwigCXXFiles = nil
1482 // Note that SFiles are okay (they go to the Go assembler)
1483 // and HFiles are okay (they might be used by the SFiles).
1484 // Also Sysofiles are okay (they might not contain object
1485 // code; see issue #16050).
1488 setError := func(msg string) {
1489 p.Error = &PackageError{
1490 ImportStack: stk.Copy(),
1495 // The gc toolchain only permits C source files with cgo or SWIG.
1496 if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1497 setError(fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1501 // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1502 // regardless of toolchain.
1503 if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1504 setError(fmt.Sprintf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1507 if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1508 setError(fmt.Sprintf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1511 if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1512 setError(fmt.Sprintf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1516 // Check for case-insensitive collisions of import paths.
1517 fold := str.ToFold(p.ImportPath)
1518 if other := foldPath[fold]; other == "" {
1519 foldPath[fold] = p.ImportPath
1520 } else if other != p.ImportPath {
1521 setError(fmt.Sprintf("case-insensitive import collision: %q and %q", p.ImportPath, other))
1525 if cfg.ModulesEnabled {
1526 mainPath := p.ImportPath
1527 if p.Internal.CmdlineFiles {
1528 mainPath = "command-line-arguments"
1530 p.Module = ModPackageModuleInfo(mainPath)
1531 if p.Name == "main" {
1532 p.Internal.BuildInfo = ModPackageBuildInfo(mainPath, p.Deps)
1537 // SafeArg reports whether arg is a "safe" command-line argument,
1538 // meaning that when it appears in a command-line, it probably
1539 // doesn't have some special meaning other than its own name.
1540 // Obviously args beginning with - are not safe (they look like flags).
1541 // Less obviously, args beginning with @ are not safe (they look like
1542 // GNU binutils flagfile specifiers, sometimes called "response files").
1543 // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
1544 // We accept leading . _ and / as likely in file system paths.
1545 // There is a copy of this function in cmd/compile/internal/gc/noder.go.
1546 func SafeArg(name string) bool {
1551 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
1554 // LinkerDeps returns the list of linker-induced dependencies for main package p.
1555 func LinkerDeps(p *Package) []string {
1556 // Everything links runtime.
1557 deps := []string{"runtime"}
1559 // External linking mode forces an import of runtime/cgo.
1560 if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
1561 deps = append(deps, "runtime/cgo")
1563 // On ARM with GOARM=5, it forces an import of math, for soft floating point.
1564 if cfg.Goarch == "arm" {
1565 deps = append(deps, "math")
1567 // Using the race detector forces an import of runtime/race.
1569 deps = append(deps, "runtime/race")
1571 // Using memory sanitizer forces an import of runtime/msan.
1573 deps = append(deps, "runtime/msan")
1579 // externalLinkingForced reports whether external linking is being
1580 // forced even for programs that do not use cgo.
1581 func externalLinkingForced(p *Package) bool {
1582 // Some targets must use external linking even inside GOROOT.
1583 switch cfg.BuildContext.GOOS {
1587 switch cfg.BuildContext.GOARCH {
1588 case "arm", "arm64":
1593 if !cfg.BuildContext.CgoEnabled {
1596 // Currently build modes c-shared, pie (on systems that do not
1597 // support PIE with internal linking mode (currently all
1598 // systems: issue #18968)), plugin, and -linkshared force
1599 // external linking mode, as of course does
1600 // -ldflags=-linkmode=external. External linking mode forces
1601 // an import of runtime/cgo.
1602 pieCgo := cfg.BuildBuildmode == "pie"
1603 linkmodeExternal := false
1605 ldflags := BuildLdflags.For(p)
1606 for i, a := range ldflags {
1607 if a == "-linkmode=external" {
1608 linkmodeExternal = true
1610 if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
1611 linkmodeExternal = true
1616 return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
1619 // mkAbs rewrites list, which must be paths relative to p.Dir,
1620 // into a sorted list of absolute paths. It edits list in place but for
1621 // convenience also returns list back to its caller.
1622 func (p *Package) mkAbs(list []string) []string {
1623 for i, f := range list {
1624 list[i] = filepath.Join(p.Dir, f)
1630 // InternalGoFiles returns the list of Go files being built for the package,
1631 // using absolute paths.
1632 func (p *Package) InternalGoFiles() []string {
1633 return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
1636 // InternalXGoFiles returns the list of Go files being built for the XTest package,
1637 // using absolute paths.
1638 func (p *Package) InternalXGoFiles() []string {
1639 return p.mkAbs(p.XTestGoFiles)
1642 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
1643 // using absolute paths. "Possibly relevant" means that files are not excluded
1644 // due to build tags, but files with names beginning with . or _ are still excluded.
1645 func (p *Package) InternalAllGoFiles() []string {
1647 for _, f := range p.IgnoredGoFiles {
1648 if f != "" && f[0] != '.' || f[0] != '_' {
1649 extra = append(extra, f)
1652 return p.mkAbs(str.StringList(extra, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
1655 // usesSwig reports whether the package needs to run SWIG.
1656 func (p *Package) UsesSwig() bool {
1657 return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
1660 // usesCgo reports whether the package needs to run cgo
1661 func (p *Package) UsesCgo() bool {
1662 return len(p.CgoFiles) > 0
1665 // PackageList returns the list of packages in the dag rooted at roots
1666 // as visited in a depth-first post-order traversal.
1667 func PackageList(roots []*Package) []*Package {
1668 seen := map[*Package]bool{}
1670 var walk func(*Package)
1671 walk = func(p *Package) {
1676 for _, p1 := range p.Internal.Imports {
1679 all = append(all, p)
1681 for _, root := range roots {
1687 // TestPackageList returns the list of packages in the dag rooted at roots
1688 // as visited in a depth-first post-order traversal, including the test
1689 // imports of the roots. This ignores errors in test packages.
1690 func TestPackageList(roots []*Package) []*Package {
1691 seen := map[*Package]bool{}
1693 var walk func(*Package)
1694 walk = func(p *Package) {
1699 for _, p1 := range p.Internal.Imports {
1702 all = append(all, p)
1704 walkTest := func(root *Package, path string) {
1706 p1 := LoadImport(path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
1707 if p1.Error == nil {
1711 for _, root := range roots {
1713 for _, path := range root.TestImports {
1714 walkTest(root, path)
1716 for _, path := range root.XTestImports {
1717 walkTest(root, path)
1723 var cmdCache = map[string]*Package{}
1725 func ClearCmdCache() {
1726 for name := range cmdCache {
1727 delete(cmdCache, name)
1731 // LoadPackage loads the package named by arg.
1732 func LoadPackage(arg string, stk *ImportStack) *Package {
1733 p := loadPackage(arg, stk)
1738 // LoadPackageNoFlags is like LoadPackage
1739 // but does not guarantee that the build tool flags are set in the result.
1740 // It is only for use by GOPATH-based "go get"
1741 // and is only appropriate for preliminary loading of packages.
1742 // A real load using LoadPackage or (more likely)
1743 // Packages, PackageAndErrors, or PackagesForBuild
1744 // must be done before passing the package to any build
1745 // steps, so that the tool flags can be set properly.
1746 // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
1747 func LoadPackageNoFlags(arg string, stk *ImportStack) *Package {
1748 return loadPackage(arg, stk)
1751 // loadPackage is like loadImport but is used for command-line arguments,
1752 // not for paths found in import statements. In addition to ordinary import paths,
1753 // loadPackage accepts pseudo-paths beginning with cmd/ to denote commands
1754 // in the Go command directory, as well as paths to those directories.
1755 func loadPackage(arg string, stk *ImportStack) *Package {
1757 panic("loadPackage called with empty package path")
1759 if build.IsLocalImport(arg) {
1761 if !filepath.IsAbs(dir) {
1762 if abs, err := filepath.Abs(dir); err == nil {
1763 // interpret relative to current directory
1767 if sub, ok := hasSubdir(cfg.GOROOTsrc, dir); ok && strings.HasPrefix(sub, "cmd/") && !strings.Contains(sub[4:], "/") {
1771 if strings.HasPrefix(arg, "cmd/") && !strings.Contains(arg[4:], "/") {
1772 if p := cmdCache[arg]; p != nil {
1778 bp, err := cfg.BuildContext.ImportDir(filepath.Join(cfg.GOROOTsrc, arg), 0)
1781 bp.BinDir = cfg.GOROOTbin
1782 bp.Root = cfg.GOROOT
1783 bp.SrcRoot = cfg.GOROOTsrc
1786 p.load(stk, bp, err)
1787 if p.Error == nil && p.Name != "main" {
1788 p.Error = &PackageError{
1789 ImportStack: stk.Copy(),
1790 Err: fmt.Sprintf("expected package main but found package %s in %s", p.Name, p.Dir),
1796 // Wasn't a command; must be a package.
1797 // If it is a local import path but names a standard package,
1798 // we treat it as if the user specified the standard package.
1799 // This lets you run go test ./ioutil in package io and be
1800 // referring to io/ioutil rather than a hypothetical import of
1802 if build.IsLocalImport(arg) || filepath.IsAbs(arg) {
1804 if !filepath.IsAbs(arg) {
1805 dir = filepath.Join(base.Cwd, arg)
1807 bp, _ := cfg.BuildContext.ImportDir(dir, build.FindOnly)
1808 if bp.ImportPath != "" && bp.ImportPath != "." {
1813 return LoadImport(arg, base.Cwd, nil, stk, nil, 0)
1816 // Packages returns the packages named by the
1817 // command line arguments 'args'. If a named package
1818 // cannot be loaded at all (for example, if the directory does not exist),
1819 // then packages prints an error and does not include that
1820 // package in the results. However, if errors occur trying
1821 // to load dependencies of a named package, the named
1822 // package is still returned, with p.Incomplete = true
1823 // and details in p.DepsErrors.
1824 func Packages(args []string) []*Package {
1826 for _, pkg := range PackagesAndErrors(args) {
1827 if pkg.Error != nil {
1828 base.Errorf("can't load package: %s", pkg.Error)
1831 pkgs = append(pkgs, pkg)
1836 // PackagesAndErrors is like 'packages' but returns a
1837 // *Package for every argument, even the ones that
1838 // cannot be loaded at all.
1839 // The packages that fail to load will have p.Error != nil.
1840 func PackagesAndErrors(patterns []string) []*Package {
1841 if len(patterns) > 0 && strings.HasSuffix(patterns[0], ".go") {
1842 return []*Package{GoFilesPackage(patterns)}
1845 matches := ImportPaths(patterns)
1849 seenPkg = make(map[*Package]bool)
1852 for _, m := range matches {
1853 for _, pkg := range m.Pkgs {
1855 panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern))
1857 p := loadPackage(pkg, &stk)
1858 p.Match = append(p.Match, m.Pattern)
1859 p.Internal.CmdlinePkg = true
1861 // Note: do not set = m.Literal unconditionally
1862 // because maybe we'll see p matching both
1863 // a literal and also a non-literal pattern.
1864 p.Internal.CmdlinePkgLiteral = true
1870 pkgs = append(pkgs, p)
1874 // Now that CmdlinePkg is set correctly,
1875 // compute the effective flags for all loaded packages
1876 // (not just the ones matching the patterns but also
1877 // their dependencies).
1878 setToolFlags(pkgs...)
1883 func setToolFlags(pkgs ...*Package) {
1884 for _, p := range PackageList(pkgs) {
1885 p.Internal.Asmflags = BuildAsmflags.For(p)
1886 p.Internal.Gcflags = BuildGcflags.For(p)
1887 p.Internal.Ldflags = BuildLdflags.For(p)
1888 p.Internal.Gccgoflags = BuildGccgoflags.For(p)
1892 func ImportPaths(args []string) []*search.Match {
1893 if ModInit(); cfg.ModulesEnabled {
1894 return ModImportPaths(args)
1896 return search.ImportPaths(args)
1899 // PackagesForBuild is like Packages but exits
1900 // if any of the packages or their dependencies have errors
1901 // (cannot be built).
1902 func PackagesForBuild(args []string) []*Package {
1903 pkgs := PackagesAndErrors(args)
1904 printed := map[*PackageError]bool{}
1905 for _, pkg := range pkgs {
1906 if pkg.Error != nil {
1907 base.Errorf("can't load package: %s", pkg.Error)
1908 printed[pkg.Error] = true
1910 for _, err := range pkg.DepsErrors {
1911 // Since these are errors in dependencies,
1912 // the same error might show up multiple times,
1913 // once in each package that depends on it.
1914 // Only print each once.
1917 base.Errorf("%s", err)
1923 // Check for duplicate loads of the same package.
1924 // That should be impossible, but if it does happen then
1925 // we end up trying to build the same package twice,
1926 // usually in parallel overwriting the same files,
1927 // which doesn't work very well.
1928 seen := map[string]bool{}
1929 reported := map[string]bool{}
1930 for _, pkg := range PackageList(pkgs) {
1931 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
1932 reported[pkg.ImportPath] = true
1933 base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
1935 seen[pkg.ImportPath] = true
1942 // GoFilesPackage creates a package for building a collection of Go files
1943 // (typically named on the command line). The target is named p.a for
1944 // package p or named after the first Go file for package main.
1945 func GoFilesPackage(gofiles []string) *Package {
1948 for _, f := range gofiles {
1949 if !strings.HasSuffix(f, ".go") {
1950 base.Fatalf("named files must be .go files")
1955 ctxt := cfg.BuildContext
1956 ctxt.UseAllFiles = true
1958 // Synthesize fake "directory" that only shows the named files,
1959 // to make it look like this is a standard package or
1960 // command directory. So that local imports resolve
1961 // consistently, the files must all be in the same directory.
1962 var dirent []os.FileInfo
1964 for _, file := range gofiles {
1965 fi, err := os.Stat(file)
1967 base.Fatalf("%s", err)
1970 base.Fatalf("%s is a directory, should be a Go file", file)
1972 dir1, _ := filepath.Split(file)
1978 } else if dir != dir1 {
1979 base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
1981 dirent = append(dirent, fi)
1983 ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
1985 if cfg.ModulesEnabled {
1986 ModImportFromFiles(gofiles)
1993 dir, err = filepath.Abs(dir)
1995 base.Fatalf("%s", err)
1998 bp, err := ctxt.ImportDir(dir, 0)
2000 pkg.Internal.Local = true
2001 pkg.Internal.CmdlineFiles = true
2003 pkg.load(&stk, bp, err)
2005 pkg.Internal.LocalPrefix = dirToImportPath(dir)
2006 pkg.ImportPath = "command-line-arguments"
2010 if pkg.Name == "main" {
2011 _, elem := filepath.Split(gofiles[0])
2012 exe := elem[:len(elem)-len(".go")] + cfg.ExeSuffix
2013 if cfg.BuildO == "" {
2016 if cfg.GOBIN != "" {
2017 pkg.Target = filepath.Join(cfg.GOBIN, exe)
2018 } else if cfg.ModulesEnabled {
2019 pkg.Target = filepath.Join(ModBinDir(), exe)