1
2
3
4
5
6 package load
7
8 import (
9 "bytes"
10 "context"
11 "encoding/json"
12 "errors"
13 "fmt"
14 "go/scanner"
15 "go/token"
16 "internal/godebug"
17 "internal/platform"
18 "io/fs"
19 "os"
20 pathpkg "path"
21 "path/filepath"
22 "runtime"
23 "runtime/debug"
24 "slices"
25 "sort"
26 "strconv"
27 "strings"
28 "time"
29 "unicode"
30 "unicode/utf8"
31
32 "cmd/internal/objabi"
33
34 "cmd/go/internal/base"
35 "cmd/go/internal/build"
36 "cmd/go/internal/cfg"
37 "cmd/go/internal/fips140"
38 "cmd/go/internal/fsys"
39 "cmd/go/internal/gover"
40 "cmd/go/internal/imports"
41 "cmd/go/internal/modfetch"
42 "cmd/go/internal/modindex"
43 "cmd/go/internal/modinfo"
44 "cmd/go/internal/modload"
45 "cmd/go/internal/search"
46 "cmd/go/internal/str"
47 "cmd/go/internal/trace"
48 "cmd/go/internal/vcs"
49 "cmd/internal/par"
50 "cmd/internal/pathcache"
51 "cmd/internal/pkgpattern"
52
53 "golang.org/x/mod/modfile"
54 "golang.org/x/mod/module"
55 )
56
57
58 type Package struct {
59 PackagePublic
60 Internal PackageInternal
61 }
62
63 type PackagePublic struct {
64
65
66
67 Dir string `json:",omitempty"`
68 ImportPath string `json:",omitempty"`
69 ImportComment string `json:",omitempty"`
70 Name string `json:",omitempty"`
71 Doc string `json:",omitempty"`
72 Target string `json:",omitempty"`
73 Shlib string `json:",omitempty"`
74 Root string `json:",omitempty"`
75 ConflictDir string `json:",omitempty"`
76 ForTest string `json:",omitempty"`
77 Export string `json:",omitempty"`
78 BuildID string `json:",omitempty"`
79 Module *modinfo.ModulePublic `json:",omitempty"`
80 Match []string `json:",omitempty"`
81 Goroot bool `json:",omitempty"`
82 Standard bool `json:",omitempty"`
83 DepOnly bool `json:",omitempty"`
84 BinaryOnly bool `json:",omitempty"`
85 Incomplete bool `json:",omitempty"`
86
87 DefaultGODEBUG string `json:",omitempty"`
88
89
90
91
92 Stale bool `json:",omitempty"`
93 StaleReason string `json:",omitempty"`
94
95
96
97
98 GoFiles []string `json:",omitempty"`
99 CgoFiles []string `json:",omitempty"`
100 CompiledGoFiles []string `json:",omitempty"`
101 IgnoredGoFiles []string `json:",omitempty"`
102 InvalidGoFiles []string `json:",omitempty"`
103 IgnoredOtherFiles []string `json:",omitempty"`
104 CFiles []string `json:",omitempty"`
105 CXXFiles []string `json:",omitempty"`
106 MFiles []string `json:",omitempty"`
107 HFiles []string `json:",omitempty"`
108 FFiles []string `json:",omitempty"`
109 SFiles []string `json:",omitempty"`
110 SwigFiles []string `json:",omitempty"`
111 SwigCXXFiles []string `json:",omitempty"`
112 SysoFiles []string `json:",omitempty"`
113
114
115 EmbedPatterns []string `json:",omitempty"`
116 EmbedFiles []string `json:",omitempty"`
117
118
119 CgoCFLAGS []string `json:",omitempty"`
120 CgoCPPFLAGS []string `json:",omitempty"`
121 CgoCXXFLAGS []string `json:",omitempty"`
122 CgoFFLAGS []string `json:",omitempty"`
123 CgoLDFLAGS []string `json:",omitempty"`
124 CgoPkgConfig []string `json:",omitempty"`
125
126
127 Imports []string `json:",omitempty"`
128 ImportMap map[string]string `json:",omitempty"`
129 Deps []string `json:",omitempty"`
130
131
132
133 Error *PackageError `json:",omitempty"`
134 DepsErrors []*PackageError `json:",omitempty"`
135
136
137
138
139 TestGoFiles []string `json:",omitempty"`
140 TestImports []string `json:",omitempty"`
141 TestEmbedPatterns []string `json:",omitempty"`
142 TestEmbedFiles []string `json:",omitempty"`
143 XTestGoFiles []string `json:",omitempty"`
144 XTestImports []string `json:",omitempty"`
145 XTestEmbedPatterns []string `json:",omitempty"`
146 XTestEmbedFiles []string `json:",omitempty"`
147 }
148
149
150
151
152
153
154 func (p *Package) AllFiles() []string {
155 files := str.StringList(
156 p.GoFiles,
157 p.CgoFiles,
158
159 p.IgnoredGoFiles,
160
161 p.IgnoredOtherFiles,
162 p.CFiles,
163 p.CXXFiles,
164 p.MFiles,
165 p.HFiles,
166 p.FFiles,
167 p.SFiles,
168 p.SwigFiles,
169 p.SwigCXXFiles,
170 p.SysoFiles,
171 p.TestGoFiles,
172 p.XTestGoFiles,
173 )
174
175
176
177
178
179 var have map[string]bool
180 for _, file := range p.EmbedFiles {
181 if !strings.Contains(file, "/") {
182 if have == nil {
183 have = make(map[string]bool)
184 for _, file := range files {
185 have[file] = true
186 }
187 }
188 if have[file] {
189 continue
190 }
191 }
192 files = append(files, file)
193 }
194 return files
195 }
196
197
198 func (p *Package) Desc() string {
199 if p.ForTest != "" {
200 return p.ImportPath + " [" + p.ForTest + ".test]"
201 }
202 if p.Internal.ForMain != "" {
203 return p.ImportPath + " [" + p.Internal.ForMain + "]"
204 }
205 return p.ImportPath
206 }
207
208
209
210
211
212
213
214 func (p *Package) IsTestOnly() bool {
215 return p.ForTest != "" ||
216 p.Internal.TestmainGo != nil ||
217 len(p.TestGoFiles)+len(p.XTestGoFiles) > 0 && len(p.GoFiles)+len(p.CgoFiles) == 0
218 }
219
220 type PackageInternal struct {
221
222 Build *build.Package
223 Imports []*Package
224 CompiledImports []string
225 RawImports []string
226 ForceLibrary bool
227 CmdlineFiles bool
228 CmdlinePkg bool
229 CmdlinePkgLiteral bool
230 Local bool
231 LocalPrefix string
232 ExeName string
233 FuzzInstrument bool
234 Cover CoverSetup
235 OmitDebug bool
236 GobinSubdir bool
237 InternalImportOk bool
238 BuildInfo *debug.BuildInfo
239 TestmainGo *[]byte
240 Embed map[string][]string
241 OrigImportPath string
242 PGOProfile string
243 ForMain string
244
245 Asmflags []string
246 Gcflags []string
247 Ldflags []string
248 Gccgoflags []string
249 }
250
251
252
253
254
255
256 type NoGoError struct {
257 Package *Package
258 }
259
260 func (e *NoGoError) Error() string {
261 if len(e.Package.IgnoredGoFiles) > 0 {
262
263 return "build constraints exclude all Go files in " + e.Package.Dir
264 }
265 if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
266
267
268
269 return "no non-test Go files in " + e.Package.Dir
270 }
271 return "no Go files in " + e.Package.Dir
272 }
273
274
275
276
277
278
279
280
281 func (p *Package) setLoadPackageDataError(err error, path string, stk *ImportStack, importPos []token.Position) {
282 matchErr, isMatchErr := err.(*search.MatchError)
283 if isMatchErr && matchErr.Match.Pattern() == path {
284 if matchErr.Match.IsLiteral() {
285
286
287
288
289 err = matchErr.Err
290 }
291 }
292
293
294
295 nogoErr, ok := errors.AsType[*build.NoGoError](err)
296 if ok {
297 if p.Dir == "" && nogoErr.Dir != "" {
298 p.Dir = nogoErr.Dir
299 }
300 err = &NoGoError{Package: p}
301 }
302
303
304
305
306 var pos string
307 var isScanErr bool
308 if scanErr, ok := err.(scanner.ErrorList); ok && len(scanErr) > 0 {
309 isScanErr = true
310
311 scanPos := scanErr[0].Pos
312 scanPos.Filename = base.ShortPath(scanPos.Filename)
313 pos = scanPos.String()
314 err = errors.New(scanErr[0].Msg)
315 }
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332 if !isMatchErr && (nogoErr != nil || isScanErr) {
333 stk.Push(ImportInfo{Pkg: path, Pos: extractFirstImport(importPos)})
334 defer stk.Pop()
335 }
336
337 p.Error = &PackageError{
338 ImportStack: stk.Copy(),
339 Pos: pos,
340 Err: err,
341 }
342 p.Incomplete = true
343
344 top, ok := stk.Top()
345 if ok && path != top.Pkg {
346 p.Error.setPos(importPos)
347 }
348 }
349
350
351
352
353
354
355
356
357
358
359
360 func (p *Package) Resolve(s *modload.Loader, imports []string) []string {
361 if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
362 panic("internal error: p.Resolve(p.Imports) called")
363 }
364 seen := make(map[string]bool)
365 var all []string
366 for _, path := range imports {
367 path = ResolveImportPath(s, p, path)
368 if !seen[path] {
369 seen[path] = true
370 all = append(all, path)
371 }
372 }
373 sort.Strings(all)
374 return all
375 }
376
377
378 type CoverSetup struct {
379 Mode string
380 GenMeta bool
381 }
382
383 func (p *Package) copyBuild(opts PackageOpts, pp *build.Package) {
384 p.Internal.Build = pp
385
386 if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
387 old := pp.PkgTargetRoot
388 pp.PkgRoot = cfg.BuildPkgdir
389 pp.PkgTargetRoot = cfg.BuildPkgdir
390 if pp.PkgObj != "" {
391 pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
392 }
393 }
394
395 p.Dir = pp.Dir
396 p.ImportPath = pp.ImportPath
397 p.ImportComment = pp.ImportComment
398 p.Name = pp.Name
399 p.Doc = pp.Doc
400 p.Root = pp.Root
401 p.ConflictDir = pp.ConflictDir
402 p.BinaryOnly = pp.BinaryOnly
403
404
405 p.Goroot = pp.Goroot || fips140.Snapshot() && str.HasFilePathPrefix(p.Dir, fips140.Dir())
406 p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath)
407 p.GoFiles = pp.GoFiles
408 p.CgoFiles = pp.CgoFiles
409 p.IgnoredGoFiles = pp.IgnoredGoFiles
410 p.InvalidGoFiles = pp.InvalidGoFiles
411 p.IgnoredOtherFiles = pp.IgnoredOtherFiles
412 p.CFiles = pp.CFiles
413 p.CXXFiles = pp.CXXFiles
414 p.MFiles = pp.MFiles
415 p.HFiles = pp.HFiles
416 p.FFiles = pp.FFiles
417 p.SFiles = pp.SFiles
418 p.SwigFiles = pp.SwigFiles
419 p.SwigCXXFiles = pp.SwigCXXFiles
420 p.SysoFiles = pp.SysoFiles
421 if cfg.BuildMSan {
422
423
424
425 p.SysoFiles = nil
426 }
427 p.CgoCFLAGS = pp.CgoCFLAGS
428 p.CgoCPPFLAGS = pp.CgoCPPFLAGS
429 p.CgoCXXFLAGS = pp.CgoCXXFLAGS
430 p.CgoFFLAGS = pp.CgoFFLAGS
431 p.CgoLDFLAGS = pp.CgoLDFLAGS
432 p.CgoPkgConfig = pp.CgoPkgConfig
433
434 p.Imports = make([]string, len(pp.Imports))
435 copy(p.Imports, pp.Imports)
436 p.Internal.RawImports = pp.Imports
437 p.TestGoFiles = pp.TestGoFiles
438 p.TestImports = pp.TestImports
439 p.XTestGoFiles = pp.XTestGoFiles
440 p.XTestImports = pp.XTestImports
441 if opts.IgnoreImports {
442 p.Imports = nil
443 p.Internal.RawImports = nil
444 p.TestImports = nil
445 p.XTestImports = nil
446 }
447 p.EmbedPatterns = pp.EmbedPatterns
448 p.TestEmbedPatterns = pp.TestEmbedPatterns
449 p.XTestEmbedPatterns = pp.XTestEmbedPatterns
450 p.Internal.OrigImportPath = pp.ImportPath
451 }
452
453
454 type PackageError struct {
455 ImportStack ImportStack
456 Pos string
457 Err error
458 IsImportCycle bool
459 alwaysPrintStack bool
460 }
461
462 func (p *PackageError) Error() string {
463
464
465
466 if p.Pos != "" && (len(p.ImportStack) == 0 || !p.alwaysPrintStack) {
467
468
469 return p.Pos + ": " + p.Err.Error()
470 }
471
472
473
474
475
476
477
478 if len(p.ImportStack) == 0 {
479 return p.Err.Error()
480 }
481 var optpos string
482 if p.Pos != "" {
483 optpos = "\n\t" + p.Pos
484 }
485 imports := p.ImportStack.Pkgs()
486 if p.IsImportCycle {
487 imports = p.ImportStack.PkgsWithPos()
488 }
489 return "package " + strings.Join(imports, "\n\timports ") + optpos + ": " + p.Err.Error()
490 }
491
492 func (p *PackageError) Unwrap() error { return p.Err }
493
494
495
496 func (p *PackageError) MarshalJSON() ([]byte, error) {
497 perr := struct {
498 ImportStack []string
499 Pos string
500 Err string
501 }{p.ImportStack.Pkgs(), p.Pos, p.Err.Error()}
502 return json.Marshal(perr)
503 }
504
505 func (p *PackageError) setPos(posList []token.Position) {
506 if len(posList) == 0 {
507 return
508 }
509 pos := posList[0]
510 pos.Filename = base.ShortPath(pos.Filename)
511 p.Pos = pos.String()
512 }
513
514
515
516
517
518
519
520
521
522 type ImportPathError interface {
523 error
524 ImportPath() string
525 }
526
527 var (
528 _ ImportPathError = (*importError)(nil)
529 _ ImportPathError = (*mainPackageError)(nil)
530 _ ImportPathError = (*modload.ImportMissingError)(nil)
531 _ ImportPathError = (*modload.ImportMissingSumError)(nil)
532 _ ImportPathError = (*modload.DirectImportFromImplicitDependencyError)(nil)
533 )
534
535 type importError struct {
536 importPath string
537 err error
538 }
539
540 func ImportErrorf(path, format string, args ...any) ImportPathError {
541 err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
542 if errStr := err.Error(); !strings.Contains(errStr, path) && !strings.Contains(errStr, strconv.Quote(path)) {
543 panic(fmt.Sprintf("path %q not in error %q", path, errStr))
544 }
545 return err
546 }
547
548 func (e *importError) Error() string {
549 return e.err.Error()
550 }
551
552 func (e *importError) Unwrap() error {
553
554
555 return errors.Unwrap(e.err)
556 }
557
558 func (e *importError) ImportPath() string {
559 return e.importPath
560 }
561
562 type ImportInfo struct {
563 Pkg string
564 Pos *token.Position
565 }
566
567
568
569
570 type ImportStack []ImportInfo
571
572 func NewImportInfo(pkg string, pos *token.Position) ImportInfo {
573 return ImportInfo{Pkg: pkg, Pos: pos}
574 }
575
576 func (s *ImportStack) Push(p ImportInfo) {
577 *s = append(*s, p)
578 }
579
580 func (s *ImportStack) Pop() {
581 *s = (*s)[0 : len(*s)-1]
582 }
583
584 func (s *ImportStack) Copy() ImportStack {
585 return slices.Clone(*s)
586 }
587
588 func (s *ImportStack) Pkgs() []string {
589 ss := make([]string, 0, len(*s))
590 for _, v := range *s {
591 ss = append(ss, v.Pkg)
592 }
593 return ss
594 }
595
596 func (s *ImportStack) PkgsWithPos() []string {
597 ss := make([]string, 0, len(*s))
598 for _, v := range *s {
599 if v.Pos != nil {
600 ss = append(ss, v.Pkg+" from "+filepath.Base(v.Pos.Filename))
601 } else {
602 ss = append(ss, v.Pkg)
603 }
604 }
605 return ss
606 }
607
608 func (s *ImportStack) Top() (ImportInfo, bool) {
609 if len(*s) == 0 {
610 return ImportInfo{}, false
611 }
612 return (*s)[len(*s)-1], true
613 }
614
615
616
617
618 func (sp *ImportStack) shorterThan(t []string) bool {
619 s := *sp
620 if len(s) != len(t) {
621 return len(s) < len(t)
622 }
623
624 for i := range s {
625 siPkg := s[i].Pkg
626 if siPkg != t[i] {
627 return siPkg < t[i]
628 }
629 }
630 return false
631 }
632
633
634
635
636
637
638
639
640 func dirToImportPath(dir string) string {
641 return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
642 }
643
644 func makeImportValid(r rune) rune {
645
646 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
647 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
648 return '_'
649 }
650 return r
651 }
652
653
654 const (
655
656
657
658
659
660
661
662
663
664 ResolveImport = 1 << iota
665
666
667
668 ResolveModule
669
670
671
672 GetTestDeps
673
674
675
676
677 cmdlinePkg
678
679
680
681 cmdlinePkgLiteral
682 )
683
684
685 func LoadPackage(ld *modload.Loader, ctx context.Context, opts PackageOpts, path, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package {
686 p, err := loadImport(ld, ctx, opts, nil, path, srcDir, nil, stk, importPos, mode)
687 if err != nil {
688 base.Fatalf("internal error: loadImport of %q with nil parent returned an error", path)
689 }
690 return p
691 }
692
693
694
695
696
697
698
699
700
701
702 func loadImport(ld *modload.Loader, ctx context.Context, opts PackageOpts, pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) (*Package, *PackageError) {
703 ctx, span := trace.StartSpan(ctx, "modload.loadImport "+path)
704 defer span.Done()
705
706 if path == "" {
707 panic("LoadImport called with empty package path")
708 }
709
710 var parentPath, parentRoot string
711 parentIsStd := false
712 if parent != nil {
713 parentPath = parent.ImportPath
714 parentRoot = parent.Root
715 parentIsStd = parent.Standard
716 }
717 bp, loaded, err := loadPackageData(ld, ctx, path, parentPath, srcDir, parentRoot, parentIsStd, mode)
718 if loaded && pre != nil && !opts.IgnoreImports {
719 pre.preloadImports(ld, ctx, opts, bp.Imports, bp)
720 }
721 if bp == nil {
722 p := &Package{
723 PackagePublic: PackagePublic{
724 ImportPath: path,
725 Incomplete: true,
726 },
727 }
728 if importErr, ok := err.(ImportPathError); !ok || importErr.ImportPath() != path {
729
730
731
732
733
734
735
736 stk.Push(ImportInfo{Pkg: path, Pos: extractFirstImport(importPos)})
737 defer stk.Pop()
738 }
739 p.setLoadPackageDataError(err, path, stk, nil)
740 setToolFlags(ld, p)
741 return p, nil
742 }
743
744 setCmdline := func(p *Package) {
745 if mode&cmdlinePkg != 0 {
746 p.Internal.CmdlinePkg = true
747 }
748 if mode&cmdlinePkgLiteral != 0 {
749 p.Internal.CmdlinePkgLiteral = true
750 }
751 }
752
753 importPath := bp.ImportPath
754 var p *Package
755 if cp := ld.PackageCache()[importPath]; cp != nil {
756 p = cp.(*Package)
757 stk.Push(ImportInfo{Pkg: path, Pos: extractFirstImport(importPos)})
758 p = reusePackage(p, stk)
759 stk.Pop()
760 setCmdline(p)
761 } else {
762 p = new(Package)
763 p.Internal.Local = build.IsLocalImport(path)
764 p.ImportPath = importPath
765 ld.PackageCache()[importPath] = p
766
767 setCmdline(p)
768 setToolFlags(ld, p)
769
770
771
772
773 p.load(ld, ctx, opts, path, stk, importPos, bp, err)
774
775 if !cfg.ModulesEnabled && path != cleanImport(path) {
776 p.Error = &PackageError{
777 ImportStack: stk.Copy(),
778 Err: ImportErrorf(path, "non-canonical import path %q: should be %q", path, pathpkg.Clean(path)),
779 }
780 p.Incomplete = true
781 p.Error.setPos(importPos)
782 }
783 }
784
785
786 if perr := disallowInternal(ld, ctx, srcDir, parent, parentPath, p, stk); perr != nil {
787 perr.setPos(importPos)
788 return p, perr
789 }
790 if mode&ResolveImport != 0 {
791 if perr := disallowVendor(srcDir, path, parentPath, p, stk); perr != nil {
792 perr.setPos(importPos)
793 return p, perr
794 }
795 }
796
797 if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
798 perr := &PackageError{
799 ImportStack: stk.Copy(),
800 Err: ImportErrorf(path, "import %q is a program, not an importable package", path),
801 }
802 perr.setPos(importPos)
803 return p, perr
804 }
805
806 if p.Internal.Local && parent != nil && !parent.Internal.Local {
807 var err error
808 if path == "." {
809 err = ImportErrorf(path, "%s: cannot import current directory", path)
810 } else {
811 err = ImportErrorf(path, "local import %q in non-local package", path)
812 }
813 perr := &PackageError{
814 ImportStack: stk.Copy(),
815 Err: err,
816 }
817 perr.setPos(importPos)
818 return p, perr
819 }
820
821 return p, nil
822 }
823
824 func extractFirstImport(importPos []token.Position) *token.Position {
825 if len(importPos) == 0 {
826 return nil
827 }
828 return &importPos[0]
829 }
830
831
832
833
834
835
836
837
838
839
840 func loadPackageData(ld *modload.Loader, ctx context.Context, path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
841 ctx, span := trace.StartSpan(ctx, "load.loadPackageData "+path)
842 defer span.Done()
843
844 if path == "" {
845 panic("loadPackageData called with empty package path")
846 }
847
848 if strings.HasPrefix(path, "mod/") {
849
850
851
852
853
854 return nil, false, fmt.Errorf("disallowed import path %q", path)
855 }
856
857 if strings.Contains(path, "@") {
858 return nil, false, errors.New("can only use path@version syntax with 'go get' and 'go install' in module-aware mode")
859 }
860
861
862
863
864
865
866
867
868
869
870
871 importKey := importSpec{
872 path: path,
873 parentPath: parentPath,
874 parentDir: parentDir,
875 parentRoot: parentRoot,
876 parentIsStd: parentIsStd,
877 mode: mode,
878 }
879 r := resolvedImportCache.Do(importKey, func() resolvedImport {
880 var r resolvedImport
881 if newPath, dir, ok := fips140.ResolveImport(path); ok {
882 r.path = newPath
883 r.dir = dir
884 } else if cfg.ModulesEnabled {
885 r.dir, r.path, r.err = modload.Lookup(ld, parentPath, parentIsStd, path)
886 } else if build.IsLocalImport(path) {
887 r.dir = filepath.Join(parentDir, path)
888 r.path = dirToImportPath(r.dir)
889 } else if mode&ResolveImport != 0 {
890
891
892
893
894 r.path = resolveImportPath(ld, path, parentPath, parentDir, parentRoot, parentIsStd)
895 } else if mode&ResolveModule != 0 {
896 r.path = moduleImportPath(path, parentPath, parentDir, parentRoot)
897 }
898 if r.path == "" {
899 r.path = path
900 }
901 return r
902 })
903
904
905
906
907
908
909 p, err := packageDataCache.Do(r.path, func() (*build.Package, error) {
910 loaded = true
911 var data struct {
912 p *build.Package
913 err error
914 }
915 if r.dir != "" {
916 var buildMode build.ImportMode
917 buildContext := cfg.BuildContext
918 if !cfg.ModulesEnabled {
919 buildMode = build.ImportComment
920 } else {
921 buildContext.GOPATH = ""
922 }
923 modroot := modload.PackageModRoot(ld, ctx, r.path)
924 if modroot == "" && str.HasFilePathPrefix(r.dir, cfg.GOROOTsrc) {
925 modroot = cfg.GOROOTsrc
926 gorootSrcCmd := filepath.Join(cfg.GOROOTsrc, "cmd")
927 if str.HasFilePathPrefix(r.dir, gorootSrcCmd) {
928 modroot = gorootSrcCmd
929 }
930 }
931 if modroot == "" && cfg.BuildMod == "vendor" && ld.Enabled() {
932
933
934
935
936
937
938 for _, m := range ld.MainModules.Versions() {
939 root := ld.MainModules.ModRoot(m)
940 if root != "" && str.HasFilePathPrefix(r.dir, root) && len(root) > len(modroot) {
941 modroot = root
942 }
943 }
944 }
945 if modroot != "" {
946 if rp, err := modindex.GetPackage(modroot, r.dir); err == nil {
947 data.p, data.err = rp.Import(cfg.BuildContext, buildMode)
948 goto Happy
949 } else if !errors.Is(err, modindex.ErrNotIndexed) {
950 base.Fatal(err)
951 }
952 }
953 data.p, data.err = buildContext.ImportDir(r.dir, buildMode)
954 Happy:
955 if cfg.ModulesEnabled {
956
957
958 if info := modload.PackageModuleInfo(ld, ctx, path); info != nil {
959 data.p.Root = info.Dir
960 }
961 }
962 if r.err != nil {
963 if data.err != nil {
964
965
966
967
968 } else if errors.Is(r.err, imports.ErrNoGo) {
969
970
971
972
973
974
975
976
977
978
979 } else {
980 data.err = r.err
981 }
982 }
983 } else if r.err != nil {
984 data.p = new(build.Package)
985 data.err = r.err
986 } else if cfg.ModulesEnabled && path != "unsafe" {
987 data.p = new(build.Package)
988 data.err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", r.path)
989 } else {
990 buildMode := build.ImportComment
991 if mode&ResolveImport == 0 || r.path != path {
992
993 buildMode |= build.IgnoreVendor
994 }
995 data.p, data.err = cfg.BuildContext.Import(r.path, parentDir, buildMode)
996 }
997 data.p.ImportPath = r.path
998
999
1000
1001 if !data.p.Goroot {
1002 if cfg.GOBIN != "" {
1003 data.p.BinDir = cfg.GOBIN
1004 } else if cfg.ModulesEnabled {
1005 data.p.BinDir = modload.BinDir(ld)
1006 }
1007 }
1008
1009 if !cfg.ModulesEnabled && data.err == nil &&
1010 data.p.ImportComment != "" && data.p.ImportComment != path &&
1011 !strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
1012 data.err = fmt.Errorf("code in directory %s expects import %q", data.p.Dir, data.p.ImportComment)
1013 }
1014 return data.p, data.err
1015 })
1016
1017 return p, loaded, err
1018 }
1019
1020
1021
1022 type importSpec struct {
1023 path string
1024 parentPath, parentDir, parentRoot string
1025 parentIsStd bool
1026 mode int
1027 }
1028
1029
1030
1031
1032 type resolvedImport struct {
1033 path, dir string
1034 err error
1035 }
1036
1037
1038 var resolvedImportCache par.Cache[importSpec, resolvedImport]
1039
1040
1041 var packageDataCache par.ErrCache[string, *build.Package]
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055 var preloadWorkerCount = runtime.GOMAXPROCS(0)
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066 type preload struct {
1067 cancel chan struct{}
1068 queue *par.Queue
1069 }
1070
1071
1072
1073 func newPreload() *preload {
1074 pre := &preload{
1075 cancel: make(chan struct{}),
1076 queue: par.NewQueue(preloadWorkerCount),
1077 }
1078 return pre
1079 }
1080
1081
1082
1083
1084 func (pre *preload) preloadMatches(ld *modload.Loader, ctx context.Context, opts PackageOpts, matches []*search.Match) {
1085 for _, m := range matches {
1086 for _, pkg := range m.Pkgs {
1087 pre.queue.Add(func() {
1088 select {
1089 case <-pre.cancel:
1090 return
1091 default:
1092 }
1093 mode := 0
1094 bp, loaded, err := loadPackageData(ld, ctx, pkg, "", base.Cwd(), "", false, mode)
1095 if bp != nil && loaded && err == nil && !opts.IgnoreImports {
1096 pre.preloadImports(ld, ctx, opts, bp.Imports, bp)
1097 }
1098 })
1099 }
1100 }
1101 }
1102
1103
1104
1105
1106 func (pre *preload) preloadImports(ld *modload.Loader, ctx context.Context, opts PackageOpts, imports []string, parent *build.Package) {
1107 parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
1108 for _, path := range imports {
1109 if path == "C" || path == "unsafe" {
1110 continue
1111 }
1112 pre.queue.Add(func() {
1113 select {
1114 case <-pre.cancel:
1115 return
1116 default:
1117 }
1118 bp, loaded, err := loadPackageData(ld, ctx, path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
1119 if bp != nil && loaded && err == nil && !opts.IgnoreImports {
1120 pre.preloadImports(ld, ctx, opts, bp.Imports, bp)
1121 }
1122 })
1123 }
1124 }
1125
1126
1127
1128
1129 func (pre *preload) flush() {
1130
1131
1132 if v := recover(); v != nil {
1133 panic(v)
1134 }
1135
1136 close(pre.cancel)
1137 <-pre.queue.Idle()
1138 }
1139
1140 func cleanImport(path string) string {
1141 orig := path
1142 path = pathpkg.Clean(path)
1143 if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
1144 path = "./" + path
1145 }
1146 return path
1147 }
1148
1149 var isDirCache par.Cache[string, bool]
1150
1151 func isDir(path string) bool {
1152 return isDirCache.Do(path, func() bool {
1153 fi, err := fsys.Stat(path)
1154 return err == nil && fi.IsDir()
1155 })
1156 }
1157
1158
1159
1160
1161
1162
1163 func ResolveImportPath(s *modload.Loader, parent *Package, path string) (found string) {
1164 var parentPath, parentDir, parentRoot string
1165 parentIsStd := false
1166 if parent != nil {
1167 parentPath = parent.ImportPath
1168 parentDir = parent.Dir
1169 parentRoot = parent.Root
1170 parentIsStd = parent.Standard
1171 }
1172 return resolveImportPath(s, path, parentPath, parentDir, parentRoot, parentIsStd)
1173 }
1174
1175 func resolveImportPath(s *modload.Loader, path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
1176 if cfg.ModulesEnabled {
1177 if _, p, e := modload.Lookup(s, parentPath, parentIsStd, path); e == nil {
1178 return p
1179 }
1180 return path
1181 }
1182 found = vendoredImportPath(path, parentPath, parentDir, parentRoot)
1183 if found != path {
1184 return found
1185 }
1186 return moduleImportPath(path, parentPath, parentDir, parentRoot)
1187 }
1188
1189
1190
1191 func dirAndRoot(path string, dir, root string) (string, string) {
1192 origDir, origRoot := dir, root
1193 dir = filepath.Clean(dir)
1194 root = filepath.Join(root, "src")
1195 if !str.HasFilePathPrefix(dir, root) || path != "command-line-arguments" && filepath.Join(root, path) != dir {
1196
1197 dir = expandPath(dir)
1198 root = expandPath(root)
1199 }
1200
1201 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 {
1202 debug.PrintStack()
1203 base.Fatalf("unexpected directory layout:\n"+
1204 " import path: %s\n"+
1205 " root: %s\n"+
1206 " dir: %s\n"+
1207 " expand root: %s\n"+
1208 " expand dir: %s\n"+
1209 " separator: %s",
1210 path,
1211 filepath.Join(origRoot, "src"),
1212 filepath.Clean(origDir),
1213 origRoot,
1214 origDir,
1215 string(filepath.Separator))
1216 }
1217
1218 return dir, root
1219 }
1220
1221
1222
1223
1224
1225 func vendoredImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1226 if parentRoot == "" {
1227 return path
1228 }
1229
1230 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1231
1232 vpath := "vendor/" + path
1233 for i := len(dir); i >= len(root); i-- {
1234 if i < len(dir) && dir[i] != filepath.Separator {
1235 continue
1236 }
1237
1238
1239
1240
1241 if !isDir(filepath.Join(dir[:i], "vendor")) {
1242 continue
1243 }
1244 targ := filepath.Join(dir[:i], vpath)
1245 if isDir(targ) && hasGoFiles(targ) {
1246 importPath := parentPath
1247 if importPath == "command-line-arguments" {
1248
1249
1250 importPath = dir[len(root)+1:]
1251 }
1252
1253
1254
1255
1256
1257
1258
1259
1260 chopped := len(dir) - i
1261 if chopped == len(importPath)+1 {
1262
1263
1264
1265
1266 return vpath
1267 }
1268 return importPath[:len(importPath)-chopped] + "/" + vpath
1269 }
1270 }
1271 return path
1272 }
1273
1274 var (
1275 modulePrefix = []byte("\nmodule ")
1276 goModPathCache par.Cache[string, string]
1277 )
1278
1279
1280 func goModPath(dir string) (path string) {
1281 return goModPathCache.Do(dir, func() string {
1282 data, err := os.ReadFile(filepath.Join(dir, "go.mod"))
1283 if err != nil {
1284 return ""
1285 }
1286 var i int
1287 if bytes.HasPrefix(data, modulePrefix[1:]) {
1288 i = 0
1289 } else {
1290 i = bytes.Index(data, modulePrefix)
1291 if i < 0 {
1292 return ""
1293 }
1294 i++
1295 }
1296 line := data[i:]
1297
1298
1299 if j := bytes.IndexByte(line, '\n'); j >= 0 {
1300 line = line[:j]
1301 }
1302 if line[len(line)-1] == '\r' {
1303 line = line[:len(line)-1]
1304 }
1305 line = line[len("module "):]
1306
1307
1308 path = strings.TrimSpace(string(line))
1309 if path != "" && path[0] == '"' {
1310 s, err := strconv.Unquote(path)
1311 if err != nil {
1312 return ""
1313 }
1314 path = s
1315 }
1316 return path
1317 })
1318 }
1319
1320
1321
1322 func findVersionElement(path string) (i, j int) {
1323 j = len(path)
1324 for i = len(path) - 1; i >= 0; i-- {
1325 if path[i] == '/' {
1326 if isVersionElement(path[i+1 : j]) {
1327 return i, j
1328 }
1329 j = i
1330 }
1331 }
1332 return -1, -1
1333 }
1334
1335
1336
1337 func isVersionElement(s string) bool {
1338 if len(s) < 2 || s[0] != 'v' || s[1] == '0' || s[1] == '1' && len(s) == 2 {
1339 return false
1340 }
1341 for i := 1; i < len(s); i++ {
1342 if s[i] < '0' || '9' < s[i] {
1343 return false
1344 }
1345 }
1346 return true
1347 }
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357 func moduleImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
1358 if parentRoot == "" {
1359 return path
1360 }
1361
1362
1363
1364
1365
1366 if i, _ := findVersionElement(path); i < 0 {
1367 return path
1368 }
1369
1370 dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
1371
1372
1373 for i := len(dir); i >= len(root); i-- {
1374 if i < len(dir) && dir[i] != filepath.Separator {
1375 continue
1376 }
1377 if goModPath(dir[:i]) != "" {
1378 goto HaveGoMod
1379 }
1380 }
1381
1382
1383 return path
1384
1385 HaveGoMod:
1386
1387
1388
1389
1390
1391 if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
1392 return path
1393 }
1394
1395
1396
1397
1398
1399
1400 limit := len(path)
1401 for limit > 0 {
1402 i, j := findVersionElement(path[:limit])
1403 if i < 0 {
1404 return path
1405 }
1406 if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
1407 if mpath := goModPath(bp.Dir); mpath != "" {
1408
1409
1410
1411 if mpath == path[:j] {
1412 return path[:i] + path[j:]
1413 }
1414
1415
1416
1417
1418 return path
1419 }
1420 }
1421 limit = i
1422 }
1423 return path
1424 }
1425
1426
1427
1428
1429
1430 func hasGoFiles(dir string) bool {
1431 files, _ := os.ReadDir(dir)
1432 for _, f := range files {
1433 if !f.IsDir() && strings.HasSuffix(f.Name(), ".go") {
1434 return true
1435 }
1436 }
1437 return false
1438 }
1439
1440
1441
1442
1443 func reusePackage(p *Package, stk *ImportStack) *Package {
1444
1445
1446
1447 if p.Internal.Imports == nil {
1448 if p.Error == nil {
1449 p.Error = &PackageError{
1450 ImportStack: stk.Copy(),
1451 Err: errors.New("import cycle not allowed"),
1452 IsImportCycle: true,
1453 }
1454 } else if !p.Error.IsImportCycle {
1455
1456
1457
1458 p.Error.IsImportCycle = true
1459 }
1460 p.Incomplete = true
1461 }
1462
1463
1464 if p.Error != nil && p.Error.ImportStack != nil &&
1465 !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack.Pkgs()) {
1466 p.Error.ImportStack = stk.Copy()
1467 }
1468 return p
1469 }
1470
1471
1472
1473
1474
1475 func disallowInternal(ld *modload.Loader, ctx context.Context, srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *PackageError {
1476
1477
1478
1479
1480
1481
1482 if p.Error != nil {
1483 return nil
1484 }
1485
1486
1487
1488
1489
1490 if str.HasPathPrefix(p.ImportPath, "testing/internal") && importerPath == "testmain" {
1491 return nil
1492 }
1493
1494
1495 if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
1496 return nil
1497 }
1498
1499
1500
1501
1502 if p.Standard && strings.HasPrefix(importerPath, "bootstrap/") {
1503 return nil
1504 }
1505
1506
1507
1508
1509 if importerPath == "" {
1510 return nil
1511 }
1512
1513
1514 i, ok := findInternal(p.ImportPath)
1515 if !ok {
1516 return nil
1517 }
1518
1519
1520
1521 if i > 0 {
1522 i--
1523 }
1524
1525
1526
1527
1528
1529
1530
1531
1532 if str.HasPathPrefix(importerPath, "crypto") && str.HasPathPrefix(p.ImportPath, "crypto/internal/fips140") {
1533 return nil
1534 }
1535 if str.HasPathPrefix(importerPath, "crypto/internal/fips140") {
1536 if str.HasPathPrefix(p.ImportPath, "crypto/internal") {
1537 return nil
1538 }
1539 goto Error
1540 }
1541
1542 if p.Module == nil {
1543 parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
1544
1545 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1546 return nil
1547 }
1548
1549
1550 srcDir = expandPath(srcDir)
1551 parent = expandPath(parent)
1552 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1553 return nil
1554 }
1555 } else {
1556
1557
1558 if importer.Internal.CmdlineFiles {
1559
1560
1561
1562
1563
1564 importerPath, _ = ld.MainModules.DirImportPath(ld, ctx, importer.Dir)
1565 }
1566 parentOfInternal := p.ImportPath[:i]
1567 if str.HasPathPrefix(importerPath, parentOfInternal) {
1568 return nil
1569 }
1570 }
1571
1572 Error:
1573
1574 perr := &PackageError{
1575 alwaysPrintStack: true,
1576 ImportStack: stk.Copy(),
1577 Err: ImportErrorf(p.ImportPath, "use of internal package %s not allowed", p.ImportPath),
1578 }
1579 return perr
1580 }
1581
1582
1583
1584
1585 func findInternal(path string) (index int, ok bool) {
1586
1587
1588
1589
1590 switch {
1591 case strings.HasSuffix(path, "/internal"):
1592 return len(path) - len("internal"), true
1593 case strings.Contains(path, "/internal/"):
1594 return strings.LastIndex(path, "/internal/") + 1, true
1595 case path == "internal", strings.HasPrefix(path, "internal/"):
1596 return 0, true
1597 }
1598 return 0, false
1599 }
1600
1601
1602
1603
1604 func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *PackageError {
1605
1606
1607
1608 if importerPath == "" {
1609 return nil
1610 }
1611
1612 if perr := disallowVendorVisibility(srcDir, p, importerPath, stk); perr != nil {
1613 return perr
1614 }
1615
1616
1617 if i, ok := FindVendor(path); ok {
1618 perr := &PackageError{
1619 ImportStack: stk.Copy(),
1620 Err: ImportErrorf(path, "%s must be imported as %s", path, path[i+len("vendor/"):]),
1621 }
1622 return perr
1623 }
1624
1625 return nil
1626 }
1627
1628
1629
1630
1631
1632
1633 func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *PackageError {
1634
1635
1636
1637
1638 if importerPath == "" {
1639 return nil
1640 }
1641
1642
1643 i, ok := FindVendor(p.ImportPath)
1644 if !ok {
1645 return nil
1646 }
1647
1648
1649
1650 if i > 0 {
1651 i--
1652 }
1653 truncateTo := i + len(p.Dir) - len(p.ImportPath)
1654 if truncateTo < 0 || len(p.Dir) < truncateTo {
1655 return nil
1656 }
1657 parent := p.Dir[:truncateTo]
1658 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1659 return nil
1660 }
1661
1662
1663 srcDir = expandPath(srcDir)
1664 parent = expandPath(parent)
1665 if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
1666 return nil
1667 }
1668
1669
1670
1671 perr := &PackageError{
1672 ImportStack: stk.Copy(),
1673 Err: errors.New("use of vendored package not allowed"),
1674 }
1675 return perr
1676 }
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686 func FindVendor(path string) (index int, ok bool) {
1687
1688
1689
1690 switch {
1691 case strings.Contains(path, "/vendor/"):
1692 return strings.LastIndex(path, "/vendor/") + 1, true
1693 case strings.HasPrefix(path, "vendor/"):
1694 return 0, true
1695 }
1696 return 0, false
1697 }
1698
1699 type TargetDir int
1700
1701 const (
1702 ToTool TargetDir = iota
1703 ToBin
1704 )
1705
1706
1707 func InstallTargetDir(p *Package) TargetDir {
1708 if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
1709 switch p.ImportPath {
1710 case "cmd/go", "cmd/gofmt":
1711 return ToBin
1712 }
1713 return ToTool
1714 }
1715 return ToBin
1716 }
1717
1718 var cgoExclude = map[string]bool{
1719 "runtime/cgo": true,
1720 }
1721
1722 var cgoSyscallExclude = map[string]bool{
1723 "runtime/cgo": true,
1724 "runtime/race": true,
1725 "runtime/msan": true,
1726 "runtime/asan": true,
1727 }
1728
1729 var foldPath = make(map[string]string)
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739 func (p *Package) exeFromImportPath() string {
1740 _, elem := pathpkg.Split(p.ImportPath)
1741 if cfg.ModulesEnabled {
1742
1743
1744 if elem != p.ImportPath && isVersionElement(elem) {
1745 _, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath))
1746 }
1747 }
1748 return elem
1749 }
1750
1751
1752
1753
1754
1755 func (p *Package) exeFromFiles() string {
1756 var src string
1757 if len(p.GoFiles) > 0 {
1758 src = p.GoFiles[0]
1759 } else if len(p.CgoFiles) > 0 {
1760 src = p.CgoFiles[0]
1761 } else {
1762 return ""
1763 }
1764 _, elem := filepath.Split(src)
1765 return elem[:len(elem)-len(".go")]
1766 }
1767
1768
1769 func (p *Package) DefaultExecName() string {
1770 if p.Internal.CmdlineFiles {
1771 return p.exeFromFiles()
1772 }
1773 return p.exeFromImportPath()
1774 }
1775
1776
1777
1778
1779 func (p *Package) load(ld *modload.Loader, ctx context.Context, opts PackageOpts, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
1780 p.copyBuild(opts, bp)
1781
1782
1783
1784
1785 if p.Internal.Local && !cfg.ModulesEnabled {
1786 p.Internal.LocalPrefix = dirToImportPath(p.Dir)
1787 }
1788
1789
1790
1791
1792 setError := func(err error) {
1793 if p.Error == nil {
1794 p.Error = &PackageError{
1795 ImportStack: stk.Copy(),
1796 Err: err,
1797 }
1798 p.Incomplete = true
1799
1800
1801
1802
1803
1804
1805
1806 top, ok := stk.Top()
1807 if ok && path != top.Pkg && len(importPos) > 0 {
1808 p.Error.setPos(importPos)
1809 }
1810 }
1811 }
1812
1813 if err != nil {
1814 p.Incomplete = true
1815 p.setLoadPackageDataError(err, path, stk, importPos)
1816 }
1817
1818 useBindir := p.Name == "main"
1819 if !p.Standard {
1820 switch cfg.BuildBuildmode {
1821 case "c-archive", "c-shared", "plugin":
1822 useBindir = false
1823 }
1824 }
1825
1826 if useBindir {
1827 elem := p.DefaultExecName() + cfg.ExeSuffix
1828 full := filepath.Join(cfg.BuildContext.GOOS+"_"+cfg.BuildContext.GOARCH, elem)
1829 if cfg.BuildContext.GOOS != runtime.GOOS || cfg.BuildContext.GOARCH != runtime.GOARCH {
1830
1831 elem = full
1832 }
1833 if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
1834 p.Internal.Build.BinDir = modload.BinDir(ld)
1835 }
1836 if p.Internal.Build.BinDir != "" {
1837
1838 p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
1839 if !p.Goroot && strings.Contains(elem, string(filepath.Separator)) && cfg.GOBIN != "" {
1840
1841 p.Target = ""
1842 p.Internal.GobinSubdir = true
1843 }
1844 }
1845 if InstallTargetDir(p) == ToTool {
1846
1847
1848 if cfg.BuildToolchainName == "gccgo" {
1849 p.Target = filepath.Join(build.ToolDir, elem)
1850 } else {
1851 p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
1852 }
1853 }
1854 } else if p.Internal.Local {
1855
1856
1857 p.Target = ""
1858 } else if p.Standard && cfg.BuildContext.Compiler == "gccgo" {
1859
1860 p.Target = ""
1861 } else {
1862 p.Target = p.Internal.Build.PkgObj
1863 if cfg.BuildBuildmode == "shared" && p.Internal.Build.PkgTargetRoot != "" {
1864
1865
1866
1867 p.Target = filepath.Join(p.Internal.Build.PkgTargetRoot, p.ImportPath+".a")
1868 }
1869 if cfg.BuildLinkshared && p.Internal.Build.PkgTargetRoot != "" {
1870
1871
1872
1873 targetPrefix := filepath.Join(p.Internal.Build.PkgTargetRoot, p.ImportPath)
1874 p.Target = targetPrefix + ".a"
1875 shlibnamefile := targetPrefix + ".shlibname"
1876 shlib, err := os.ReadFile(shlibnamefile)
1877 if err != nil && !os.IsNotExist(err) {
1878 base.Fatalf("reading shlibname: %v", err)
1879 }
1880 if err == nil {
1881 libname := strings.TrimSpace(string(shlib))
1882 if cfg.BuildContext.Compiler == "gccgo" {
1883 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
1884 } else {
1885 p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
1886 }
1887 }
1888 }
1889 }
1890
1891
1892
1893 importPaths := p.Imports
1894 addImport := func(path string, forCompiler bool) {
1895 for _, p := range importPaths {
1896 if path == p {
1897 return
1898 }
1899 }
1900 importPaths = append(importPaths, path)
1901 if forCompiler {
1902 p.Internal.CompiledImports = append(p.Internal.CompiledImports, path)
1903 }
1904 }
1905
1906 if !opts.IgnoreImports {
1907
1908
1909 if p.UsesCgo() {
1910 addImport("unsafe", true)
1911 }
1912 if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
1913 addImport("runtime/cgo", true)
1914 }
1915 if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
1916 addImport("syscall", true)
1917 }
1918
1919
1920 if p.UsesSwig() && cfg.BuildContext.CgoEnabled == build.CgoEnabled && !p.UsesCgoBinding() {
1921 addImport("unsafe", true)
1922 if cfg.BuildContext.Compiler != "gccgo" {
1923 addImport("runtime/cgo", true)
1924 }
1925 addImport("syscall", true)
1926 addImport("sync", true)
1927
1928
1929
1930 }
1931
1932
1933 if p.Name == "main" && !p.Internal.ForceLibrary {
1934 ldDeps, err := LinkerDeps(ld, p)
1935 if err != nil {
1936 setError(err)
1937 return
1938 }
1939 for _, dep := range ldDeps {
1940 addImport(dep, false)
1941 }
1942 }
1943 }
1944
1945
1946
1947
1948 fold := str.ToFold(p.ImportPath)
1949 if other := foldPath[fold]; other == "" {
1950 foldPath[fold] = p.ImportPath
1951 } else if other != p.ImportPath {
1952 setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
1953 return
1954 }
1955
1956 if !SafeArg(p.ImportPath) {
1957 setError(ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath))
1958 return
1959 }
1960
1961
1962
1963
1964 stk.Push(ImportInfo{Pkg: path, Pos: extractFirstImport(importPos)})
1965 defer stk.Pop()
1966
1967 if p.BinaryOnly {
1968 setError(errors.New("binary-only packages are no longer supported"))
1969 }
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(ld, ctx, pkgPath)
1977 }
1978 p.DefaultGODEBUG = defaultGODEBUG(ld, 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
1991
1992
1993
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
2002
2003
2004
2005
2006
2007
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
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(ld, 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
2049
2050
2051
2052 p.setBuildInfo(ctx, ld.Fetcher(), opts.AutoVCS)
2053 }
2054
2055
2056
2057
2058
2059 if cfg.BuildContext.CgoEnabled != build.CgoEnabled && !p.UsesCgoBinding() {
2060 p.CFiles = nil
2061 p.CXXFiles = nil
2062 p.MFiles = nil
2063 p.SwigFiles = nil
2064 p.SwigCXXFiles = nil
2065
2066
2067
2068
2069 }
2070
2071 if cfg.RestrictedBuild() && !p.Standard && len(p.SysoFiles) > 0 {
2072 setError(fmt.Errorf(".syso files not allowed when GORESTRICTEDBUILD=1: %s", strings.Join(p.SysoFiles, " ")))
2073 return
2074 }
2075
2076
2077 if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
2078 setError(fmt.Errorf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
2079 return
2080 }
2081
2082
2083
2084 if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
2085 setError(fmt.Errorf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
2086 return
2087 }
2088 if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
2089 setError(fmt.Errorf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
2090 return
2091 }
2092 if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
2093 setError(fmt.Errorf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
2094 return
2095 }
2096
2097
2098
2099
2100 if p.UsesCgoBinding() {
2101 var files []string
2102 for _, list := range [][]string{p.CFiles, p.CXXFiles, p.MFiles, p.FFiles, p.SwigFiles, p.SwigCXXFiles} {
2103 files = append(files, list...)
2104 }
2105 for _, f := range p.SFiles {
2106 if strings.HasSuffix(f, ".S") || strings.HasSuffix(f, ".sx") {
2107 files = append(files, f)
2108 }
2109 }
2110 if len(files) > 0 {
2111 setError(fmt.Errorf("source files requiring a C compiler not allowed in a package using cgo binding pragmas: %s", strings.Join(files, " ")))
2112 return
2113 }
2114 }
2115 }
2116
2117
2118 type EmbedError struct {
2119 Pattern string
2120 Err error
2121 }
2122
2123 func (e *EmbedError) Error() string {
2124 return fmt.Sprintf("pattern %s: %v", e.Pattern, e.Err)
2125 }
2126
2127 func (e *EmbedError) Unwrap() error {
2128 return e.Err
2129 }
2130
2131
2132
2133
2134
2135
2136 func ResolveEmbed(dir string, patterns []string) ([]string, error) {
2137 files, _, err := resolveEmbed(dir, patterns)
2138 return files, err
2139 }
2140
2141 var embedfollowsymlinks = godebug.New("embedfollowsymlinks")
2142
2143
2144
2145
2146
2147 func resolveEmbed(pkgdir string, patterns []string) (files []string, pmap map[string][]string, err error) {
2148 var pattern string
2149 defer func() {
2150 if err != nil {
2151 err = &EmbedError{
2152 Pattern: pattern,
2153 Err: err,
2154 }
2155 }
2156 }()
2157
2158
2159 pmap = make(map[string][]string)
2160 have := make(map[string]int)
2161 dirOK := make(map[string]bool)
2162 pid := 0
2163 for _, pattern = range patterns {
2164 pid++
2165
2166 glob, all := strings.CutPrefix(pattern, "all:")
2167
2168 if _, err := pathpkg.Match(glob, ""); err != nil || !validEmbedPattern(glob) {
2169 return nil, nil, fmt.Errorf("invalid pattern syntax")
2170 }
2171
2172
2173 match, err := fsys.Glob(str.QuoteGlob(str.WithFilePathSeparator(pkgdir)) + filepath.FromSlash(glob))
2174 if err != nil {
2175 return nil, nil, err
2176 }
2177
2178
2179
2180
2181
2182 var list []string
2183 for _, file := range match {
2184
2185 rel := filepath.ToSlash(str.TrimFilePathPrefix(file, pkgdir))
2186
2187 what := "file"
2188 info, err := fsys.Lstat(file)
2189 if err != nil {
2190 return nil, nil, err
2191 }
2192 if info.IsDir() {
2193 what = "directory"
2194 }
2195
2196
2197
2198 for dir := file; len(dir) > len(pkgdir)+1 && !dirOK[dir]; dir = filepath.Dir(dir) {
2199 if _, err := fsys.Stat(filepath.Join(dir, "go.mod")); err == nil {
2200 return nil, nil, fmt.Errorf("cannot embed %s %s: in different module", what, rel)
2201 }
2202 if dir != file {
2203 if info, err := fsys.Lstat(dir); err == nil && !info.IsDir() {
2204 return nil, nil, fmt.Errorf("cannot embed %s %s: in non-directory %s", what, rel, dir[len(pkgdir)+1:])
2205 }
2206 }
2207 dirOK[dir] = true
2208 if elem := filepath.Base(dir); isBadEmbedName(elem) {
2209 if dir == file {
2210 return nil, nil, fmt.Errorf("cannot embed %s %s: invalid name %s", what, rel, elem)
2211 } else {
2212 return nil, nil, fmt.Errorf("cannot embed %s %s: in invalid directory %s", what, rel, elem)
2213 }
2214 }
2215 }
2216
2217 switch {
2218 default:
2219 return nil, nil, fmt.Errorf("cannot embed irregular file %s", rel)
2220
2221 case info.Mode().IsRegular():
2222 if have[rel] != pid {
2223 have[rel] = pid
2224 list = append(list, rel)
2225 }
2226
2227
2228
2229
2230
2231 case embedfollowsymlinks.Value() == "1" && info.Mode()&fs.ModeType == fs.ModeSymlink:
2232 info, err := fsys.Stat(file)
2233 if err != nil {
2234 return nil, nil, err
2235 }
2236 if !info.Mode().IsRegular() {
2237 return nil, nil, fmt.Errorf("cannot embed irregular file %s", rel)
2238 }
2239 if have[rel] != pid {
2240 embedfollowsymlinks.IncNonDefault()
2241 have[rel] = pid
2242 list = append(list, rel)
2243 }
2244
2245 case info.IsDir():
2246
2247
2248 count := 0
2249 err := fsys.WalkDir(file, func(path string, d fs.DirEntry, err error) error {
2250 if err != nil {
2251 return err
2252 }
2253 rel := filepath.ToSlash(str.TrimFilePathPrefix(path, pkgdir))
2254 name := d.Name()
2255 if path != file && (isBadEmbedName(name) || ((name[0] == '.' || name[0] == '_') && !all)) {
2256
2257
2258 if d.IsDir() {
2259 return fs.SkipDir
2260 }
2261
2262 if name[0] == '.' || name[0] == '_' {
2263 return nil
2264 }
2265
2266
2267 if isBadEmbedName(name) {
2268 return fmt.Errorf("cannot embed file %s: invalid name %s", rel, name)
2269 }
2270 return nil
2271 }
2272 if d.IsDir() {
2273 if _, err := fsys.Stat(filepath.Join(path, "go.mod")); err == nil {
2274 return filepath.SkipDir
2275 }
2276 return nil
2277 }
2278 if !d.Type().IsRegular() {
2279 return nil
2280 }
2281 count++
2282 if have[rel] != pid {
2283 have[rel] = pid
2284 list = append(list, rel)
2285 }
2286 return nil
2287 })
2288 if err != nil {
2289 return nil, nil, err
2290 }
2291 if count == 0 {
2292 return nil, nil, fmt.Errorf("cannot embed directory %s: contains no embeddable files", rel)
2293 }
2294 }
2295 }
2296
2297 if len(list) == 0 {
2298 return nil, nil, fmt.Errorf("no matching files found")
2299 }
2300 sort.Strings(list)
2301 pmap[pattern] = list
2302 }
2303
2304 for file := range have {
2305 files = append(files, file)
2306 }
2307 sort.Strings(files)
2308 return files, pmap, nil
2309 }
2310
2311 func validEmbedPattern(pattern string) bool {
2312 return pattern != "." && fs.ValidPath(pattern)
2313 }
2314
2315
2316
2317
2318 func isBadEmbedName(name string) bool {
2319 if err := module.CheckFilePath(name); err != nil {
2320 return true
2321 }
2322 switch name {
2323
2324 case "":
2325 return true
2326
2327
2328
2329 case ".bzr", ".hg", ".git", ".svn":
2330 return true
2331 }
2332 return false
2333 }
2334
2335
2336
2337 var vcsStatusCache par.ErrCache[string, vcs.Status]
2338
2339 func appendBuildSetting(info *debug.BuildInfo, key, value string) {
2340 value = strings.ReplaceAll(value, "\n", " ")
2341 info.Settings = append(info.Settings, debug.BuildSetting{Key: key, Value: value})
2342 }
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353 func (p *Package) setBuildInfo(ctx context.Context, f *modfetch.Fetcher, autoVCS bool) {
2354 setPkgErrorf := func(format string, args ...any) {
2355 if p.Error == nil {
2356 p.Error = &PackageError{Err: fmt.Errorf(format, args...)}
2357 p.Incomplete = true
2358 }
2359 }
2360
2361 var debugModFromModinfo func(*modinfo.ModulePublic) *debug.Module
2362 debugModFromModinfo = func(mi *modinfo.ModulePublic) *debug.Module {
2363 version := mi.Version
2364 if version == "" {
2365 version = "(devel)"
2366 }
2367 dm := &debug.Module{
2368 Path: mi.Path,
2369 Version: version,
2370 }
2371 if mi.Replace != nil {
2372 dm.Replace = debugModFromModinfo(mi.Replace)
2373 } else if mi.Version != "" && cfg.BuildMod != "vendor" {
2374 dm.Sum = modfetch.Sum(ctx, module.Version{Path: mi.Path, Version: mi.Version})
2375 }
2376 return dm
2377 }
2378
2379 var main debug.Module
2380 if p.Module != nil {
2381 main = *debugModFromModinfo(p.Module)
2382 }
2383
2384 visited := make(map[*Package]bool)
2385 mdeps := make(map[module.Version]*debug.Module)
2386 var q []*Package
2387 q = append(q, p.Internal.Imports...)
2388 for len(q) > 0 {
2389 p1 := q[0]
2390 q = q[1:]
2391 if visited[p1] {
2392 continue
2393 }
2394 visited[p1] = true
2395 if p1.Module != nil {
2396 m := module.Version{Path: p1.Module.Path, Version: p1.Module.Version}
2397 if p1.Module.Path != main.Path && mdeps[m] == nil {
2398 mdeps[m] = debugModFromModinfo(p1.Module)
2399 }
2400 }
2401 q = append(q, p1.Internal.Imports...)
2402 }
2403 sortedMods := make([]module.Version, 0, len(mdeps))
2404 for mod := range mdeps {
2405 sortedMods = append(sortedMods, mod)
2406 }
2407 gover.ModSort(sortedMods)
2408 deps := make([]*debug.Module, len(sortedMods))
2409 for i, mod := range sortedMods {
2410 deps[i] = mdeps[mod]
2411 }
2412
2413 pkgPath := p.ImportPath
2414 if p.Internal.CmdlineFiles {
2415 pkgPath = "command-line-arguments"
2416 }
2417 info := &debug.BuildInfo{
2418 Path: pkgPath,
2419 Main: main,
2420 Deps: deps,
2421 }
2422 appendSetting := func(key, value string) {
2423 appendBuildSetting(info, key, value)
2424 }
2425
2426
2427
2428
2429 if cfg.BuildASan {
2430 appendSetting("-asan", "true")
2431 }
2432 if BuildAsmflags.present {
2433 appendSetting("-asmflags", BuildAsmflags.String())
2434 }
2435 buildmode := cfg.BuildBuildmode
2436 if buildmode == "default" {
2437 if p.Name == "main" {
2438 buildmode = "exe"
2439 if platform.DefaultPIE(cfg.Goos, cfg.Goarch, cfg.BuildRace) {
2440 buildmode = "pie"
2441 }
2442 } else {
2443 buildmode = "archive"
2444 }
2445 }
2446 appendSetting("-buildmode", buildmode)
2447 appendSetting("-compiler", cfg.BuildContext.Compiler)
2448 if cfg.BuildMod == "vendor" {
2449
2450
2451
2452
2453 appendSetting("-mod", "vendor")
2454 }
2455 if gccgoflags := BuildGccgoflags.String(); gccgoflags != "" && cfg.BuildContext.Compiler == "gccgo" {
2456 appendSetting("-gccgoflags", gccgoflags)
2457 }
2458 if gcflags := BuildGcflags.String(); gcflags != "" && cfg.BuildContext.Compiler == "gc" {
2459 appendSetting("-gcflags", gcflags)
2460 }
2461 if ldflags := BuildLdflags.String(); ldflags != "" {
2462
2463
2464
2465
2466
2467
2468
2469
2470 if !cfg.BuildTrimpath {
2471 appendSetting("-ldflags", ldflags)
2472 }
2473 }
2474 if cfg.BuildCover {
2475 appendSetting("-cover", "true")
2476 }
2477 if cfg.BuildMSan {
2478 appendSetting("-msan", "true")
2479 }
2480
2481 if cfg.BuildRace {
2482 appendSetting("-race", "true")
2483 }
2484 if tags := cfg.BuildContext.BuildTags; len(tags) > 0 {
2485 appendSetting("-tags", strings.Join(tags, ","))
2486 }
2487 if cfg.BuildTrimpath {
2488 appendSetting("-trimpath", "true")
2489 }
2490 if p.DefaultGODEBUG != "" {
2491 appendSetting("DefaultGODEBUG", p.DefaultGODEBUG)
2492 }
2493 cgo := "0"
2494 switch cfg.BuildContext.CgoEnabled {
2495 case build.CgoEnabled:
2496 cgo = "1"
2497 case build.CgoBindings:
2498 cgo = "bindings"
2499 }
2500 appendSetting("CGO_ENABLED", cgo)
2501
2502
2503
2504
2505
2506
2507
2508 if !cfg.BuildTrimpath {
2509 switch cfg.BuildContext.CgoEnabled {
2510 case build.CgoEnabled:
2511 for _, name := range []string{"CGO_CFLAGS", "CGO_CPPFLAGS", "CGO_CXXFLAGS", "CGO_LDFLAGS"} {
2512 appendSetting(name, cfg.Getenv(name))
2513 }
2514 case build.CgoBindings:
2515 appendSetting("CGO_LDFLAGS", cfg.Getenv("CGO_LDFLAGS"))
2516 }
2517 }
2518 appendSetting("GOARCH", cfg.BuildContext.GOARCH)
2519 if cfg.RawGOEXPERIMENT != "" {
2520 appendSetting("GOEXPERIMENT", cfg.RawGOEXPERIMENT)
2521 }
2522 if fips140.Enabled() {
2523 appendSetting("GOFIPS140", fips140.Version())
2524 }
2525 appendSetting("GOOS", cfg.BuildContext.GOOS)
2526 if key, val, _ := cfg.GetArchEnv(); key != "" && val != "" {
2527 appendSetting(key, val)
2528 }
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538 setVCSError := func(err error) {
2539 setPkgErrorf("error obtaining VCS status: %v\n\tUse -buildvcs=false to disable VCS stamping.", err)
2540 }
2541
2542 var repoDir string
2543 var vcsCmd *vcs.Cmd
2544 var err error
2545
2546 wantVCS := false
2547 switch cfg.BuildBuildvcs {
2548 case "true":
2549 wantVCS = true
2550 case "auto":
2551 wantVCS = autoVCS && !p.IsTestOnly()
2552 case "false":
2553 default:
2554 panic(fmt.Sprintf("unexpected value for cfg.BuildBuildvcs: %q", cfg.BuildBuildvcs))
2555 }
2556
2557 if wantVCS && p.Module != nil && p.Module.Version == "" && !p.Standard {
2558 if p.Module.Path == "bootstrap" && cfg.GOROOT == os.Getenv("GOROOT_BOOTSTRAP") {
2559
2560
2561
2562 goto omitVCS
2563 }
2564 repoDir, vcsCmd, err = vcs.FromDir(base.Cwd(), "")
2565 if err != nil && !errors.Is(err, os.ErrNotExist) {
2566 setVCSError(err)
2567 return
2568 }
2569 if !str.HasFilePathPrefix(p.Module.Dir, repoDir) &&
2570 !str.HasFilePathPrefix(repoDir, p.Module.Dir) {
2571
2572
2573
2574
2575 goto omitVCS
2576 }
2577 if cfg.BuildBuildvcs == "auto" && vcsCmd != nil && vcsCmd.Cmd != "" {
2578 if _, err := pathcache.LookPath(vcsCmd.Cmd); err != nil {
2579
2580
2581 goto omitVCS
2582 }
2583 }
2584 }
2585 if repoDir != "" && vcsCmd.Status != nil {
2586
2587
2588
2589
2590
2591 pkgRepoDir, _, err := vcs.FromDir(p.Dir, "")
2592 if err != nil {
2593 setVCSError(err)
2594 return
2595 }
2596 if pkgRepoDir != repoDir {
2597 if cfg.BuildBuildvcs != "auto" {
2598 setVCSError(fmt.Errorf("main package is in repository %q but current directory is in repository %q", pkgRepoDir, repoDir))
2599 return
2600 }
2601 goto omitVCS
2602 }
2603 modRepoDir, _, err := vcs.FromDir(p.Module.Dir, "")
2604 if err != nil {
2605 setVCSError(err)
2606 return
2607 }
2608 if modRepoDir != repoDir {
2609 if cfg.BuildBuildvcs != "auto" {
2610 setVCSError(fmt.Errorf("main module is in repository %q but current directory is in repository %q", modRepoDir, repoDir))
2611 return
2612 }
2613 goto omitVCS
2614 }
2615
2616 st, err := vcsStatusCache.Do(repoDir, func() (vcs.Status, error) {
2617 return vcsCmd.Status(vcsCmd, repoDir)
2618 })
2619 if err != nil {
2620 setVCSError(err)
2621 return
2622 }
2623
2624 appendSetting("vcs", vcsCmd.Cmd)
2625 if st.Revision != "" {
2626 appendSetting("vcs.revision", st.Revision)
2627 }
2628 if !st.CommitTime.IsZero() {
2629 stamp := st.CommitTime.UTC().Format(time.RFC3339Nano)
2630 appendSetting("vcs.time", stamp)
2631 }
2632 appendSetting("vcs.modified", strconv.FormatBool(st.Uncommitted))
2633
2634 rootModPath := goModPath(repoDir)
2635
2636 if rootModPath == "" {
2637 goto omitVCS
2638 }
2639 codeRoot, _, ok := module.SplitPathVersion(rootModPath)
2640 if !ok {
2641 goto omitVCS
2642 }
2643 repo := f.LookupLocal(ctx, codeRoot, p.Module.Path, repoDir)
2644 revInfo, err := repo.Stat(ctx, st.Revision)
2645 if err != nil {
2646 goto omitVCS
2647 }
2648 vers := revInfo.Version
2649 if vers != "" {
2650 if st.Uncommitted {
2651
2652 if strings.HasSuffix(vers, "+incompatible") {
2653 vers += ".dirty"
2654 } else {
2655 vers += "+dirty"
2656 }
2657 }
2658 info.Main.Version = vers
2659 }
2660 }
2661 omitVCS:
2662
2663 p.Internal.BuildInfo = info
2664 }
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675 func SafeArg(name string) bool {
2676 if name == "" {
2677 return false
2678 }
2679 c := name[0]
2680 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
2681 }
2682
2683
2684 func LinkerDeps(s *modload.Loader, p *Package) ([]string, error) {
2685
2686 deps := []string{"runtime"}
2687
2688
2689 if what := externalLinkingReason(s, p); what != "" && cfg.BuildContext.Compiler != "gccgo" {
2690 if cfg.RestrictedBuild() {
2691 return nil, fmt.Errorf("%s requires external linking, which is not allowed when GORESTRICTEDBUILD=1", what)
2692 }
2693 if cfg.BuildContext.CgoEnabled == build.CgoDisabled {
2694 return nil, fmt.Errorf("%s requires external (cgo) linking, but cgo is not enabled", what)
2695 }
2696 deps = append(deps, "runtime/cgo")
2697 }
2698
2699 if cfg.Goarch == "arm" {
2700 deps = append(deps, "math")
2701 }
2702
2703 if cfg.BuildRace {
2704 deps = append(deps, "runtime/race")
2705 }
2706
2707 if cfg.BuildMSan {
2708 deps = append(deps, "runtime/msan")
2709 }
2710
2711 if cfg.BuildASan {
2712 deps = append(deps, "runtime/asan")
2713 }
2714
2715 if cfg.BuildCover {
2716 deps = append(deps, "runtime/coverage")
2717 }
2718
2719 return deps, nil
2720 }
2721
2722
2723
2724
2725 func externalLinkingReason(s *modload.Loader, p *Package) (what string) {
2726
2727 if platform.MustLinkExternal(cfg.Goos, cfg.Goarch, false) {
2728 return cfg.Goos + "/" + cfg.Goarch
2729 }
2730
2731
2732 switch cfg.BuildBuildmode {
2733 case "c-shared":
2734 if cfg.BuildContext.GOARCH == "wasm" {
2735 break
2736 }
2737 fallthrough
2738 case "plugin":
2739 return "-buildmode=" + cfg.BuildBuildmode
2740 }
2741
2742
2743 if cfg.BuildLinkshared {
2744 return "-linkshared"
2745 }
2746
2747
2748
2749 isPIE := false
2750 if cfg.BuildBuildmode == "pie" {
2751 isPIE = true
2752 } else if cfg.BuildBuildmode == "default" && platform.DefaultPIE(cfg.BuildContext.GOOS, cfg.BuildContext.GOARCH, cfg.BuildRace) {
2753 isPIE = true
2754 }
2755
2756
2757
2758 if isPIE && !platform.InternalLinkPIESupported(cfg.BuildContext.GOOS, cfg.BuildContext.GOARCH) {
2759 if cfg.BuildBuildmode == "pie" {
2760 return "-buildmode=pie"
2761 }
2762 return "default PIE binary"
2763 }
2764
2765
2766
2767 if p != nil {
2768 ldflags := BuildLdflags.For(s, p)
2769 for i := len(ldflags) - 1; i >= 0; i-- {
2770 a := ldflags[i]
2771 if a == "-linkmode=external" ||
2772 a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
2773 return a
2774 } else if a == "-linkmode=internal" ||
2775 a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "internal" {
2776 return ""
2777 }
2778 }
2779 }
2780
2781 return ""
2782 }
2783
2784
2785
2786
2787 func (p *Package) mkAbs(list []string) []string {
2788 for i, f := range list {
2789 list[i] = filepath.Join(p.Dir, f)
2790 }
2791 sort.Strings(list)
2792 return list
2793 }
2794
2795
2796
2797 func (p *Package) InternalGoFiles() []string {
2798 return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
2799 }
2800
2801
2802
2803 func (p *Package) InternalXGoFiles() []string {
2804 return p.mkAbs(p.XTestGoFiles)
2805 }
2806
2807
2808
2809
2810 func (p *Package) InternalAllGoFiles() []string {
2811 return p.mkAbs(str.StringList(p.IgnoredGoFiles, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
2812 }
2813
2814
2815 func (p *Package) UsesSwig() bool {
2816 return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
2817 }
2818
2819
2820 func (p *Package) UsesCgo() bool {
2821 return len(p.CgoFiles) > 0
2822 }
2823
2824
2825
2826 func (p *Package) UsesCgoBinding() bool {
2827 return p.UsesCgo() && cfg.BuildContext.Compiler == "gc" && cfg.Experiment != nil && cfg.Experiment.CgoBindings && p.Internal.Build != nil && p.Internal.Build.CgoBindings
2828 }
2829
2830
2831
2832 func PackageList(roots []*Package) []*Package {
2833 seen := map[*Package]bool{}
2834 all := []*Package{}
2835 var walk func(*Package)
2836 walk = func(p *Package) {
2837 if seen[p] {
2838 return
2839 }
2840 seen[p] = true
2841 for _, p1 := range p.Internal.Imports {
2842 walk(p1)
2843 }
2844 all = append(all, p)
2845 }
2846 for _, root := range roots {
2847 walk(root)
2848 }
2849 return all
2850 }
2851
2852
2853
2854
2855 func TestPackageList(ld *modload.Loader, ctx context.Context, opts PackageOpts, roots []*Package) []*Package {
2856 seen := map[*Package]bool{}
2857 all := []*Package{}
2858 var walk func(*Package)
2859 walk = func(p *Package) {
2860 if seen[p] {
2861 return
2862 }
2863 seen[p] = true
2864 for _, p1 := range p.Internal.Imports {
2865 walk(p1)
2866 }
2867 all = append(all, p)
2868 }
2869 walkTest := func(root *Package, path string) {
2870 var stk ImportStack
2871 p1, err := loadImport(ld, ctx, opts, nil, path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
2872 if err != nil && root.Error == nil {
2873
2874 root.Error = err
2875 root.Incomplete = true
2876 }
2877 if p1.Error == nil {
2878 walk(p1)
2879 }
2880 }
2881 for _, root := range roots {
2882 walk(root)
2883 for _, path := range root.TestImports {
2884 walkTest(root, path)
2885 }
2886 for _, path := range root.XTestImports {
2887 walkTest(root, path)
2888 }
2889 }
2890 return all
2891 }
2892
2893
2894
2895 func LoadPackageWithFlags(ld *modload.Loader, path, srcDir string, stk *ImportStack, importPos []token.Position, mode int) *Package {
2896 p := LoadPackage(ld, context.TODO(), PackageOpts{}, path, srcDir, stk, importPos, mode)
2897 setToolFlags(ld, p)
2898 return p
2899 }
2900
2901
2902
2903 type PackageOpts struct {
2904
2905
2906
2907 IgnoreImports bool
2908
2909
2910
2911
2912
2913
2914
2915
2916 ModResolveTests bool
2917
2918
2919
2920
2921
2922
2923 MainOnly bool
2924
2925
2926
2927 AutoVCS bool
2928
2929
2930
2931 SuppressBuildInfo bool
2932
2933
2934
2935 SuppressEmbedFiles bool
2936 }
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946 func PackagesAndErrors(ld *modload.Loader, ctx context.Context, opts PackageOpts, patterns []string) []*Package {
2947 ctx, span := trace.StartSpan(ctx, "load.PackagesAndErrors")
2948 defer span.Done()
2949
2950 for _, p := range patterns {
2951
2952
2953
2954 if strings.HasSuffix(p, ".go") {
2955
2956
2957 if fi, err := fsys.Stat(p); err == nil && !fi.IsDir() {
2958 pkgs := []*Package{GoFilesPackage(ld, ctx, opts, patterns)}
2959 setPGOProfilePath(pkgs)
2960 return pkgs
2961 }
2962 }
2963 }
2964
2965 var matches []*search.Match
2966 if modload.Init(ld); cfg.ModulesEnabled {
2967 modOpts := modload.PackageOpts{
2968 ResolveMissingImports: true,
2969 LoadTests: opts.ModResolveTests,
2970 SilencePackageErrors: true,
2971 }
2972 matches, _ = modload.LoadPackages(ld, ctx, modOpts, patterns...)
2973 } else {
2974 matches = search.ImportPaths(patterns)
2975 }
2976
2977 var (
2978 pkgs []*Package
2979 stk ImportStack
2980 seenPkg = make(map[*Package]bool)
2981 )
2982
2983 pre := newPreload()
2984 defer pre.flush()
2985 pre.preloadMatches(ld, ctx, opts, matches)
2986
2987 for _, m := range matches {
2988 for _, pkg := range m.Pkgs {
2989 if pkg == "" {
2990 panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
2991 }
2992 mode := cmdlinePkg
2993 if m.IsLiteral() {
2994
2995
2996
2997 mode |= cmdlinePkgLiteral
2998 }
2999 p, perr := loadImport(ld, ctx, opts, pre, pkg, base.Cwd(), nil, &stk, nil, mode)
3000 if perr != nil {
3001 base.Fatalf("internal error: loadImport of %q with nil parent returned an error", pkg)
3002 }
3003 p.Match = append(p.Match, m.Pattern())
3004 if seenPkg[p] {
3005 continue
3006 }
3007 seenPkg[p] = true
3008 pkgs = append(pkgs, p)
3009 }
3010
3011 if len(m.Errs) > 0 {
3012
3013
3014
3015 p := new(Package)
3016 p.ImportPath = m.Pattern()
3017
3018 var stk ImportStack
3019 var importPos []token.Position
3020 p.setLoadPackageDataError(m.Errs[0], m.Pattern(), &stk, importPos)
3021 p.Incomplete = true
3022 p.Match = append(p.Match, m.Pattern())
3023 p.Internal.CmdlinePkg = true
3024 if m.IsLiteral() {
3025 p.Internal.CmdlinePkgLiteral = true
3026 }
3027 pkgs = append(pkgs, p)
3028 }
3029 }
3030
3031 if opts.MainOnly {
3032 pkgs = mainPackagesOnly(pkgs, matches)
3033 }
3034
3035
3036
3037
3038
3039 setToolFlags(ld, pkgs...)
3040
3041 setPGOProfilePath(pkgs)
3042
3043 return pkgs
3044 }
3045
3046
3047
3048 func setPGOProfilePath(pkgs []*Package) {
3049 updateBuildInfo := func(p *Package, file string) {
3050
3051 if p.Internal.BuildInfo == nil {
3052 return
3053 }
3054
3055 if cfg.BuildTrimpath {
3056 appendBuildSetting(p.Internal.BuildInfo, "-pgo", filepath.Base(file))
3057 } else {
3058 appendBuildSetting(p.Internal.BuildInfo, "-pgo", file)
3059 }
3060
3061 slices.SortFunc(p.Internal.BuildInfo.Settings, func(x, y debug.BuildSetting) int {
3062 return strings.Compare(x.Key, y.Key)
3063 })
3064 }
3065
3066 switch cfg.BuildPGO {
3067 case "off":
3068 return
3069
3070 case "auto":
3071
3072
3073
3074
3075
3076
3077
3078 for _, p := range pkgs {
3079 if p.Name != "main" {
3080 continue
3081 }
3082 pmain := p
3083 file := filepath.Join(pmain.Dir, "default.pgo")
3084 if _, err := os.Stat(file); err != nil {
3085 continue
3086 }
3087
3088
3089
3090
3091 visited := make(map[*Package]*Package)
3092 var split func(p *Package) *Package
3093 split = func(p *Package) *Package {
3094 if p1 := visited[p]; p1 != nil {
3095 return p1
3096 }
3097
3098 if len(pkgs) > 1 && p != pmain {
3099
3100
3101
3102
3103 if p.Internal.PGOProfile != "" {
3104 panic("setPGOProfilePath: already have profile")
3105 }
3106 p1 := new(Package)
3107 *p1 = *p
3108
3109
3110
3111 p1.Imports = slices.Clone(p.Imports)
3112 p1.Internal.Imports = slices.Clone(p.Internal.Imports)
3113 p1.Internal.ForMain = pmain.ImportPath
3114 visited[p] = p1
3115 p = p1
3116 } else {
3117 visited[p] = p
3118 }
3119 p.Internal.PGOProfile = file
3120 updateBuildInfo(p, file)
3121
3122 for i, pp := range p.Internal.Imports {
3123 p.Internal.Imports[i] = split(pp)
3124 }
3125 return p
3126 }
3127
3128
3129 split(pmain)
3130 }
3131
3132 default:
3133
3134
3135 file, err := filepath.Abs(cfg.BuildPGO)
3136 if err != nil {
3137 base.Fatalf("fail to get absolute path of PGO file %s: %v", cfg.BuildPGO, err)
3138 }
3139
3140 for _, p := range PackageList(pkgs) {
3141 p.Internal.PGOProfile = file
3142 updateBuildInfo(p, file)
3143 }
3144 }
3145 }
3146
3147
3148
3149 func CheckPackageErrors(pkgs []*Package) {
3150 PackageErrors(pkgs, func(p *Package) {
3151 DefaultPrinter().Errorf(p, "%v", p.Error)
3152 })
3153 base.ExitIfErrors()
3154 }
3155
3156
3157 func PackageErrors(pkgs []*Package, report func(*Package)) {
3158 var anyIncomplete, anyErrors bool
3159 for _, pkg := range pkgs {
3160 if pkg.Incomplete {
3161 anyIncomplete = true
3162 }
3163 }
3164 if anyIncomplete {
3165 all := PackageList(pkgs)
3166 for _, p := range all {
3167 if p.Error != nil {
3168 report(p)
3169 anyErrors = true
3170 }
3171 }
3172 }
3173 if anyErrors {
3174 return
3175 }
3176
3177
3178
3179
3180
3181
3182 seen := map[string]bool{}
3183 reported := map[string]bool{}
3184 for _, pkg := range PackageList(pkgs) {
3185
3186
3187
3188 key := pkg.ImportPath
3189 if pkg.Internal.PGOProfile != "" {
3190 key += " pgo:" + pkg.Internal.PGOProfile
3191 }
3192 if seen[key] && !reported[key] {
3193 reported[key] = true
3194 base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
3195 }
3196 seen[key] = true
3197 }
3198 if len(reported) > 0 {
3199 base.ExitIfErrors()
3200 }
3201 }
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214 func mainPackagesOnly(pkgs []*Package, matches []*search.Match) []*Package {
3215 treatAsMain := map[string]bool{}
3216 for _, m := range matches {
3217 if m.IsLiteral() {
3218 for _, path := range m.Pkgs {
3219 treatAsMain[path] = true
3220 }
3221 }
3222 }
3223
3224 var mains []*Package
3225 for _, pkg := range pkgs {
3226 if pkg.Name == "main" || (pkg.Name == "" && pkg.Error != nil) {
3227 treatAsMain[pkg.ImportPath] = true
3228 mains = append(mains, pkg)
3229 continue
3230 }
3231
3232 if len(pkg.InvalidGoFiles) > 0 {
3233
3234
3235
3236 treatAsMain[pkg.ImportPath] = true
3237 }
3238 if treatAsMain[pkg.ImportPath] {
3239 if pkg.Error == nil {
3240 pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
3241 pkg.Incomplete = true
3242 }
3243 mains = append(mains, pkg)
3244 }
3245 }
3246
3247 for _, m := range matches {
3248 if m.IsLiteral() || len(m.Pkgs) == 0 {
3249 continue
3250 }
3251 foundMain := false
3252 for _, path := range m.Pkgs {
3253 if treatAsMain[path] {
3254 foundMain = true
3255 break
3256 }
3257 }
3258 if !foundMain {
3259 fmt.Fprintf(os.Stderr, "go: warning: %q matched only non-main packages\n", m.Pattern())
3260 }
3261 }
3262
3263 return mains
3264 }
3265
3266 type mainPackageError struct {
3267 importPath string
3268 }
3269
3270 func (e *mainPackageError) Error() string {
3271 return fmt.Sprintf("package %s is not a main package", e.importPath)
3272 }
3273
3274 func (e *mainPackageError) ImportPath() string {
3275 return e.importPath
3276 }
3277
3278 func setToolFlags(ld *modload.Loader, pkgs ...*Package) {
3279 for _, p := range PackageList(pkgs) {
3280 p.Internal.Asmflags = BuildAsmflags.For(ld, p)
3281 p.Internal.Gcflags = BuildGcflags.For(ld, p)
3282 p.Internal.Ldflags = BuildLdflags.For(ld, p)
3283 p.Internal.Gccgoflags = BuildGccgoflags.For(ld, p)
3284 }
3285 }
3286
3287 var errFileNotFound = errors.New("file not found")
3288
3289
3290
3291
3292 func GoFilesPackage(ld *modload.Loader, ctx context.Context, opts PackageOpts, gofiles []string) *Package {
3293 modload.Init(ld)
3294
3295 for _, f := range gofiles {
3296 if !strings.HasSuffix(f, ".go") {
3297 pkg := new(Package)
3298 pkg.Internal.Local = true
3299 pkg.Internal.CmdlineFiles = true
3300 pkg.Name = f
3301 pkg.Error = &PackageError{
3302 Err: fmt.Errorf("named files must be .go files: %s", pkg.Name),
3303 }
3304 pkg.Incomplete = true
3305 return pkg
3306 }
3307 }
3308
3309 var stk ImportStack
3310 ctxt := cfg.BuildContext
3311 ctxt.UseAllFiles = true
3312
3313
3314
3315
3316
3317 var dirent []fs.FileInfo
3318 var dir string
3319 for _, file := range gofiles {
3320 fi, err := fsys.Stat(file)
3321 if err != nil {
3322 if os.IsNotExist(err) {
3323
3324
3325 err = &fs.PathError{Op: "stat", Path: file, Err: errFileNotFound}
3326 }
3327 base.Fatalf("%s", err)
3328 }
3329 if fi.IsDir() {
3330 base.Fatalf("%s is a directory, should be a Go file", file)
3331 }
3332 dir1 := filepath.Dir(file)
3333 if dir == "" {
3334 dir = dir1
3335 } else if dir != dir1 {
3336 base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
3337 }
3338 dirent = append(dirent, fi)
3339 }
3340 ctxt.ReadDir = func(string) ([]fs.FileInfo, error) { return dirent, nil }
3341
3342 if cfg.ModulesEnabled {
3343 modload.ImportFromFiles(ld, ctx, gofiles)
3344 }
3345
3346 var err error
3347 if dir == "" {
3348 dir = base.Cwd()
3349 }
3350 dir, err = filepath.Abs(dir)
3351 if err != nil {
3352 base.Fatalf("%s", err)
3353 }
3354
3355 bp, err := ctxt.ImportDir(dir, 0)
3356 pkg := new(Package)
3357 pkg.Internal.Local = true
3358 pkg.Internal.CmdlineFiles = true
3359 pkg.load(ld, ctx, opts, "command-line-arguments", &stk, nil, bp, err)
3360 if !cfg.ModulesEnabled {
3361 pkg.Internal.LocalPrefix = dirToImportPath(dir)
3362 }
3363 pkg.ImportPath = "command-line-arguments"
3364 pkg.Target = ""
3365 pkg.Match = gofiles
3366
3367 if pkg.Name == "main" {
3368 exe := pkg.DefaultExecName() + cfg.ExeSuffix
3369
3370 if cfg.GOBIN != "" {
3371 pkg.Target = filepath.Join(cfg.GOBIN, exe)
3372 } else if cfg.ModulesEnabled {
3373 pkg.Target = filepath.Join(modload.BinDir(ld), exe)
3374 }
3375 }
3376
3377 if opts.MainOnly && pkg.Name != "main" && pkg.Error == nil {
3378 pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
3379 pkg.Incomplete = true
3380 }
3381 setToolFlags(ld, pkg)
3382
3383 return pkg
3384 }
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401 func PackagesAndErrorsOutsideModule(ld *modload.Loader, ctx context.Context, opts PackageOpts, args []string) ([]*Package, error) {
3402 if !ld.ForceUseModules {
3403 panic("modload.ForceUseModules must be true")
3404 }
3405 if ld.RootMode != modload.NoRoot {
3406 panic("modload.RootMode must be NoRoot")
3407 }
3408
3409
3410 var version string
3411 var firstPath string
3412 for _, arg := range args {
3413 if i := strings.Index(arg, "@"); i >= 0 {
3414 firstPath, version = arg[:i], arg[i+1:]
3415 if version == "" {
3416 return nil, fmt.Errorf("%s: version must not be empty", arg)
3417 }
3418 break
3419 }
3420 }
3421 patterns := make([]string, len(args))
3422 for i, arg := range args {
3423 p, found := strings.CutSuffix(arg, "@"+version)
3424 if !found {
3425 return nil, fmt.Errorf("%s: all arguments must refer to packages in the same module at the same version (@%s)", arg, version)
3426 }
3427 switch {
3428 case build.IsLocalImport(p):
3429 return nil, fmt.Errorf("%s: argument must be a package path, not a relative path", arg)
3430 case filepath.IsAbs(p):
3431 return nil, fmt.Errorf("%s: argument must be a package path, not an absolute path", arg)
3432 case search.IsMetaPackage(p):
3433 return nil, fmt.Errorf("%s: argument must be a package path, not a meta-package", arg)
3434 case pathpkg.Clean(p) != p:
3435 return nil, fmt.Errorf("%s: argument must be a clean package path", arg)
3436 case !strings.Contains(p, "...") && search.IsStandardImportPath(p) && modindex.IsStandardPackage(cfg.GOROOT, cfg.BuildContext.Compiler, p):
3437 return nil, fmt.Errorf("%s: argument must not be a package in the standard library", arg)
3438 default:
3439 patterns[i] = p
3440 }
3441 }
3442 patterns = search.CleanPatterns(patterns)
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452 allowed := ld.CheckAllowed
3453 if modload.IsRevisionQuery(firstPath, version) {
3454
3455 allowed = nil
3456 }
3457 noneSelected := func(path string) (version string) { return "none" }
3458 qrs, err := modload.QueryPackages(ld, ctx, patterns[0], version, noneSelected, allowed)
3459 if err != nil {
3460 return nil, fmt.Errorf("%s: %w", args[0], err)
3461 }
3462 rootMod := qrs[0].Mod
3463 deprecation, err := modload.CheckDeprecation(ld, ctx, rootMod)
3464 if err != nil {
3465 return nil, fmt.Errorf("%s: %w", args[0], err)
3466 }
3467 if deprecation != "" {
3468 fmt.Fprintf(os.Stderr, "go: module %s is deprecated: %s\n", rootMod.Path, modload.ShortMessage(deprecation, ""))
3469 }
3470 data, err := ld.Fetcher().GoMod(ctx, rootMod.Path, rootMod.Version)
3471 if err != nil {
3472 return nil, fmt.Errorf("%s: %w", args[0], err)
3473 }
3474 f, err := modfile.Parse("go.mod", data, nil)
3475 if err != nil {
3476 return nil, fmt.Errorf("%s (in %s): %w", args[0], rootMod, err)
3477 }
3478 directiveFmt := "%s (in %s):\n" +
3479 "\tThe go.mod file for the module providing named packages contains one or\n" +
3480 "\tmore %s directives. It must not contain directives that would cause\n" +
3481 "\tit to be interpreted differently than if it were the main module."
3482 if len(f.Replace) > 0 {
3483 return nil, fmt.Errorf(directiveFmt, args[0], rootMod, "replace")
3484 }
3485 if len(f.Exclude) > 0 {
3486 return nil, fmt.Errorf(directiveFmt, args[0], rootMod, "exclude")
3487 }
3488
3489
3490
3491
3492 if _, err := modload.EditBuildList(ld, ctx, nil, []module.Version{rootMod}); err != nil {
3493 return nil, fmt.Errorf("%s: %w", args[0], err)
3494 }
3495
3496
3497 pkgs := PackagesAndErrors(ld, ctx, opts, patterns)
3498
3499
3500 for _, pkg := range pkgs {
3501 var pkgErr error
3502 if pkg.Module == nil {
3503
3504
3505 pkgErr = fmt.Errorf("package %s not provided by module %s", pkg.ImportPath, rootMod)
3506 } else if pkg.Module.Path != rootMod.Path || pkg.Module.Version != rootMod.Version {
3507 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)
3508 }
3509 if pkgErr != nil && pkg.Error == nil {
3510 pkg.Error = &PackageError{Err: pkgErr}
3511 pkg.Incomplete = true
3512 }
3513 }
3514
3515 matchers := make([]func(string) bool, len(patterns))
3516 for i, p := range patterns {
3517 if strings.Contains(p, "...") {
3518 matchers[i] = pkgpattern.MatchPattern(p)
3519 }
3520 }
3521 return pkgs, nil
3522 }
3523
3524
3525 func EnsureImport(s *modload.Loader, p *Package, pkg string) {
3526 for _, d := range p.Internal.Imports {
3527 if d.Name == pkg {
3528 return
3529 }
3530 }
3531
3532 p1, err := loadImport(s, context.TODO(), PackageOpts{}, nil, pkg, p.Dir, p, &ImportStack{}, nil, 0)
3533 if err != nil {
3534 base.Fatalf("load %s: %v", pkg, err)
3535 }
3536 if p1.Error != nil {
3537 base.Fatalf("load %s: %v", pkg, p1.Error)
3538 }
3539
3540 p.Internal.Imports = append(p.Internal.Imports, p1)
3541 }
3542
3543
3544
3545
3546
3547
3548 func PrepareForCoverageBuild(s *modload.Loader, pkgs []*Package) {
3549 var match []func(*modload.Loader, *Package) bool
3550
3551 matchMainModAndCommandLine := func(_ *modload.Loader, p *Package) bool {
3552
3553 return p.Internal.CmdlineFiles || p.Internal.CmdlinePkg || (p.Module != nil && p.Module.Main)
3554 }
3555
3556 if len(cfg.BuildCoverPkg) != 0 {
3557
3558
3559 match = make([]func(*modload.Loader, *Package) bool, len(cfg.BuildCoverPkg))
3560 for i := range cfg.BuildCoverPkg {
3561 match[i] = MatchPackage(cfg.BuildCoverPkg[i], base.Cwd())
3562 }
3563 } else {
3564
3565
3566
3567 match = []func(*modload.Loader, *Package) bool{matchMainModAndCommandLine}
3568 }
3569
3570
3571
3572
3573 SelectCoverPackages(s, PackageList(pkgs), match, "build")
3574 }
3575
3576 func SelectCoverPackages(s *modload.Loader, roots []*Package, match []func(*modload.Loader, *Package) bool, op string) []*Package {
3577 var warntag string
3578 var includeMain bool
3579 switch op {
3580 case "build":
3581 warntag = "built"
3582 includeMain = true
3583 case "test":
3584 warntag = "tested"
3585 default:
3586 panic("internal error, bad mode passed to SelectCoverPackages")
3587 }
3588
3589 covered := []*Package{}
3590 matched := make([]bool, len(match))
3591 for _, p := range roots {
3592 haveMatch := false
3593 for i := range match {
3594 if match[i](s, p) {
3595 matched[i] = true
3596 haveMatch = true
3597 }
3598 }
3599
3600
3601
3602
3603
3604
3605
3606
3607 cmode := cfg.BuildCoverMode
3608 if cfg.BuildRace && p.Standard && objabi.LookupPkgSpecial(p.ImportPath).Runtime {
3609 cmode = "regonly"
3610 }
3611
3612
3613
3614
3615 if includeMain && p.Name == "main" && !haveMatch {
3616 haveMatch = true
3617 cmode = "regonly"
3618 }
3619
3620 if !haveMatch {
3621 continue
3622 }
3623
3624
3625
3626 if p.ImportPath == "unsafe" {
3627 continue
3628 }
3629
3630
3631
3632
3633
3634
3635
3636
3637 if len(p.GoFiles)+len(p.CgoFiles) == 0 {
3638 continue
3639 }
3640
3641
3642
3643
3644
3645 if cfg.BuildCoverMode == "atomic" && p.Standard &&
3646 (p.ImportPath == "sync/atomic" || p.ImportPath == "internal/runtime/atomic") {
3647 continue
3648 }
3649
3650
3651 p.Internal.Cover.Mode = cmode
3652 covered = append(covered, p)
3653
3654
3655 if cfg.BuildCoverMode == "atomic" {
3656 EnsureImport(s, p, "sync/atomic")
3657 }
3658 }
3659
3660
3661 for i := range cfg.BuildCoverPkg {
3662 if !matched[i] {
3663 fmt.Fprintf(os.Stderr, "warning: no packages being %s depend on matches for pattern %s\n", warntag, cfg.BuildCoverPkg[i])
3664 }
3665 }
3666
3667 return covered
3668 }
3669
View as plain text