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