Debian Codegraph @

src/cmd/go/internal/load/pkg.go

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