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