]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/go/internal/load/pkg.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / cmd / go / internal / load / pkg.go
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package load loads packages.
6 package load
7
8 import (
9         "bytes"
10         "encoding/json"
11         "errors"
12         "fmt"
13         "go/build"
14         "go/scanner"
15         "go/token"
16         "io/ioutil"
17         "os"
18         pathpkg "path"
19         "path/filepath"
20         "runtime"
21         "sort"
22         "strconv"
23         "strings"
24         "unicode"
25         "unicode/utf8"
26
27         "cmd/go/internal/base"
28         "cmd/go/internal/cfg"
29         "cmd/go/internal/modinfo"
30         "cmd/go/internal/par"
31         "cmd/go/internal/search"
32         "cmd/go/internal/str"
33 )
34
35 var (
36         // module initialization hook; never nil, no-op if module use is disabled
37         ModInit func()
38
39         // module hooks; nil if module use is disabled
40         ModBinDir            func() string                                                                            // return effective bin directory
41         ModLookup            func(parentPath string, parentIsStd bool, path string) (dir, realPath string, err error) // lookup effective meaning of import
42         ModPackageModuleInfo func(path string) *modinfo.ModulePublic                                                  // return module info for Package struct
43         ModImportPaths       func(args []string) []*search.Match                                                      // expand import paths
44         ModPackageBuildInfo  func(main string, deps []string) string                                                  // return module info to embed in binary
45         ModInfoProg          func(info string, isgccgo bool) []byte                                                   // wrap module info in .go code for binary
46         ModImportFromFiles   func([]string)                                                                           // update go.mod to add modules for imports in these files
47         ModDirImportPath     func(string) string                                                                      // return effective import path for directory
48 )
49
50 var IgnoreImports bool // control whether we ignore imports in packages
51
52 // A Package describes a single package found in a directory.
53 type Package struct {
54         PackagePublic                 // visible in 'go list'
55         Internal      PackageInternal // for use inside go command only
56 }
57
58 type PackagePublic struct {
59         // Note: These fields are part of the go command's public API.
60         // See list.go. It is okay to add fields, but not to change or
61         // remove existing ones. Keep in sync with list.go
62         Dir           string                `json:",omitempty"` // directory containing package sources
63         ImportPath    string                `json:",omitempty"` // import path of package in dir
64         ImportComment string                `json:",omitempty"` // path in import comment on package statement
65         Name          string                `json:",omitempty"` // package name
66         Doc           string                `json:",omitempty"` // package documentation string
67         Target        string                `json:",omitempty"` // installed target for this package (may be executable)
68         Shlib         string                `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
69         Root          string                `json:",omitempty"` // Go root, Go path dir, or module root dir containing this package
70         ConflictDir   string                `json:",omitempty"` // Dir is hidden by this other directory
71         ForTest       string                `json:",omitempty"` // package is only for use in named test
72         Export        string                `json:",omitempty"` // file containing export data (set by go list -export)
73         Module        *modinfo.ModulePublic `json:",omitempty"` // info about package's module, if any
74         Match         []string              `json:",omitempty"` // command-line patterns matching this package
75         Goroot        bool                  `json:",omitempty"` // is this package found in the Go root?
76         Standard      bool                  `json:",omitempty"` // is this package part of the standard Go library?
77         DepOnly       bool                  `json:",omitempty"` // package is only as a dependency, not explicitly listed
78         BinaryOnly    bool                  `json:",omitempty"` // package cannot be recompiled
79         Incomplete    bool                  `json:",omitempty"` // was there an error loading this package or dependencies?
80
81         // Stale and StaleReason remain here *only* for the list command.
82         // They are only initialized in preparation for list execution.
83         // The regular build determines staleness on the fly during action execution.
84         Stale       bool   `json:",omitempty"` // would 'go install' do anything for this package?
85         StaleReason string `json:",omitempty"` // why is Stale true?
86
87         // Source files
88         // If you add to this list you MUST add to p.AllFiles (below) too.
89         // Otherwise file name security lists will not apply to any new additions.
90         GoFiles         []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
91         CgoFiles        []string `json:",omitempty"` // .go source files that import "C"
92         CompiledGoFiles []string `json:",omitempty"` // .go output from running cgo on CgoFiles
93         IgnoredGoFiles  []string `json:",omitempty"` // .go source files ignored due to build constraints
94         CFiles          []string `json:",omitempty"` // .c source files
95         CXXFiles        []string `json:",omitempty"` // .cc, .cpp and .cxx source files
96         MFiles          []string `json:",omitempty"` // .m source files
97         HFiles          []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
98         FFiles          []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
99         SFiles          []string `json:",omitempty"` // .s source files
100         SwigFiles       []string `json:",omitempty"` // .swig files
101         SwigCXXFiles    []string `json:",omitempty"` // .swigcxx files
102         SysoFiles       []string `json:",omitempty"` // .syso system object files added to package
103
104         // Cgo directives
105         CgoCFLAGS    []string `json:",omitempty"` // cgo: flags for C compiler
106         CgoCPPFLAGS  []string `json:",omitempty"` // cgo: flags for C preprocessor
107         CgoCXXFLAGS  []string `json:",omitempty"` // cgo: flags for C++ compiler
108         CgoFFLAGS    []string `json:",omitempty"` // cgo: flags for Fortran compiler
109         CgoLDFLAGS   []string `json:",omitempty"` // cgo: flags for linker
110         CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
111
112         // Dependency information
113         Imports   []string          `json:",omitempty"` // import paths used by this package
114         ImportMap map[string]string `json:",omitempty"` // map from source import to ImportPath (identity entries omitted)
115         Deps      []string          `json:",omitempty"` // all (recursively) imported dependencies
116
117         // Error information
118         // Incomplete is above, packed into the other bools
119         Error      *PackageError   `json:",omitempty"` // error loading this package (not dependencies)
120         DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
121
122         // Test information
123         // If you add to this list you MUST add to p.AllFiles (below) too.
124         // Otherwise file name security lists will not apply to any new additions.
125         TestGoFiles  []string `json:",omitempty"` // _test.go files in package
126         TestImports  []string `json:",omitempty"` // imports from TestGoFiles
127         XTestGoFiles []string `json:",omitempty"` // _test.go files outside package
128         XTestImports []string `json:",omitempty"` // imports from XTestGoFiles
129 }
130
131 // AllFiles returns the names of all the files considered for the package.
132 // This is used for sanity and security checks, so we include all files,
133 // even IgnoredGoFiles, because some subcommands consider them.
134 // The go/build package filtered others out (like foo_wrongGOARCH.s)
135 // and that's OK.
136 func (p *Package) AllFiles() []string {
137         return str.StringList(
138                 p.GoFiles,
139                 p.CgoFiles,
140                 // no p.CompiledGoFiles, because they are from GoFiles or generated by us
141                 p.IgnoredGoFiles,
142                 p.CFiles,
143                 p.CXXFiles,
144                 p.MFiles,
145                 p.HFiles,
146                 p.FFiles,
147                 p.SFiles,
148                 p.SwigFiles,
149                 p.SwigCXXFiles,
150                 p.SysoFiles,
151                 p.TestGoFiles,
152                 p.XTestGoFiles,
153         )
154 }
155
156 // Desc returns the package "description", for use in b.showOutput.
157 func (p *Package) Desc() string {
158         if p.ForTest != "" {
159                 return p.ImportPath + " [" + p.ForTest + ".test]"
160         }
161         return p.ImportPath
162 }
163
164 type PackageInternal struct {
165         // Unexported fields are not part of the public API.
166         Build             *build.Package
167         Imports           []*Package           // this package's direct imports
168         CompiledImports   []string             // additional Imports necessary when using CompiledGoFiles (all from standard library)
169         RawImports        []string             // this package's original imports as they appear in the text of the program
170         ForceLibrary      bool                 // this package is a library (even if named "main")
171         CmdlineFiles      bool                 // package built from files listed on command line
172         CmdlinePkg        bool                 // package listed on command line
173         CmdlinePkgLiteral bool                 // package listed as literal on command line (not via wildcard)
174         Local             bool                 // imported via local path (./ or ../)
175         LocalPrefix       string               // interpret ./ and ../ imports relative to this prefix
176         ExeName           string               // desired name for temporary executable
177         CoverMode         string               // preprocess Go source files with the coverage tool in this mode
178         CoverVars         map[string]*CoverVar // variables created by coverage analysis
179         OmitDebug         bool                 // tell linker not to write debug information
180         GobinSubdir       bool                 // install target would be subdir of GOBIN
181         BuildInfo         string               // add this info to package main
182         TestmainGo        *[]byte              // content for _testmain.go
183
184         Asmflags   []string // -asmflags for this package
185         Gcflags    []string // -gcflags for this package
186         Ldflags    []string // -ldflags for this package
187         Gccgoflags []string // -gccgoflags for this package
188 }
189
190 // A NoGoError indicates that no Go files for the package were applicable to the
191 // build for that package.
192 //
193 // That may be because there were no files whatsoever, or because all files were
194 // excluded, or because all non-excluded files were test sources.
195 type NoGoError struct {
196         Package *Package
197 }
198
199 func (e *NoGoError) Error() string {
200         if len(e.Package.constraintIgnoredGoFiles()) > 0 {
201                 // Go files exist, but they were ignored due to build constraints.
202                 return "build constraints exclude all Go files in " + e.Package.Dir
203         }
204         if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
205                 // Test Go files exist, but we're not interested in them.
206                 // The double-negative is unfortunate but we want e.Package.Dir
207                 // to appear at the end of error message.
208                 return "no non-test Go files in " + e.Package.Dir
209         }
210         return "no Go files in " + e.Package.Dir
211 }
212
213 // setLoadPackageDataError presents an error found when loading package data
214 // as a *PackageError. It has special cases for some common errors to improve
215 // messages shown to users and reduce redundancy.
216 //
217 // setLoadPackageDataError returns true if it's safe to load information about
218 // imported packages, for example, if there was a parse error loading imports
219 // in one file, but other files are okay.
220 func (p *Package) setLoadPackageDataError(err error, path string, stk *ImportStack) {
221         // Include the path on the import stack unless the error includes it already.
222         errHasPath := false
223         if impErr, ok := err.(ImportPathError); ok && impErr.ImportPath() == path {
224                 errHasPath = true
225         } else if matchErr, ok := err.(*search.MatchError); ok && matchErr.Match.Pattern() == path {
226                 errHasPath = true
227                 if matchErr.Match.IsLiteral() {
228                         // The error has a pattern has a pattern similar to the import path.
229                         // It may be slightly different (./foo matching example.com/foo),
230                         // but close enough to seem redundant.
231                         // Unwrap the error so we don't show the pattern.
232                         err = matchErr.Err
233                 }
234         }
235         var errStk []string
236         if errHasPath {
237                 errStk = stk.Copy()
238         } else {
239                 stk.Push(path)
240                 errStk = stk.Copy()
241                 stk.Pop()
242         }
243
244         // Replace (possibly wrapped) *build.NoGoError with *load.NoGoError.
245         // The latter is more specific about the cause.
246         var nogoErr *build.NoGoError
247         if errors.As(err, &nogoErr) {
248                 if p.Dir == "" && nogoErr.Dir != "" {
249                         p.Dir = nogoErr.Dir
250                 }
251                 err = &NoGoError{Package: p}
252         }
253
254         // Take only the first error from a scanner.ErrorList. PackageError only
255         // has room for one position, so we report the first error with a position
256         // instead of all of the errors without a position.
257         var pos string
258         if scanErr, ok := err.(scanner.ErrorList); ok && len(scanErr) > 0 {
259                 scanPos := scanErr[0].Pos
260                 scanPos.Filename = base.ShortPath(scanPos.Filename)
261                 pos = scanPos.String()
262                 err = errors.New(scanErr[0].Msg)
263         }
264
265         p.Error = &PackageError{
266                 ImportStack: errStk,
267                 Pos:         pos,
268                 Err:         err,
269         }
270 }
271
272 // Resolve returns the resolved version of imports,
273 // which should be p.TestImports or p.XTestImports, NOT p.Imports.
274 // The imports in p.TestImports and p.XTestImports are not recursively
275 // loaded during the initial load of p, so they list the imports found in
276 // the source file, but most processing should be over the vendor-resolved
277 // import paths. We do this resolution lazily both to avoid file system work
278 // and because the eventual real load of the test imports (during 'go test')
279 // can produce better error messages if it starts with the original paths.
280 // The initial load of p loads all the non-test imports and rewrites
281 // the vendored paths, so nothing should ever call p.vendored(p.Imports).
282 func (p *Package) Resolve(imports []string) []string {
283         if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
284                 panic("internal error: p.Resolve(p.Imports) called")
285         }
286         seen := make(map[string]bool)
287         var all []string
288         for _, path := range imports {
289                 path = ResolveImportPath(p, path)
290                 if !seen[path] {
291                         seen[path] = true
292                         all = append(all, path)
293                 }
294         }
295         sort.Strings(all)
296         return all
297 }
298
299 // CoverVar holds the name of the generated coverage variables targeting the named file.
300 type CoverVar struct {
301         File string // local file name
302         Var  string // name of count struct
303 }
304
305 func (p *Package) copyBuild(pp *build.Package) {
306         p.Internal.Build = pp
307
308         if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
309                 old := pp.PkgTargetRoot
310                 pp.PkgRoot = cfg.BuildPkgdir
311                 pp.PkgTargetRoot = cfg.BuildPkgdir
312                 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
313         }
314
315         p.Dir = pp.Dir
316         p.ImportPath = pp.ImportPath
317         p.ImportComment = pp.ImportComment
318         p.Name = pp.Name
319         p.Doc = pp.Doc
320         p.Root = pp.Root
321         p.ConflictDir = pp.ConflictDir
322         p.BinaryOnly = pp.BinaryOnly
323
324         // TODO? Target
325         p.Goroot = pp.Goroot
326         p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath)
327         p.GoFiles = pp.GoFiles
328         p.CgoFiles = pp.CgoFiles
329         p.IgnoredGoFiles = pp.IgnoredGoFiles
330         p.CFiles = pp.CFiles
331         p.CXXFiles = pp.CXXFiles
332         p.MFiles = pp.MFiles
333         p.HFiles = pp.HFiles
334         p.FFiles = pp.FFiles
335         p.SFiles = pp.SFiles
336         p.SwigFiles = pp.SwigFiles
337         p.SwigCXXFiles = pp.SwigCXXFiles
338         p.SysoFiles = pp.SysoFiles
339         if cfg.BuildMSan {
340                 // There's no way for .syso files to be built both with and without
341                 // support for memory sanitizer. Assume they are built without,
342                 // and drop them.
343                 p.SysoFiles = nil
344         }
345         p.CgoCFLAGS = pp.CgoCFLAGS
346         p.CgoCPPFLAGS = pp.CgoCPPFLAGS
347         p.CgoCXXFLAGS = pp.CgoCXXFLAGS
348         p.CgoFFLAGS = pp.CgoFFLAGS
349         p.CgoLDFLAGS = pp.CgoLDFLAGS
350         p.CgoPkgConfig = pp.CgoPkgConfig
351         // We modify p.Imports in place, so make copy now.
352         p.Imports = make([]string, len(pp.Imports))
353         copy(p.Imports, pp.Imports)
354         p.Internal.RawImports = pp.Imports
355         p.TestGoFiles = pp.TestGoFiles
356         p.TestImports = pp.TestImports
357         p.XTestGoFiles = pp.XTestGoFiles
358         p.XTestImports = pp.XTestImports
359         if IgnoreImports {
360                 p.Imports = nil
361                 p.Internal.RawImports = nil
362                 p.TestImports = nil
363                 p.XTestImports = nil
364         }
365 }
366
367 // A PackageError describes an error loading information about a package.
368 type PackageError struct {
369         ImportStack      []string // shortest path from package named on command line to this one
370         Pos              string   // position of error
371         Err              error    // the error itself
372         IsImportCycle    bool     // the error is an import cycle
373         Hard             bool     // whether the error is soft or hard; soft errors are ignored in some places
374         alwaysPrintStack bool     // whether to always print the ImportStack
375 }
376
377 func (p *PackageError) Error() string {
378         if p.Pos != "" && (len(p.ImportStack) == 0 || !p.alwaysPrintStack) {
379                 // Omit import stack. The full path to the file where the error
380                 // is the most important thing.
381                 return p.Pos + ": " + p.Err.Error()
382         }
383
384         // If the error is an ImportPathError, and the last path on the stack appears
385         // in the error message, omit that path from the stack to avoid repetition.
386         // If an ImportPathError wraps another ImportPathError that matches the
387         // last path on the stack, we don't omit the path. An error like
388         // "package A imports B: error loading C caused by B" would not be clearer
389         // if "imports B" were omitted.
390         if len(p.ImportStack) == 0 {
391                 return p.Err.Error()
392         }
393         var optpos string
394         if p.Pos != "" {
395                 optpos = "\n\t" + p.Pos
396         }
397         return "package " + strings.Join(p.ImportStack, "\n\timports ") + optpos + ": " + p.Err.Error()
398 }
399
400 func (p *PackageError) Unwrap() error { return p.Err }
401
402 // PackageError implements MarshalJSON so that Err is marshaled as a string
403 // and non-essential fields are omitted.
404 func (p *PackageError) MarshalJSON() ([]byte, error) {
405         perr := struct {
406                 ImportStack []string
407                 Pos         string
408                 Err         string
409         }{p.ImportStack, p.Pos, p.Err.Error()}
410         return json.Marshal(perr)
411 }
412
413 // ImportPathError is a type of error that prevents a package from being loaded
414 // for a given import path. When such a package is loaded, a *Package is
415 // returned with Err wrapping an ImportPathError: the error is attached to
416 // the imported package, not the importing package.
417 //
418 // The string returned by ImportPath must appear in the string returned by
419 // Error. Errors that wrap ImportPathError (such as PackageError) may omit
420 // the import path.
421 type ImportPathError interface {
422         error
423         ImportPath() string
424 }
425
426 type importError struct {
427         importPath string
428         err        error // created with fmt.Errorf
429 }
430
431 var _ ImportPathError = (*importError)(nil)
432
433 func ImportErrorf(path, format string, args ...interface{}) ImportPathError {
434         err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
435         if errStr := err.Error(); !strings.Contains(errStr, path) {
436                 panic(fmt.Sprintf("path %q not in error %q", path, errStr))
437         }
438         return err
439 }
440
441 func (e *importError) Error() string {
442         return e.err.Error()
443 }
444
445 func (e *importError) Unwrap() error {
446         // Don't return e.err directly, since we're only wrapping an error if %w
447         // was passed to ImportErrorf.
448         return errors.Unwrap(e.err)
449 }
450
451 func (e *importError) ImportPath() string {
452         return e.importPath
453 }
454
455 // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended.
456 // The import path of a test package is the import path of the corresponding
457 // non-test package with the suffix "_test" added.
458 type ImportStack []string
459
460 func (s *ImportStack) Push(p string) {
461         *s = append(*s, p)
462 }
463
464 func (s *ImportStack) Pop() {
465         *s = (*s)[0 : len(*s)-1]
466 }
467
468 func (s *ImportStack) Copy() []string {
469         return append([]string{}, *s...)
470 }
471
472 // shorterThan reports whether sp is shorter than t.
473 // We use this to record the shortest import sequence
474 // that leads to a particular package.
475 func (sp *ImportStack) shorterThan(t []string) bool {
476         s := *sp
477         if len(s) != len(t) {
478                 return len(s) < len(t)
479         }
480         // If they are the same length, settle ties using string ordering.
481         for i := range s {
482                 if s[i] != t[i] {
483                         return s[i] < t[i]
484                 }
485         }
486         return false // they are equal
487 }
488
489 // packageCache is a lookup cache for LoadImport,
490 // so that if we look up a package multiple times
491 // we return the same pointer each time.
492 var packageCache = map[string]*Package{}
493
494 // ClearPackageCache clears the in-memory package cache and the preload caches.
495 // It is only for use by GOPATH-based "go get".
496 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
497 func ClearPackageCache() {
498         for name := range packageCache {
499                 delete(packageCache, name)
500         }
501         resolvedImportCache.Clear()
502         packageDataCache.Clear()
503 }
504
505 // ClearPackageCachePartial clears packages with the given import paths from the
506 // in-memory package cache and the preload caches. It is only for use by
507 // GOPATH-based "go get".
508 // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
509 func ClearPackageCachePartial(args []string) {
510         shouldDelete := make(map[string]bool)
511         for _, arg := range args {
512                 shouldDelete[arg] = true
513                 if p := packageCache[arg]; p != nil {
514                         delete(packageCache, arg)
515                 }
516         }
517         resolvedImportCache.DeleteIf(func(key interface{}) bool {
518                 return shouldDelete[key.(importSpec).path]
519         })
520         packageDataCache.DeleteIf(func(key interface{}) bool {
521                 return shouldDelete[key.(string)]
522         })
523 }
524
525 // ReloadPackageNoFlags is like LoadImport but makes sure
526 // not to use the package cache.
527 // It is only for use by GOPATH-based "go get".
528 // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
529 func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package {
530         p := packageCache[arg]
531         if p != nil {
532                 delete(packageCache, arg)
533                 resolvedImportCache.DeleteIf(func(key interface{}) bool {
534                         return key.(importSpec).path == p.ImportPath
535                 })
536                 packageDataCache.Delete(p.ImportPath)
537         }
538         return LoadImport(arg, base.Cwd, nil, stk, nil, 0)
539 }
540
541 // dirToImportPath returns the pseudo-import path we use for a package
542 // outside the Go path. It begins with _/ and then contains the full path
543 // to the directory. If the package lives in c:\home\gopher\my\pkg then
544 // the pseudo-import path is _/c_/home/gopher/my/pkg.
545 // Using a pseudo-import path like this makes the ./ imports no longer
546 // a special case, so that all the code to deal with ordinary imports works
547 // automatically.
548 func dirToImportPath(dir string) string {
549         return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
550 }
551
552 func makeImportValid(r rune) rune {
553         // Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
554         const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
555         if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
556                 return '_'
557         }
558         return r
559 }
560
561 // Mode flags for loadImport and download (in get.go).
562 const (
563         // ResolveImport means that loadImport should do import path expansion.
564         // That is, ResolveImport means that the import path came from
565         // a source file and has not been expanded yet to account for
566         // vendoring or possible module adjustment.
567         // Every import path should be loaded initially with ResolveImport,
568         // and then the expanded version (for example with the /vendor/ in it)
569         // gets recorded as the canonical import path. At that point, future loads
570         // of that package must not pass ResolveImport, because
571         // disallowVendor will reject direct use of paths containing /vendor/.
572         ResolveImport = 1 << iota
573
574         // ResolveModule is for download (part of "go get") and indicates
575         // that the module adjustment should be done, but not vendor adjustment.
576         ResolveModule
577
578         // GetTestDeps is for download (part of "go get") and indicates
579         // that test dependencies should be fetched too.
580         GetTestDeps
581 )
582
583 // LoadImport scans the directory named by path, which must be an import path,
584 // but possibly a local import path (an absolute file system path or one beginning
585 // with ./ or ../). A local relative path is interpreted relative to srcDir.
586 // It returns a *Package describing the package found in that directory.
587 // LoadImport does not set tool flags and should only be used by
588 // this package, as part of a bigger load operation, and by GOPATH-based "go get".
589 // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
590 func LoadImport(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
591         return loadImport(nil, path, srcDir, parent, stk, importPos, mode)
592 }
593
594 func loadImport(pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
595         if path == "" {
596                 panic("LoadImport called with empty package path")
597         }
598
599         var parentPath, parentRoot string
600         parentIsStd := false
601         if parent != nil {
602                 parentPath = parent.ImportPath
603                 parentRoot = parent.Root
604                 parentIsStd = parent.Standard
605         }
606         bp, loaded, err := loadPackageData(path, parentPath, srcDir, parentRoot, parentIsStd, mode)
607         if loaded && pre != nil && !IgnoreImports {
608                 pre.preloadImports(bp.Imports, bp)
609         }
610         if bp == nil {
611                 if importErr, ok := err.(ImportPathError); !ok || importErr.ImportPath() != path {
612                         // Only add path to the error's import stack if it's not already present on the error.
613                         stk.Push(path)
614                         defer stk.Pop()
615                 }
616                 return &Package{
617                         PackagePublic: PackagePublic{
618                                 ImportPath: path,
619                                 Error: &PackageError{
620                                         ImportStack: stk.Copy(),
621                                         Err:         err,
622                                 },
623                         },
624                 }
625         }
626
627         importPath := bp.ImportPath
628         p := packageCache[importPath]
629         if p != nil {
630                 stk.Push(path)
631                 p = reusePackage(p, stk)
632                 stk.Pop()
633         } else {
634                 p = new(Package)
635                 p.Internal.Local = build.IsLocalImport(path)
636                 p.ImportPath = importPath
637                 packageCache[importPath] = p
638
639                 // Load package.
640                 // loadPackageData may return bp != nil even if an error occurs,
641                 // in order to return partial information.
642                 p.load(path, stk, bp, err)
643                 // Add position information unless this is a NoGoError or an ImportCycle error.
644                 // Import cycles deserve special treatment.
645                 var g *build.NoGoError
646                 if p.Error != nil && p.Error.Pos == "" && !errors.As(err, &g) && !p.Error.IsImportCycle {
647                         p = setErrorPos(p, importPos)
648                 }
649
650                 if !cfg.ModulesEnabled && path != cleanImport(path) {
651                         p.Error = &PackageError{
652                                 ImportStack: stk.Copy(),
653                                 Err:         ImportErrorf(path, "non-canonical import path %q: should be %q", path, pathpkg.Clean(path)),
654                         }
655                         p.Incomplete = true
656                         setErrorPos(p, importPos)
657                 }
658         }
659
660         // Checked on every import because the rules depend on the code doing the importing.
661         if perr := disallowInternal(srcDir, parent, parentPath, p, stk); perr != p {
662                 return setErrorPos(perr, importPos)
663         }
664         if mode&ResolveImport != 0 {
665                 if perr := disallowVendor(srcDir, path, parentPath, p, stk); perr != p {
666                         return setErrorPos(perr, importPos)
667                 }
668         }
669
670         if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
671                 perr := *p
672                 perr.Error = &PackageError{
673                         ImportStack: stk.Copy(),
674                         Err:         ImportErrorf(path, "import %q is a program, not an importable package", path),
675                 }
676                 return setErrorPos(&perr, importPos)
677         }
678
679         if p.Internal.Local && parent != nil && !parent.Internal.Local {
680                 perr := *p
681                 var err error
682                 if path == "." {
683                         err = ImportErrorf(path, "%s: cannot import current directory", path)
684                 } else {
685                         err = ImportErrorf(path, "local import %q in non-local package", path)
686                 }
687                 perr.Error = &PackageError{
688                         ImportStack: stk.Copy(),
689                         Err:         err,
690                 }
691                 return setErrorPos(&perr, importPos)
692         }
693
694         return p
695 }
696
697 func setErrorPos(p *Package, importPos []token.Position) *Package {
698         if len(importPos) > 0 {
699                 pos := importPos[0]
700                 pos.Filename = base.ShortPath(pos.Filename)
701                 p.Error.Pos = pos.String()
702         }
703         return p
704 }
705
706 // loadPackageData loads information needed to construct a *Package. The result
707 // is cached, and later calls to loadPackageData for the same package will return
708 // the same data.
709 //
710 // loadPackageData returns a non-nil package even if err is non-nil unless
711 // the package path is malformed (for example, the path contains "mod/" or "@").
712 //
713 // loadPackageData returns a boolean, loaded, which is true if this is the
714 // first time the package was loaded. Callers may preload imports in this case.
715 func loadPackageData(path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
716         if path == "" {
717                 panic("loadPackageData called with empty package path")
718         }
719
720         if strings.HasPrefix(path, "mod/") {
721                 // Paths beginning with "mod/" might accidentally
722                 // look in the module cache directory tree in $GOPATH/pkg/mod/.
723                 // This prefix is owned by the Go core for possible use in the
724                 // standard library (since it does not begin with a domain name),
725                 // so it's OK to disallow entirely.
726                 return nil, false, fmt.Errorf("disallowed import path %q", path)
727         }
728
729         if strings.Contains(path, "@") {
730                 if cfg.ModulesEnabled {
731                         return nil, false, errors.New("can only use path@version syntax with 'go get'")
732                 } else {
733                         return nil, false, errors.New("cannot use path@version syntax in GOPATH mode")
734                 }
735         }
736
737         // Determine canonical package path and directory.
738         // For a local import the identifier is the pseudo-import path
739         // we create from the full directory to the package.
740         // Otherwise it is the usual import path.
741         // For vendored imports, it is the expanded form.
742         //
743         // Note that when modules are enabled, local import paths are normally
744         // canonicalized by modload.ImportPaths before now. However, if there's an
745         // error resolving a local path, it will be returned untransformed
746         // so that 'go list -e' reports something useful.
747         importKey := importSpec{
748                 path:        path,
749                 parentPath:  parentPath,
750                 parentDir:   parentDir,
751                 parentRoot:  parentRoot,
752                 parentIsStd: parentIsStd,
753                 mode:        mode,
754         }
755         r := resolvedImportCache.Do(importKey, func() interface{} {
756                 var r resolvedImport
757                 if build.IsLocalImport(path) {
758                         r.dir = filepath.Join(parentDir, path)
759                         r.path = dirToImportPath(r.dir)
760                 } else if cfg.ModulesEnabled {
761                         r.dir, r.path, r.err = ModLookup(parentPath, parentIsStd, path)
762                 } else if mode&ResolveImport != 0 {
763                         // We do our own path resolution, because we want to
764                         // find out the key to use in packageCache without the
765                         // overhead of repeated calls to buildContext.Import.
766                         // The code is also needed in a few other places anyway.
767                         r.path = resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
768                 } else if mode&ResolveModule != 0 {
769                         r.path = moduleImportPath(path, parentPath, parentDir, parentRoot)
770                 }
771                 if r.path == "" {
772                         r.path = path
773                 }
774                 return r
775         }).(resolvedImport)
776         // Invariant: r.path is set to the resolved import path. If the path cannot
777         // be resolved, r.path is set to path, the source import path.
778         // r.path is never empty.
779
780         // Load the package from its directory. If we already found the package's
781         // directory when resolving its import path, use that.
782         data := packageDataCache.Do(r.path, func() interface{} {
783                 loaded = true
784                 var data packageData
785                 if r.dir != "" {
786                         var buildMode build.ImportMode
787                         if !cfg.ModulesEnabled {
788                                 buildMode = build.ImportComment
789                         }
790                         data.p, data.err = cfg.BuildContext.ImportDir(r.dir, buildMode)
791                         if data.p.Root == "" && cfg.ModulesEnabled {
792                                 if info := ModPackageModuleInfo(path); info != nil {
793                                         data.p.Root = info.Dir
794                                 }
795                         }
796                 } else if r.err != nil {
797                         data.p = new(build.Package)
798                         data.err = r.err
799                 } else if cfg.ModulesEnabled && path != "unsafe" {
800                         data.p = new(build.Package)
801                         data.err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", r.path)
802                 } else {
803                         buildMode := build.ImportComment
804                         if mode&ResolveImport == 0 || r.path != path {
805                                 // Not vendoring, or we already found the vendored path.
806                                 buildMode |= build.IgnoreVendor
807                         }
808                         data.p, data.err = cfg.BuildContext.Import(r.path, parentDir, buildMode)
809                 }
810                 data.p.ImportPath = r.path
811
812                 // Set data.p.BinDir in cases where go/build.Context.Import
813                 // may give us a path we don't want.
814                 if !data.p.Goroot {
815                         if cfg.GOBIN != "" {
816                                 data.p.BinDir = cfg.GOBIN
817                         } else if cfg.ModulesEnabled {
818                                 data.p.BinDir = ModBinDir()
819                         }
820                 }
821
822                 if !cfg.ModulesEnabled && data.err == nil &&
823                         data.p.ImportComment != "" && data.p.ImportComment != path &&
824                         !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
825                         data.err = fmt.Errorf("code in directory %s expects import %q", data.p.Dir, data.p.ImportComment)
826                 }
827                 return data
828         }).(packageData)
829
830         return data.p, loaded, data.err
831 }
832
833 // importSpec describes an import declaration in source code. It is used as a
834 // cache key for resolvedImportCache.
835 type importSpec struct {
836         path                              string
837         parentPath, parentDir, parentRoot string
838         parentIsStd                       bool
839         mode                              int
840 }
841
842 // resolvedImport holds a canonical identifier for a package. It may also contain
843 // a path to the package's directory and an error if one occurred. resolvedImport
844 // is the value type in resolvedImportCache.
845 type resolvedImport struct {
846         path, dir string
847         err       error
848 }
849
850 // packageData holds information loaded from a package. It is the value type
851 // in packageDataCache.
852 type packageData struct {
853         p   *build.Package
854         err error
855 }
856
857 // resolvedImportCache maps import strings (importSpec) to canonical package names
858 // (resolvedImport).
859 var resolvedImportCache par.Cache
860
861 // packageDataCache maps canonical package names (string) to package metadata
862 // (packageData).
863 var packageDataCache par.Cache
864
865 // preloadWorkerCount is the number of concurrent goroutines that can load
866 // packages. Experimentally, there are diminishing returns with more than
867 // 4 workers. This was measured on the following machines.
868 //
869 // * MacBookPro with a 4-core Intel Core i7 CPU
870 // * Linux workstation with 6-core Intel Xeon CPU
871 // * Linux workstation with 24-core Intel Xeon CPU
872 //
873 // It is very likely (though not confirmed) that this workload is limited
874 // by memory bandwidth. We don't have a good way to determine the number of
875 // workers that would saturate the bus though, so runtime.GOMAXPROCS
876 // seems like a reasonable default.
877 var preloadWorkerCount = runtime.GOMAXPROCS(0)
878
879 // preload holds state for managing concurrent preloading of package data.
880 //
881 // A preload should be created with newPreload before loading a large
882 // package graph. flush must be called when package loading is complete
883 // to ensure preload goroutines are no longer active. This is necessary
884 // because of global mutable state that cannot safely be read and written
885 // concurrently. In particular, packageDataCache may be cleared by "go get"
886 // in GOPATH mode, and modload.loaded (accessed via ModLookup) may be
887 // modified by modload.ImportPaths (ModImportPaths).
888 type preload struct {
889         cancel chan struct{}
890         sema   chan struct{}
891 }
892
893 // newPreload creates a new preloader. flush must be called later to avoid
894 // accessing global state while it is being modified.
895 func newPreload() *preload {
896         pre := &preload{
897                 cancel: make(chan struct{}),
898                 sema:   make(chan struct{}, preloadWorkerCount),
899         }
900         return pre
901 }
902
903 // preloadMatches loads data for package paths matched by patterns.
904 // When preloadMatches returns, some packages may not be loaded yet, but
905 // loadPackageData and loadImport are always safe to call.
906 func (pre *preload) preloadMatches(matches []*search.Match) {
907         for _, m := range matches {
908                 for _, pkg := range m.Pkgs {
909                         select {
910                         case <-pre.cancel:
911                                 return
912                         case pre.sema <- struct{}{}:
913                                 go func(pkg string) {
914                                         mode := 0 // don't use vendoring or module import resolution
915                                         bp, loaded, err := loadPackageData(pkg, "", base.Cwd, "", false, mode)
916                                         <-pre.sema
917                                         if bp != nil && loaded && err == nil && !IgnoreImports {
918                                                 pre.preloadImports(bp.Imports, bp)
919                                         }
920                                 }(pkg)
921                         }
922                 }
923         }
924 }
925
926 // preloadImports queues a list of imports for preloading.
927 // When preloadImports returns, some packages may not be loaded yet,
928 // but loadPackageData and loadImport are always safe to call.
929 func (pre *preload) preloadImports(imports []string, parent *build.Package) {
930         parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
931         for _, path := range imports {
932                 if path == "C" || path == "unsafe" {
933                         continue
934                 }
935                 select {
936                 case <-pre.cancel:
937                         return
938                 case pre.sema <- struct{}{}:
939                         go func(path string) {
940                                 bp, loaded, err := loadPackageData(path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
941                                 <-pre.sema
942                                 if bp != nil && loaded && err == nil && !IgnoreImports {
943                                         pre.preloadImports(bp.Imports, bp)
944                                 }
945                         }(path)
946                 }
947         }
948 }
949
950 // flush stops pending preload operations. flush blocks until preload calls to
951 // loadPackageData have completed. The preloader will not make any new calls
952 // to loadPackageData.
953 func (pre *preload) flush() {
954         close(pre.cancel)
955         for i := 0; i < preloadWorkerCount; i++ {
956                 pre.sema <- struct{}{}
957         }
958 }
959
960 func cleanImport(path string) string {
961         orig := path
962         path = pathpkg.Clean(path)
963         if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
964                 path = "./" + path
965         }
966         return path
967 }
968
969 var isDirCache par.Cache
970
971 func isDir(path string) bool {
972         return isDirCache.Do(path, func() interface{} {
973                 fi, err := os.Stat(path)
974                 return err == nil && fi.IsDir()
975         }).(bool)
976 }
977
978 // ResolveImportPath returns the true meaning of path when it appears in parent.
979 // There are two different resolutions applied.
980 // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
981 // If vendor expansion doesn't trigger, then the path is also subject to
982 // Go 1.11 module legacy conversion (golang.org/issue/25069).
983 func ResolveImportPath(parent *Package, path string) (found string) {
984         var parentPath, parentDir, parentRoot string
985         parentIsStd := false
986         if parent != nil {
987                 parentPath = parent.ImportPath
988                 parentDir = parent.Dir
989                 parentRoot = parent.Root
990                 parentIsStd = parent.Standard
991         }
992         return resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
993 }
994
995 func resolveImportPath(path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
996         if cfg.ModulesEnabled {
997                 if _, p, e := ModLookup(parentPath, parentIsStd, path); e == nil {
998                         return p
999                 }
1000                 return path
1001         }
1002         found = vendoredImportPath(path, parentPath, parentDir, parentRoot)
1003         if found != path {
1004                 return found
1005         }
1006         return moduleImportPath(path, parentPath, parentDir, parentRoot)
1007 }
1008
1009 // dirAndRoot returns the source directory and workspace root
1010 // for the package p, guaranteeing that root is a path prefix of dir.
1011 func dirAndRoot(path string, dir, root string) (string, string) {
1012         origDir, origRoot := dir, root
1013         dir = filepath.Clean(dir)
1014         root = filepath.Join(root, "src")
1015         if !str.HasFilePathPrefix(dir, root) || path != "command-line-arguments" && filepath.Join(root, path) != dir {
1016                 // Look for symlinks before reporting error.
1017                 dir = expandPath(dir)
1018                 root = expandPath(root)
1019         }
1020
1021         if !str.HasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator || path != "command-line-arguments" && !build.IsLocalImport(path) && filepath.Join(root, path) != dir {
1022                 base.Fatalf("unexpected directory layout:\n"+
1023                         "       import path: %s\n"+
1024                         "       root: %s\n"+
1025                         "       dir: %s\n"+
1026                         "       expand root: %s\n"+
1027                         "       expand dir: %s\n"+
1028                         "       separator: %s",
1029                         path,
1030                         filepath.Join(origRoot, "src"),
1031                         filepath.Clean(origDir),
1032                         origRoot,
1033                         origDir,
1034                         string(filepath.Separator))
1035         }
1036
1037         return dir, root
1038 }
1039
1040 // vendoredImportPath returns the vendor-expansion of path when it appears in parent.
1041 // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
1042 // x/vendor/path, vendor/path, or else stay path if none of those exist.
1043 // vendoredImportPath returns the expanded path or, if no expansion is found, the original.
1044 func vendoredImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1045         if parentRoot == "" {
1046                 return path
1047         }
1048
1049         dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1050
1051         vpath := "vendor/" + path
1052         for i := len(dir); i >= len(root); i-- {
1053                 if i < len(dir) && dir[i] != filepath.Separator {
1054                         continue
1055                 }
1056                 // Note: checking for the vendor directory before checking
1057                 // for the vendor/path directory helps us hit the
1058                 // isDir cache more often. It also helps us prepare a more useful
1059                 // list of places we looked, to report when an import is not found.
1060                 if !isDir(filepath.Join(dir[:i], "vendor")) {
1061                         continue
1062                 }
1063                 targ := filepath.Join(dir[:i], vpath)
1064                 if isDir(targ) && hasGoFiles(targ) {
1065                         importPath := parentPath
1066                         if importPath == "command-line-arguments" {
1067                                 // If parent.ImportPath is 'command-line-arguments'.
1068                                 // set to relative directory to root (also chopped root directory)
1069                                 importPath = dir[len(root)+1:]
1070                         }
1071                         // We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
1072                         // We know the import path for parent's dir.
1073                         // We chopped off some number of path elements and
1074                         // added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
1075                         // Now we want to know the import path for that directory.
1076                         // Construct it by chopping the same number of path elements
1077                         // (actually the same number of bytes) from parent's import path
1078                         // and then append /vendor/path.
1079                         chopped := len(dir) - i
1080                         if chopped == len(importPath)+1 {
1081                                 // We walked up from c:\gopath\src\foo\bar
1082                                 // and found c:\gopath\src\vendor\path.
1083                                 // We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
1084                                 // Use "vendor/path" without any prefix.
1085                                 return vpath
1086                         }
1087                         return importPath[:len(importPath)-chopped] + "/" + vpath
1088                 }
1089         }
1090         return path
1091 }
1092
1093 var (
1094         modulePrefix   = []byte("\nmodule ")
1095         goModPathCache par.Cache
1096 )
1097
1098 // goModPath returns the module path in the go.mod in dir, if any.
1099 func goModPath(dir string) (path string) {
1100         return goModPathCache.Do(dir, func() interface{} {
1101                 data, err := ioutil.ReadFile(filepath.Join(dir, "go.mod"))
1102                 if err != nil {
1103                         return ""
1104                 }
1105                 var i int
1106                 if bytes.HasPrefix(data, modulePrefix[1:]) {
1107                         i = 0
1108                 } else {
1109                         i = bytes.Index(data, modulePrefix)
1110                         if i < 0 {
1111                                 return ""
1112                         }
1113                         i++
1114                 }
1115                 line := data[i:]
1116
1117                 // Cut line at \n, drop trailing \r if present.
1118                 if j := bytes.IndexByte(line, '\n'); j >= 0 {
1119                         line = line[:j]
1120                 }
1121                 if line[len(line)-1] == '\r' {
1122                         line = line[:len(line)-1]
1123                 }
1124                 line = line[len("module "):]
1125
1126                 // If quoted, unquote.
1127                 path = strings.TrimSpace(string(line))
1128                 if path != "" && path[0] == '"' {
1129                         s, err := strconv.Unquote(path)
1130                         if err != nil {
1131                                 return ""
1132                         }
1133                         path = s
1134                 }
1135                 return path
1136         }).(string)
1137 }
1138
1139 // findVersionElement returns the slice indices of the final version element /vN in path.
1140 // If there is no such element, it returns -1, -1.
1141 func findVersionElement(path string) (i, j int) {
1142         j = len(path)
1143         for i = len(path) - 1; i >= 0; i-- {
1144                 if path[i] == '/' {
1145                         if isVersionElement(path[i+1 : j]) {
1146                                 return i, j
1147                         }
1148                         j = i
1149                 }
1150         }
1151         return -1, -1
1152 }
1153
1154 // isVersionElement reports whether s is a well-formed path version element:
1155 // v2, v3, v10, etc, but not v0, v05, v1.
1156 func isVersionElement(s string) bool {
1157         if len(s) < 2 || s[0] != 'v' || s[1] == '0' || s[1] == '1' && len(s) == 2 {
1158                 return false
1159         }
1160         for i := 1; i < len(s); i++ {
1161                 if s[i] < '0' || '9' < s[i] {
1162                         return false
1163                 }
1164         }
1165         return true
1166 }
1167
1168 // moduleImportPath translates import paths found in go modules
1169 // back down to paths that can be resolved in ordinary builds.
1170 //
1171 // Define “new” code as code with a go.mod file in the same directory
1172 // or a parent directory. If an import in new code says x/y/v2/z but
1173 // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
1174 // then go build will read the import as x/y/z instead.
1175 // See golang.org/issue/25069.
1176 func moduleImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1177         if parentRoot == "" {
1178                 return path
1179         }
1180
1181         // If there are no vN elements in path, leave it alone.
1182         // (The code below would do the same, but only after
1183         // some other file system accesses that we can avoid
1184         // here by returning early.)
1185         if i, _ := findVersionElement(path); i < 0 {
1186                 return path
1187         }
1188
1189         dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1190
1191         // Consider dir and parents, up to and including root.
1192         for i := len(dir); i >= len(root); i-- {
1193                 if i < len(dir) && dir[i] != filepath.Separator {
1194                         continue
1195                 }
1196                 if goModPath(dir[:i]) != "" {
1197                         goto HaveGoMod
1198                 }
1199         }
1200         // This code is not in a tree with a go.mod,
1201         // so apply no changes to the path.
1202         return path
1203
1204 HaveGoMod:
1205         // This import is in a tree with a go.mod.
1206         // Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
1207         // if GOPATH/src/x/y/go.mod says module "x/y/v2",
1208
1209         // If x/y/v2/z exists, use it unmodified.
1210         if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
1211                 return path
1212         }
1213
1214         // Otherwise look for a go.mod supplying a version element.
1215         // Some version-like elements may appear in paths but not
1216         // be module versions; we skip over those to look for module
1217         // versions. For example the module m/v2 might have a
1218         // package m/v2/api/v1/foo.
1219         limit := len(path)
1220         for limit > 0 {
1221                 i, j := findVersionElement(path[:limit])
1222                 if i < 0 {
1223                         return path
1224                 }
1225                 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
1226                         if mpath := goModPath(bp.Dir); mpath != "" {
1227                                 // Found a valid go.mod file, so we're stopping the search.
1228                                 // If the path is m/v2/p and we found m/go.mod that says
1229                                 // "module m/v2", then we return "m/p".
1230                                 if mpath == path[:j] {
1231                                         return path[:i] + path[j:]
1232                                 }
1233                                 // Otherwise just return the original path.
1234                                 // We didn't find anything worth rewriting,
1235                                 // and the go.mod indicates that we should
1236                                 // not consider parent directories.
1237                                 return path
1238                         }
1239                 }
1240                 limit = i
1241         }
1242         return path
1243 }
1244
1245 // hasGoFiles reports whether dir contains any files with names ending in .go.
1246 // For a vendor check we must exclude directories that contain no .go files.
1247 // Otherwise it is not possible to vendor just a/b/c and still import the
1248 // non-vendored a/b. See golang.org/issue/13832.
1249 func hasGoFiles(dir string) bool {
1250         fis, _ := ioutil.ReadDir(dir)
1251         for _, fi := range fis {
1252                 if !fi.IsDir() && strings.HasSuffix(fi.Name(), ".go") {
1253                         return true
1254                 }
1255         }
1256         return false
1257 }
1258
1259 // reusePackage reuses package p to satisfy the import at the top
1260 // of the import stack stk. If this use causes an import loop,
1261 // reusePackage updates p's error information to record the loop.
1262 func reusePackage(p *Package, stk *ImportStack) *Package {
1263         // We use p.Internal.Imports==nil to detect a package that
1264         // is in the midst of its own loadPackage call
1265         // (all the recursion below happens before p.Internal.Imports gets set).
1266         if p.Internal.Imports == nil {
1267                 if p.Error == nil {
1268                         p.Error = &PackageError{
1269                                 ImportStack:   stk.Copy(),
1270                                 Err:           errors.New("import cycle not allowed"),
1271                                 IsImportCycle: true,
1272                         }
1273                 }
1274                 p.Incomplete = true
1275         }
1276         // Don't rewrite the import stack in the error if we have an import cycle.
1277         // If we do, we'll lose the path that describes the cycle.
1278         if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
1279                 p.Error.ImportStack = stk.Copy()
1280         }
1281         return p
1282 }
1283
1284 // disallowInternal checks that srcDir (containing package importerPath, if non-empty)
1285 // is allowed to import p.
1286 // If the import is allowed, disallowInternal returns the original package p.
1287 // If not, it returns a new package containing just an appropriate error.
1288 func disallowInternal(srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *Package {
1289         // golang.org/s/go14internal:
1290         // An import of a path containing the element “internal”
1291         // is disallowed if the importing code is outside the tree
1292         // rooted at the parent of the “internal” directory.
1293
1294         // There was an error loading the package; stop here.
1295         if p.Error != nil {
1296                 return p
1297         }
1298
1299         // The generated 'testmain' package is allowed to access testing/internal/...,
1300         // as if it were generated into the testing directory tree
1301         // (it's actually in a temporary directory outside any Go tree).
1302         // This cleans up a former kludge in passing functionality to the testing package.
1303         if str.HasPathPrefix(p.ImportPath, "testing/internal") && importerPath == "testmain" {
1304                 return p
1305         }
1306
1307         // We can't check standard packages with gccgo.
1308         if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
1309                 return p
1310         }
1311
1312         // The sort package depends on internal/reflectlite, but during bootstrap
1313         // the path rewriting causes the normal internal checks to fail.
1314         // Instead, just ignore the internal rules during bootstrap.
1315         if p.Standard && strings.HasPrefix(importerPath, "bootstrap/") {
1316                 return p
1317         }
1318
1319         // importerPath is empty: we started
1320         // with a name given on the command line, not an
1321         // import. Anything listed on the command line is fine.
1322         if importerPath == "" {
1323                 return p
1324         }
1325
1326         // Check for "internal" element: three cases depending on begin of string and/or end of string.
1327         i, ok := findInternal(p.ImportPath)
1328         if !ok {
1329                 return p
1330         }
1331
1332         // Internal is present.
1333         // Map import path back to directory corresponding to parent of internal.
1334         if i > 0 {
1335                 i-- // rewind over slash in ".../internal"
1336         }
1337
1338         if p.Module == nil {
1339                 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
1340
1341                 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1342                         return p
1343                 }
1344
1345                 // Look for symlinks before reporting error.
1346                 srcDir = expandPath(srcDir)
1347                 parent = expandPath(parent)
1348                 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1349                         return p
1350                 }
1351         } else {
1352                 // p is in a module, so make it available based on the importer's import path instead
1353                 // of the file path (https://golang.org/issue/23970).
1354                 if importer.Internal.CmdlineFiles {
1355                         // The importer is a list of command-line files.
1356                         // Pretend that the import path is the import path of the
1357                         // directory containing them.
1358                         // If the directory is outside the main module, this will resolve to ".",
1359                         // which is not a prefix of any valid module.
1360                         importerPath = ModDirImportPath(importer.Dir)
1361                 }
1362                 parentOfInternal := p.ImportPath[:i]
1363                 if str.HasPathPrefix(importerPath, parentOfInternal) {
1364                         return p
1365                 }
1366         }
1367
1368         // Internal is present, and srcDir is outside parent's tree. Not allowed.
1369         perr := *p
1370         perr.Error = &PackageError{
1371                 alwaysPrintStack: true,
1372                 ImportStack:      stk.Copy(),
1373                 Err:              ImportErrorf(p.ImportPath, "use of internal package "+p.ImportPath+" not allowed"),
1374         }
1375         perr.Incomplete = true
1376         return &perr
1377 }
1378
1379 // findInternal looks for the final "internal" path element in the given import path.
1380 // If there isn't one, findInternal returns ok=false.
1381 // Otherwise, findInternal returns ok=true and the index of the "internal".
1382 func findInternal(path string) (index int, ok bool) {
1383         // Three cases, depending on internal at start/end of string or not.
1384         // The order matters: we must return the index of the final element,
1385         // because the final one produces the most restrictive requirement
1386         // on the importer.
1387         switch {
1388         case strings.HasSuffix(path, "/internal"):
1389                 return len(path) - len("internal"), true
1390         case strings.Contains(path, "/internal/"):
1391                 return strings.LastIndex(path, "/internal/") + 1, true
1392         case path == "internal", strings.HasPrefix(path, "internal/"):
1393                 return 0, true
1394         }
1395         return 0, false
1396 }
1397
1398 // disallowVendor checks that srcDir is allowed to import p as path.
1399 // If the import is allowed, disallowVendor returns the original package p.
1400 // If not, it returns a new package containing just an appropriate error.
1401 func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *Package {
1402         // If the importerPath is empty, we started
1403         // with a name given on the command line, not an
1404         // import. Anything listed on the command line is fine.
1405         if importerPath == "" {
1406                 return p
1407         }
1408
1409         if perr := disallowVendorVisibility(srcDir, p, importerPath, stk); perr != p {
1410                 return perr
1411         }
1412
1413         // Paths like x/vendor/y must be imported as y, never as x/vendor/y.
1414         if i, ok := FindVendor(path); ok {
1415                 perr := *p
1416                 perr.Error = &PackageError{
1417                         ImportStack: stk.Copy(),
1418                         Err:         ImportErrorf(path, "%s must be imported as %s", path, path[i+len("vendor/"):]),
1419                 }
1420                 perr.Incomplete = true
1421                 return &perr
1422         }
1423
1424         return p
1425 }
1426
1427 // disallowVendorVisibility checks that srcDir is allowed to import p.
1428 // The rules are the same as for /internal/ except that a path ending in /vendor
1429 // is not subject to the rules, only subdirectories of vendor.
1430 // This allows people to have packages and commands named vendor,
1431 // for maximal compatibility with existing source trees.
1432 func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *Package {
1433         // The stack does not include p.ImportPath.
1434         // If there's nothing on the stack, we started
1435         // with a name given on the command line, not an
1436         // import. Anything listed on the command line is fine.
1437         if importerPath == "" {
1438                 return p
1439         }
1440
1441         // Check for "vendor" element.
1442         i, ok := FindVendor(p.ImportPath)
1443         if !ok {
1444                 return p
1445         }
1446
1447         // Vendor is present.
1448         // Map import path back to directory corresponding to parent of vendor.
1449         if i > 0 {
1450                 i-- // rewind over slash in ".../vendor"
1451         }
1452         truncateTo := i + len(p.Dir) - len(p.ImportPath)
1453         if truncateTo < 0 || len(p.Dir) < truncateTo {
1454                 return p
1455         }
1456         parent := p.Dir[:truncateTo]
1457         if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1458                 return p
1459         }
1460
1461         // Look for symlinks before reporting error.
1462         srcDir = expandPath(srcDir)
1463         parent = expandPath(parent)
1464         if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1465                 return p
1466         }
1467
1468         // Vendor is present, and srcDir is outside parent's tree. Not allowed.
1469         perr := *p
1470         perr.Error = &PackageError{
1471                 ImportStack: stk.Copy(),
1472                 Err:         errors.New("use of vendored package not allowed"),
1473         }
1474         perr.Incomplete = true
1475         return &perr
1476 }
1477
1478 // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
1479 // If there isn't one, FindVendor returns ok=false.
1480 // Otherwise, FindVendor returns ok=true and the index of the "vendor".
1481 //
1482 // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
1483 // not the vendored copy of an import "" (the empty import path).
1484 // This will allow people to have packages or commands named vendor.
1485 // This may help reduce breakage, or it may just be confusing. We'll see.
1486 func FindVendor(path string) (index int, ok bool) {
1487         // Two cases, depending on internal at start of string or not.
1488         // The order matters: we must return the index of the final element,
1489         // because the final one is where the effective import path starts.
1490         switch {
1491         case strings.Contains(path, "/vendor/"):
1492                 return strings.LastIndex(path, "/vendor/") + 1, true
1493         case strings.HasPrefix(path, "vendor/"):
1494                 return 0, true
1495         }
1496         return 0, false
1497 }
1498
1499 type TargetDir int
1500
1501 const (
1502         ToTool    TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
1503         ToBin                      // to bin dir inside package root (default for non-cmd/*)
1504         StalePath                  // an old import path; fail to build
1505 )
1506
1507 // InstallTargetDir reports the target directory for installing the command p.
1508 func InstallTargetDir(p *Package) TargetDir {
1509         if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
1510                 return StalePath
1511         }
1512         if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1513                 switch p.ImportPath {
1514                 case "cmd/go", "cmd/gofmt":
1515                         return ToBin
1516                 }
1517                 return ToTool
1518         }
1519         return ToBin
1520 }
1521
1522 var cgoExclude = map[string]bool{
1523         "runtime/cgo": true,
1524 }
1525
1526 var cgoSyscallExclude = map[string]bool{
1527         "runtime/cgo":  true,
1528         "runtime/race": true,
1529         "runtime/msan": true,
1530 }
1531
1532 var foldPath = make(map[string]string)
1533
1534 // exeFromImportPath returns an executable name
1535 // for a package using the import path.
1536 //
1537 // The executable name is the last element of the import path.
1538 // In module-aware mode, an additional rule is used on import paths
1539 // consisting of two or more path elements. If the last element is
1540 // a vN path element specifying the major version, then the
1541 // second last element of the import path is used instead.
1542 func (p *Package) exeFromImportPath() string {
1543         _, elem := pathpkg.Split(p.ImportPath)
1544         if cfg.ModulesEnabled {
1545                 // If this is example.com/mycmd/v2, it's more useful to
1546                 // install it as mycmd than as v2. See golang.org/issue/24667.
1547                 if elem != p.ImportPath && isVersionElement(elem) {
1548                         _, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath))
1549                 }
1550         }
1551         return elem
1552 }
1553
1554 // exeFromFiles returns an executable name for a package
1555 // using the first element in GoFiles or CgoFiles collections without the prefix.
1556 //
1557 // Returns empty string in case of empty collection.
1558 func (p *Package) exeFromFiles() string {
1559         var src string
1560         if len(p.GoFiles) > 0 {
1561                 src = p.GoFiles[0]
1562         } else if len(p.CgoFiles) > 0 {
1563                 src = p.CgoFiles[0]
1564         } else {
1565                 return ""
1566         }
1567         _, elem := filepath.Split(src)
1568         return elem[:len(elem)-len(".go")]
1569 }
1570
1571 // DefaultExecName returns the default executable name for a package
1572 func (p *Package) DefaultExecName() string {
1573         if p.Internal.CmdlineFiles {
1574                 return p.exeFromFiles()
1575         }
1576         return p.exeFromImportPath()
1577 }
1578
1579 // load populates p using information from bp, err, which should
1580 // be the result of calling build.Context.Import.
1581 // stk contains the import stack, not including path itself.
1582 func (p *Package) load(path string, stk *ImportStack, bp *build.Package, err error) {
1583         p.copyBuild(bp)
1584
1585         // The localPrefix is the path we interpret ./ imports relative to.
1586         // Synthesized main packages sometimes override this.
1587         if p.Internal.Local {
1588                 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1589         }
1590
1591         // setError sets p.Error if it hasn't already been set. We may proceed
1592         // after encountering some errors so that 'go list -e' has more complete
1593         // output. If there's more than one error, we should report the first.
1594         setError := func(err error) {
1595                 if p.Error == nil {
1596                         p.Error = &PackageError{
1597                                 ImportStack: stk.Copy(),
1598                                 Err:         err,
1599                         }
1600                 }
1601         }
1602
1603         if err != nil {
1604                 p.Incomplete = true
1605                 p.setLoadPackageDataError(err, path, stk)
1606         }
1607
1608         useBindir := p.Name == "main"
1609         if !p.Standard {
1610                 switch cfg.BuildBuildmode {
1611                 case "c-archive", "c-shared", "plugin":
1612                         useBindir = false
1613                 }
1614         }
1615
1616         if useBindir {
1617                 // Report an error when the old code.google.com/p/go.tools paths are used.
1618                 if InstallTargetDir(p) == StalePath {
1619                         newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
1620                         e := ImportErrorf(p.ImportPath, "the %v command has moved; use %v instead.", p.ImportPath, newPath)
1621                         setError(e)
1622                         return
1623                 }
1624                 elem := p.DefaultExecName()
1625                 full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
1626                 if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
1627                         // Install cross-compiled binaries to subdirectories of bin.
1628                         elem = full
1629                 }
1630                 if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
1631                         p.Internal.Build.BinDir = ModBinDir()
1632                 }
1633                 if p.Internal.Build.BinDir != "" {
1634                         // Install to GOBIN or bin of GOPATH entry.
1635                         p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1636                         if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
1637                                 // Do not create $GOBIN/goos_goarch/elem.
1638                                 p.Target = ""
1639                                 p.Internal.GobinSubdir = true
1640                         }
1641                 }
1642                 if InstallTargetDir(p) == ToTool {
1643                         // This is for 'go tool'.
1644                         // Override all the usual logic and force it into the tool directory.
1645                         if cfg.BuildToolchainName == "gccgo" {
1646                                 p.Target = filepath.Join(base.ToolDir, elem)
1647                         } else {
1648                                 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1649                         }
1650                 }
1651                 if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
1652                         p.Target += ".exe"
1653                 }
1654         } else if p.Internal.Local {
1655                 // Local import turned into absolute path.
1656                 // No permanent install target.
1657                 p.Target = ""
1658         } else {
1659                 p.Target = p.Internal.Build.PkgObj
1660                 if cfg.BuildLinkshared && p.Target != "" {
1661                         // TODO(bcmills): The reliance on p.Target implies that -linkshared does
1662                         // not work for any package that lacks a Target — such as a non-main
1663                         // package in module mode. We should probably fix that.
1664                         shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
1665                         shlib, err := ioutil.ReadFile(shlibnamefile)
1666                         if err != nil && !os.IsNotExist(err) {
1667                                 base.Fatalf("reading shlibname: %v", err)
1668                         }
1669                         if err == nil {
1670                                 libname := strings.TrimSpace(string(shlib))
1671                                 if cfg.BuildContext.Compiler == "gccgo" {
1672                                         p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1673                                 } else {
1674                                         p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1675                                 }
1676                         }
1677                 }
1678         }
1679
1680         // Build augmented import list to add implicit dependencies.
1681         // Be careful not to add imports twice, just to avoid confusion.
1682         importPaths := p.Imports
1683         addImport := func(path string, forCompiler bool) {
1684                 for _, p := range importPaths {
1685                         if path == p {
1686                                 return
1687                         }
1688                 }
1689                 importPaths = append(importPaths, path)
1690                 if forCompiler {
1691                         p.Internal.CompiledImports = append(p.Internal.CompiledImports, path)
1692                 }
1693         }
1694
1695         // Cgo translation adds imports of "unsafe", "runtime/cgo" and "syscall",
1696         // except for certain packages, to avoid circular dependencies.
1697         if p.UsesCgo() {
1698                 addImport("unsafe", true)
1699         }
1700         if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1701                 addImport("runtime/cgo", true)
1702         }
1703         if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1704                 addImport("syscall", true)
1705         }
1706
1707         // SWIG adds imports of some standard packages.
1708         if p.UsesSwig() {
1709                 addImport("unsafe", true)
1710                 if cfg.BuildContext.Compiler != "gccgo" {
1711                         addImport("runtime/cgo", true)
1712                 }
1713                 addImport("syscall", true)
1714                 addImport("sync", true)
1715
1716                 // TODO: The .swig and .swigcxx files can use
1717                 // %go_import directives to import other packages.
1718         }
1719
1720         // The linker loads implicit dependencies.
1721         if p.Name == "main" && !p.Internal.ForceLibrary {
1722                 for _, dep := range LinkerDeps(p) {
1723                         addImport(dep, false)
1724                 }
1725         }
1726
1727         // Check for case-insensitive collisions of import paths.
1728         fold := str.ToFold(p.ImportPath)
1729         if other := foldPath[fold]; other == "" {
1730                 foldPath[fold] = p.ImportPath
1731         } else if other != p.ImportPath {
1732                 setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
1733                 return
1734         }
1735
1736         if !SafeArg(p.ImportPath) {
1737                 setError(ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath))
1738                 return
1739         }
1740
1741         stk.Push(path)
1742         defer stk.Pop()
1743
1744         // Check for case-insensitive collision of input files.
1745         // To avoid problems on case-insensitive files, we reject any package
1746         // where two different input files have equal names under a case-insensitive
1747         // comparison.
1748         inputs := p.AllFiles()
1749         f1, f2 := str.FoldDup(inputs)
1750         if f1 != "" {
1751                 setError(fmt.Errorf("case-insensitive file name collision: %q and %q", f1, f2))
1752                 return
1753         }
1754
1755         // If first letter of input file is ASCII, it must be alphanumeric.
1756         // This avoids files turning into flags when invoking commands,
1757         // and other problems we haven't thought of yet.
1758         // Also, _cgo_ files must be generated by us, not supplied.
1759         // They are allowed to have //go:cgo_ldflag directives.
1760         // The directory scan ignores files beginning with _,
1761         // so we shouldn't see any _cgo_ files anyway, but just be safe.
1762         for _, file := range inputs {
1763                 if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
1764                         setError(fmt.Errorf("invalid input file name %q", file))
1765                         return
1766                 }
1767         }
1768         if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
1769                 setError(fmt.Errorf("invalid input directory name %q", name))
1770                 return
1771         }
1772
1773         // Build list of imported packages and full dependency list.
1774         imports := make([]*Package, 0, len(p.Imports))
1775         for i, path := range importPaths {
1776                 if path == "C" {
1777                         continue
1778                 }
1779                 p1 := LoadImport(path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
1780
1781                 path = p1.ImportPath
1782                 importPaths[i] = path
1783                 if i < len(p.Imports) {
1784                         p.Imports[i] = path
1785                 }
1786
1787                 imports = append(imports, p1)
1788                 if p1.Incomplete {
1789                         p.Incomplete = true
1790                 }
1791         }
1792         p.Internal.Imports = imports
1793         p.collectDeps()
1794
1795         // unsafe is a fake package.
1796         if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
1797                 p.Target = ""
1798         }
1799
1800         // If cgo is not enabled, ignore cgo supporting sources
1801         // just as we ignore go files containing import "C".
1802         if !cfg.BuildContext.CgoEnabled {
1803                 p.CFiles = nil
1804                 p.CXXFiles = nil
1805                 p.MFiles = nil
1806                 p.SwigFiles = nil
1807                 p.SwigCXXFiles = nil
1808                 // Note that SFiles are okay (they go to the Go assembler)
1809                 // and HFiles are okay (they might be used by the SFiles).
1810                 // Also Sysofiles are okay (they might not contain object
1811                 // code; see issue #16050).
1812         }
1813
1814         // The gc toolchain only permits C source files with cgo or SWIG.
1815         if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
1816                 setError(fmt.Errorf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
1817                 return
1818         }
1819
1820         // C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
1821         // regardless of toolchain.
1822         if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1823                 setError(fmt.Errorf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
1824                 return
1825         }
1826         if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1827                 setError(fmt.Errorf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
1828                 return
1829         }
1830         if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
1831                 setError(fmt.Errorf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
1832                 return
1833         }
1834
1835         if cfg.ModulesEnabled && p.Error == nil {
1836                 mainPath := p.ImportPath
1837                 if p.Internal.CmdlineFiles {
1838                         mainPath = "command-line-arguments"
1839                 }
1840                 p.Module = ModPackageModuleInfo(mainPath)
1841                 if p.Name == "main" && len(p.DepsErrors) == 0 {
1842                         p.Internal.BuildInfo = ModPackageBuildInfo(mainPath, p.Deps)
1843                 }
1844         }
1845 }
1846
1847 // collectDeps populates p.Deps and p.DepsErrors by iterating over
1848 // p.Internal.Imports.
1849 //
1850 // TODO(jayconrod): collectDeps iterates over transitive imports for every
1851 // package. We should only need to visit direct imports.
1852 func (p *Package) collectDeps() {
1853         deps := make(map[string]*Package)
1854         var q []*Package
1855         q = append(q, p.Internal.Imports...)
1856         for i := 0; i < len(q); i++ {
1857                 p1 := q[i]
1858                 path := p1.ImportPath
1859                 // The same import path could produce an error or not,
1860                 // depending on what tries to import it.
1861                 // Prefer to record entries with errors, so we can report them.
1862                 p0 := deps[path]
1863                 if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
1864                         deps[path] = p1
1865                         for _, p2 := range p1.Internal.Imports {
1866                                 if deps[p2.ImportPath] != p2 {
1867                                         q = append(q, p2)
1868                                 }
1869                         }
1870                 }
1871         }
1872
1873         p.Deps = make([]string, 0, len(deps))
1874         for dep := range deps {
1875                 p.Deps = append(p.Deps, dep)
1876         }
1877         sort.Strings(p.Deps)
1878         for _, dep := range p.Deps {
1879                 p1 := deps[dep]
1880                 if p1 == nil {
1881                         panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
1882                 }
1883                 if p1.Error != nil {
1884                         p.DepsErrors = append(p.DepsErrors, p1.Error)
1885                 }
1886         }
1887 }
1888
1889 // SafeArg reports whether arg is a "safe" command-line argument,
1890 // meaning that when it appears in a command-line, it probably
1891 // doesn't have some special meaning other than its own name.
1892 // Obviously args beginning with - are not safe (they look like flags).
1893 // Less obviously, args beginning with @ are not safe (they look like
1894 // GNU binutils flagfile specifiers, sometimes called "response files").
1895 // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
1896 // We accept leading . _ and / as likely in file system paths.
1897 // There is a copy of this function in cmd/compile/internal/gc/noder.go.
1898 func SafeArg(name string) bool {
1899         if name == "" {
1900                 return false
1901         }
1902         c := name[0]
1903         return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
1904 }
1905
1906 // LinkerDeps returns the list of linker-induced dependencies for main package p.
1907 func LinkerDeps(p *Package) []string {
1908         // Everything links runtime.
1909         deps := []string{"runtime"}
1910
1911         // External linking mode forces an import of runtime/cgo.
1912         if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
1913                 deps = append(deps, "runtime/cgo")
1914         }
1915         // On ARM with GOARM=5, it forces an import of math, for soft floating point.
1916         if cfg.Goarch == "arm" {
1917                 deps = append(deps, "math")
1918         }
1919         // Using the race detector forces an import of runtime/race.
1920         if cfg.BuildRace {
1921                 deps = append(deps, "runtime/race")
1922         }
1923         // Using memory sanitizer forces an import of runtime/msan.
1924         if cfg.BuildMSan {
1925                 deps = append(deps, "runtime/msan")
1926         }
1927
1928         return deps
1929 }
1930
1931 // externalLinkingForced reports whether external linking is being
1932 // forced even for programs that do not use cgo.
1933 func externalLinkingForced(p *Package) bool {
1934         // Some targets must use external linking even inside GOROOT.
1935         switch cfg.BuildContext.GOOS {
1936         case "android":
1937                 if cfg.BuildContext.GOARCH != "arm64" {
1938                         return true
1939                 }
1940         case "darwin":
1941                 if cfg.BuildContext.GOARCH == "arm64" {
1942                         return true
1943                 }
1944         }
1945
1946         if !cfg.BuildContext.CgoEnabled {
1947                 return false
1948         }
1949         // Currently build modes c-shared, pie (on systems that do not
1950         // support PIE with internal linking mode (currently all
1951         // systems: issue #18968)), plugin, and -linkshared force
1952         // external linking mode, as of course does
1953         // -ldflags=-linkmode=external. External linking mode forces
1954         // an import of runtime/cgo.
1955         pieCgo := cfg.BuildBuildmode == "pie"
1956         linkmodeExternal := false
1957         if p != nil {
1958                 ldflags := BuildLdflags.For(p)
1959                 for i, a := range ldflags {
1960                         if a == "-linkmode=external" {
1961                                 linkmodeExternal = true
1962                         }
1963                         if a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
1964                                 linkmodeExternal = true
1965                         }
1966                 }
1967         }
1968
1969         return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
1970 }
1971
1972 // mkAbs rewrites list, which must be paths relative to p.Dir,
1973 // into a sorted list of absolute paths. It edits list in place but for
1974 // convenience also returns list back to its caller.
1975 func (p *Package) mkAbs(list []string) []string {
1976         for i, f := range list {
1977                 list[i] = filepath.Join(p.Dir, f)
1978         }
1979         sort.Strings(list)
1980         return list
1981 }
1982
1983 // InternalGoFiles returns the list of Go files being built for the package,
1984 // using absolute paths.
1985 func (p *Package) InternalGoFiles() []string {
1986         return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
1987 }
1988
1989 // InternalXGoFiles returns the list of Go files being built for the XTest package,
1990 // using absolute paths.
1991 func (p *Package) InternalXGoFiles() []string {
1992         return p.mkAbs(p.XTestGoFiles)
1993 }
1994
1995 // InternalGoFiles returns the list of all Go files possibly relevant for the package,
1996 // using absolute paths. "Possibly relevant" means that files are not excluded
1997 // due to build tags, but files with names beginning with . or _ are still excluded.
1998 func (p *Package) InternalAllGoFiles() []string {
1999         return p.mkAbs(str.StringList(p.constraintIgnoredGoFiles(), p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
2000 }
2001
2002 // constraintIgnoredGoFiles returns the list of Go files ignored for reasons
2003 // other than having a name beginning with '.' or '_'.
2004 func (p *Package) constraintIgnoredGoFiles() []string {
2005         if len(p.IgnoredGoFiles) == 0 {
2006                 return nil
2007         }
2008         files := make([]string, 0, len(p.IgnoredGoFiles))
2009         for _, f := range p.IgnoredGoFiles {
2010                 if f != "" && f[0] != '.' && f[0] != '_' {
2011                         files = append(files, f)
2012                 }
2013         }
2014         return files
2015 }
2016
2017 // usesSwig reports whether the package needs to run SWIG.
2018 func (p *Package) UsesSwig() bool {
2019         return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
2020 }
2021
2022 // usesCgo reports whether the package needs to run cgo
2023 func (p *Package) UsesCgo() bool {
2024         return len(p.CgoFiles) > 0
2025 }
2026
2027 // PackageList returns the list of packages in the dag rooted at roots
2028 // as visited in a depth-first post-order traversal.
2029 func PackageList(roots []*Package) []*Package {
2030         seen := map[*Package]bool{}
2031         all := []*Package{}
2032         var walk func(*Package)
2033         walk = func(p *Package) {
2034                 if seen[p] {
2035                         return
2036                 }
2037                 seen[p] = true
2038                 for _, p1 := range p.Internal.Imports {
2039                         walk(p1)
2040                 }
2041                 all = append(all, p)
2042         }
2043         for _, root := range roots {
2044                 walk(root)
2045         }
2046         return all
2047 }
2048
2049 // TestPackageList returns the list of packages in the dag rooted at roots
2050 // as visited in a depth-first post-order traversal, including the test
2051 // imports of the roots. This ignores errors in test packages.
2052 func TestPackageList(roots []*Package) []*Package {
2053         seen := map[*Package]bool{}
2054         all := []*Package{}
2055         var walk func(*Package)
2056         walk = func(p *Package) {
2057                 if seen[p] {
2058                         return
2059                 }
2060                 seen[p] = true
2061                 for _, p1 := range p.Internal.Imports {
2062                         walk(p1)
2063                 }
2064                 all = append(all, p)
2065         }
2066         walkTest := func(root *Package, path string) {
2067                 var stk ImportStack
2068                 p1 := LoadImport(path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
2069                 if p1.Error == nil {
2070                         walk(p1)
2071                 }
2072         }
2073         for _, root := range roots {
2074                 walk(root)
2075                 for _, path := range root.TestImports {
2076                         walkTest(root, path)
2077                 }
2078                 for _, path := range root.XTestImports {
2079                         walkTest(root, path)
2080                 }
2081         }
2082         return all
2083 }
2084
2085 // LoadImportWithFlags loads the package with the given import path and
2086 // sets tool flags on that package. This function is useful loading implicit
2087 // dependencies (like sync/atomic for coverage).
2088 // TODO(jayconrod): delete this function and set flags automatically
2089 // in LoadImport instead.
2090 func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
2091         p := LoadImport(path, srcDir, parent, stk, importPos, mode)
2092         setToolFlags(p)
2093         return p
2094 }
2095
2096 // Packages returns the packages named by the
2097 // command line arguments 'args'. If a named package
2098 // cannot be loaded at all (for example, if the directory does not exist),
2099 // then packages prints an error and does not include that
2100 // package in the results. However, if errors occur trying
2101 // to load dependencies of a named package, the named
2102 // package is still returned, with p.Incomplete = true
2103 // and details in p.DepsErrors.
2104 func Packages(args []string) []*Package {
2105         var pkgs []*Package
2106         for _, pkg := range PackagesAndErrors(args) {
2107                 if pkg.Error != nil {
2108                         base.Errorf("%v", pkg.Error)
2109                         continue
2110                 }
2111                 pkgs = append(pkgs, pkg)
2112         }
2113         return pkgs
2114 }
2115
2116 // PackagesAndErrors is like 'packages' but returns a
2117 // *Package for every argument, even the ones that
2118 // cannot be loaded at all.
2119 // The packages that fail to load will have p.Error != nil.
2120 func PackagesAndErrors(patterns []string) []*Package {
2121         for _, p := range patterns {
2122                 // Listing is only supported with all patterns referring to either:
2123                 // - Files that are part of the same directory.
2124                 // - Explicit package paths or patterns.
2125                 if strings.HasSuffix(p, ".go") {
2126                         // We need to test whether the path is an actual Go file and not a
2127                         // package path or pattern ending in '.go' (see golang.org/issue/34653).
2128                         if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
2129                                 return []*Package{GoFilesPackage(patterns)}
2130                         }
2131                 }
2132         }
2133
2134         matches := ImportPaths(patterns)
2135         var (
2136                 pkgs    []*Package
2137                 stk     ImportStack
2138                 seenPkg = make(map[*Package]bool)
2139         )
2140
2141         pre := newPreload()
2142         defer pre.flush()
2143         pre.preloadMatches(matches)
2144
2145         for _, m := range matches {
2146                 for _, pkg := range m.Pkgs {
2147                         if pkg == "" {
2148                                 panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
2149                         }
2150                         p := loadImport(pre, pkg, base.Cwd, nil, &stk, nil, 0)
2151                         p.Match = append(p.Match, m.Pattern())
2152                         p.Internal.CmdlinePkg = true
2153                         if m.IsLiteral() {
2154                                 // Note: do not set = m.IsLiteral unconditionally
2155                                 // because maybe we'll see p matching both
2156                                 // a literal and also a non-literal pattern.
2157                                 p.Internal.CmdlinePkgLiteral = true
2158                         }
2159                         if seenPkg[p] {
2160                                 continue
2161                         }
2162                         seenPkg[p] = true
2163                         pkgs = append(pkgs, p)
2164                 }
2165
2166                 if len(m.Errs) > 0 {
2167                         // In addition to any packages that were actually resolved from the
2168                         // pattern, there was some error in resolving the pattern itself.
2169                         // Report it as a synthetic package.
2170                         p := new(Package)
2171                         p.ImportPath = m.Pattern()
2172                         var stk ImportStack // empty stack, since the error arose from a pattern, not an import
2173                         p.setLoadPackageDataError(m.Errs[0], m.Pattern(), &stk)
2174                         p.Incomplete = true
2175                         p.Match = append(p.Match, m.Pattern())
2176                         p.Internal.CmdlinePkg = true
2177                         if m.IsLiteral() {
2178                                 p.Internal.CmdlinePkgLiteral = true
2179                         }
2180                         pkgs = append(pkgs, p)
2181                 }
2182         }
2183
2184         // Now that CmdlinePkg is set correctly,
2185         // compute the effective flags for all loaded packages
2186         // (not just the ones matching the patterns but also
2187         // their dependencies).
2188         setToolFlags(pkgs...)
2189
2190         return pkgs
2191 }
2192
2193 func setToolFlags(pkgs ...*Package) {
2194         for _, p := range PackageList(pkgs) {
2195                 p.Internal.Asmflags = BuildAsmflags.For(p)
2196                 p.Internal.Gcflags = BuildGcflags.For(p)
2197                 p.Internal.Ldflags = BuildLdflags.For(p)
2198                 p.Internal.Gccgoflags = BuildGccgoflags.For(p)
2199         }
2200 }
2201
2202 func ImportPaths(args []string) []*search.Match {
2203         if ModInit(); cfg.ModulesEnabled {
2204                 return ModImportPaths(args)
2205         }
2206         return search.ImportPaths(args)
2207 }
2208
2209 // PackagesForBuild is like Packages but exits
2210 // if any of the packages or their dependencies have errors
2211 // (cannot be built).
2212 func PackagesForBuild(args []string) []*Package {
2213         pkgs := PackagesAndErrors(args)
2214         printed := map[*PackageError]bool{}
2215         for _, pkg := range pkgs {
2216                 if pkg.Error != nil {
2217                         base.Errorf("%v", pkg.Error)
2218                         printed[pkg.Error] = true
2219                 }
2220                 for _, err := range pkg.DepsErrors {
2221                         // Since these are errors in dependencies,
2222                         // the same error might show up multiple times,
2223                         // once in each package that depends on it.
2224                         // Only print each once.
2225                         if !printed[err] {
2226                                 printed[err] = true
2227                                 base.Errorf("%v", err)
2228                         }
2229                 }
2230         }
2231         base.ExitIfErrors()
2232
2233         // Check for duplicate loads of the same package.
2234         // That should be impossible, but if it does happen then
2235         // we end up trying to build the same package twice,
2236         // usually in parallel overwriting the same files,
2237         // which doesn't work very well.
2238         seen := map[string]bool{}
2239         reported := map[string]bool{}
2240         for _, pkg := range PackageList(pkgs) {
2241                 if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
2242                         reported[pkg.ImportPath] = true
2243                         base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
2244                 }
2245                 seen[pkg.ImportPath] = true
2246         }
2247         base.ExitIfErrors()
2248
2249         return pkgs
2250 }
2251
2252 // GoFilesPackage creates a package for building a collection of Go files
2253 // (typically named on the command line). The target is named p.a for
2254 // package p or named after the first Go file for package main.
2255 func GoFilesPackage(gofiles []string) *Package {
2256         ModInit()
2257
2258         for _, f := range gofiles {
2259                 if !strings.HasSuffix(f, ".go") {
2260                         pkg := new(Package)
2261                         pkg.Internal.Local = true
2262                         pkg.Internal.CmdlineFiles = true
2263                         pkg.Name = f
2264                         pkg.Error = &PackageError{
2265                                 Err: fmt.Errorf("named files must be .go files: %s", pkg.Name),
2266                         }
2267                         return pkg
2268                 }
2269         }
2270
2271         var stk ImportStack
2272         ctxt := cfg.BuildContext
2273         ctxt.UseAllFiles = true
2274
2275         // Synthesize fake "directory" that only shows the named files,
2276         // to make it look like this is a standard package or
2277         // command directory. So that local imports resolve
2278         // consistently, the files must all be in the same directory.
2279         var dirent []os.FileInfo
2280         var dir string
2281         for _, file := range gofiles {
2282                 fi, err := os.Stat(file)
2283                 if err != nil {
2284                         base.Fatalf("%s", err)
2285                 }
2286                 if fi.IsDir() {
2287                         base.Fatalf("%s is a directory, should be a Go file", file)
2288                 }
2289                 dir1, _ := filepath.Split(file)
2290                 if dir1 == "" {
2291                         dir1 = "./"
2292                 }
2293                 if dir == "" {
2294                         dir = dir1
2295                 } else if dir != dir1 {
2296                         base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
2297                 }
2298                 dirent = append(dirent, fi)
2299         }
2300         ctxt.ReadDir = func(string) ([]os.FileInfo, error) { return dirent, nil }
2301
2302         if cfg.ModulesEnabled {
2303                 ModImportFromFiles(gofiles)
2304         }
2305
2306         var err error
2307         if dir == "" {
2308                 dir = base.Cwd
2309         }
2310         dir, err = filepath.Abs(dir)
2311         if err != nil {
2312                 base.Fatalf("%s", err)
2313         }
2314
2315         bp, err := ctxt.ImportDir(dir, 0)
2316         pkg := new(Package)
2317         pkg.Internal.Local = true
2318         pkg.Internal.CmdlineFiles = true
2319         pkg.load("command-line-arguments", &stk, bp, err)
2320         pkg.Internal.LocalPrefix = dirToImportPath(dir)
2321         pkg.ImportPath = "command-line-arguments"
2322         pkg.Target = ""
2323         pkg.Match = gofiles
2324
2325         if pkg.Name == "main" {
2326                 exe := pkg.DefaultExecName() + cfg.ExeSuffix
2327
2328                 if cfg.GOBIN != "" {
2329                         pkg.Target = filepath.Join(cfg.GOBIN, exe)
2330                 } else if cfg.ModulesEnabled {
2331                         pkg.Target = filepath.Join(ModBinDir(), exe)
2332                 }
2333         }
2334
2335         setToolFlags(pkg)
2336
2337         return pkg
2338 }