]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/go/internal/modindex/read.go
d6a04a015636b67968ead92dbadd95e86298c5c6
[gostls13.git] / src / cmd / go / internal / modindex / read.go
1 // Copyright 2022 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 modindex
6
7 import (
8         "bytes"
9         "encoding/binary"
10         "errors"
11         "fmt"
12         "go/build"
13         "go/build/constraint"
14         "go/token"
15         "internal/godebug"
16         "internal/goroot"
17         "path"
18         "path/filepath"
19         "runtime"
20         "runtime/debug"
21         "sort"
22         "strings"
23         "sync"
24         "time"
25         "unsafe"
26
27         "cmd/go/internal/base"
28         "cmd/go/internal/cache"
29         "cmd/go/internal/cfg"
30         "cmd/go/internal/fsys"
31         "cmd/go/internal/imports"
32         "cmd/go/internal/par"
33         "cmd/go/internal/str"
34 )
35
36 // enabled is used to flag off the behavior of the module index on tip.
37 // It will be removed before the release.
38 // TODO(matloob): Remove enabled once we have more confidence on the
39 // module index.
40 var enabled bool = godebug.Get("goindex") != "0"
41
42 // Module represents and encoded module index file. It is used to
43 // do the equivalent of build.Import of packages in the module and answer other
44 // questions based on the index file's data.
45 type Module struct {
46         modroot string
47         d       *decoder
48         n       int // number of packages
49 }
50
51 // moduleHash returns an ActionID corresponding to the state of the module
52 // located at filesystem path modroot.
53 func moduleHash(modroot string, ismodcache bool) (cache.ActionID, error) {
54         // We expect modules stored within the module cache to be checksummed and
55         // immutable, and we expect released modules within GOROOT to change only
56         // infrequently (when the Go version changes).
57         if !ismodcache {
58                 // The contents of this module may change over time. We don't want to pay
59                 // the cost to detect changes and re-index whenever they occur, so just
60                 // don't index it at all.
61                 //
62                 // Note that this is true even for modules in GOROOT/src: non-release builds
63                 // of the Go toolchain may have arbitrary development changes on top of the
64                 // commit reported by runtime.Version, or could be completly artificial due
65                 // to lacking a `git` binary (like "devel gomote.XXXXX", as synthesized by
66                 // "gomote push" as of 2022-06-15). (Release builds shouldn't have
67                 // modifications, but we don't want to use a behavior for releases that we
68                 // haven't tested during development.)
69                 return cache.ActionID{}, ErrNotIndexed
70         }
71
72         h := cache.NewHash("moduleIndex")
73         // TODO(bcmills): Since modules in the index are checksummed, we could
74         // probably improve the cache hit rate by keying off of the module
75         // path@version (perhaps including the checksum?) instead of the module root
76         // directory.
77         fmt.Fprintf(h, "module index %s %s %v\n", runtime.Version(), indexVersion, modroot)
78         return h.Sum(), nil
79 }
80
81 const modTimeCutoff = 2 * time.Second
82
83 // dirHash returns an ActionID corresponding to the state of the package
84 // located at filesystem path pkgdir.
85 func dirHash(modroot, pkgdir string) (cache.ActionID, error) {
86         h := cache.NewHash("moduleIndex")
87         fmt.Fprintf(h, "modroot %s\n", modroot)
88         fmt.Fprintf(h, "package %s %s %v\n", runtime.Version(), indexVersion, pkgdir)
89         entries, err := fsys.ReadDir(pkgdir)
90         if err != nil {
91                 // pkgdir might not be a directory. give up on hashing.
92                 return cache.ActionID{}, ErrNotIndexed
93         }
94         cutoff := time.Now().Add(-modTimeCutoff)
95         for _, info := range entries {
96                 if info.IsDir() {
97                         continue
98                 }
99
100                 if !info.Mode().IsRegular() {
101                         return cache.ActionID{}, ErrNotIndexed
102                 }
103                 // To avoid problems for very recent files where a new
104                 // write might not change the mtime due to file system
105                 // mtime precision, reject caching if a file was read that
106                 // is less than modTimeCutoff old.
107                 //
108                 // This is the same strategy used for hashing test inputs.
109                 // See hashOpen in cmd/go/internal/test/test.go for the
110                 // corresponding code.
111                 if info.ModTime().After(cutoff) {
112                         return cache.ActionID{}, ErrNotIndexed
113                 }
114
115                 fmt.Fprintf(h, "file %v %v %v\n", info.Name(), info.ModTime(), info.Size())
116         }
117         return h.Sum(), nil
118 }
119
120 var modrootCache par.Cache
121
122 var ErrNotIndexed = errors.New("not in module index")
123
124 var (
125         errDisabled           = fmt.Errorf("%w: module indexing disabled", ErrNotIndexed)
126         errNotFromModuleCache = fmt.Errorf("%w: not from module cache", ErrNotIndexed)
127 )
128
129 // GetPackage returns the IndexPackage for the package at the given path.
130 // It will return ErrNotIndexed if the directory should be read without
131 // using the index, for instance because the index is disabled, or the packgae
132 // is not in a module.
133 func GetPackage(modroot, pkgdir string) (*IndexPackage, error) {
134         mi, err := GetModule(modroot)
135         if err == nil {
136                 return mi.Package(relPath(pkgdir, modroot)), nil
137         }
138         if !errors.Is(err, errNotFromModuleCache) {
139                 return nil, err
140         }
141         if cfg.BuildContext.Compiler == "gccgo" && str.HasPathPrefix(modroot, cfg.GOROOTsrc) {
142                 return nil, err // gccgo has no sources for GOROOT packages.
143         }
144         return openIndexPackage(modroot, pkgdir)
145 }
146
147 // GetModule returns the Module for the given modroot.
148 // It will return ErrNotIndexed if the directory should be read without
149 // using the index, for instance because the index is disabled, or the packgae
150 // is not in a module.
151 func GetModule(modroot string) (*Module, error) {
152         if !enabled || cache.DefaultDir() == "off" {
153                 return nil, errDisabled
154         }
155         if modroot == "" {
156                 panic("modindex.GetPackage called with empty modroot")
157         }
158         if cfg.BuildMod == "vendor" {
159                 // Even if the main module is in the module cache,
160                 // its vendored dependencies are not loaded from their
161                 // usual cached locations.
162                 return nil, errNotFromModuleCache
163         }
164         modroot = filepath.Clean(modroot)
165         if !str.HasFilePathPrefix(modroot, cfg.GOMODCACHE) {
166                 return nil, errNotFromModuleCache
167         }
168         return openIndexModule(modroot, true)
169 }
170
171 var mcache par.Cache
172
173 // openIndexModule returns the module index for modPath.
174 // It will return ErrNotIndexed if the module can not be read
175 // using the index because it contains symlinks.
176 func openIndexModule(modroot string, ismodcache bool) (*Module, error) {
177         type result struct {
178                 mi  *Module
179                 err error
180         }
181         r := mcache.Do(modroot, func() any {
182                 fsys.Trace("openIndexModule", modroot)
183                 id, err := moduleHash(modroot, ismodcache)
184                 if err != nil {
185                         return result{nil, err}
186                 }
187                 data, _, err := cache.Default().GetMmap(id)
188                 if err != nil {
189                         // Couldn't read from modindex. Assume we couldn't read from
190                         // the index because the module hasn't been indexed yet.
191                         data, err = indexModule(modroot)
192                         if err != nil {
193                                 return result{nil, err}
194                         }
195                         if err = cache.Default().PutBytes(id, data); err != nil {
196                                 return result{nil, err}
197                         }
198                 }
199                 mi, err := fromBytes(modroot, data)
200                 if err != nil {
201                         return result{nil, err}
202                 }
203                 return result{mi, nil}
204         }).(result)
205         return r.mi, r.err
206 }
207
208 var pcache par.Cache
209
210 func openIndexPackage(modroot, pkgdir string) (*IndexPackage, error) {
211         type result struct {
212                 pkg *IndexPackage
213                 err error
214         }
215         r := pcache.Do([2]string{modroot, pkgdir}, func() any {
216                 fsys.Trace("openIndexPackage", pkgdir)
217                 id, err := dirHash(modroot, pkgdir)
218                 if err != nil {
219                         return result{nil, err}
220                 }
221                 data, _, err := cache.Default().GetMmap(id)
222                 if err != nil {
223                         // Couldn't read from index. Assume we couldn't read from
224                         // the index because the package hasn't been indexed yet.
225                         data = indexPackage(modroot, pkgdir)
226                         if err = cache.Default().PutBytes(id, data); err != nil {
227                                 return result{nil, err}
228                         }
229                 }
230                 pkg, err := packageFromBytes(modroot, data)
231                 if err != nil {
232                         return result{nil, err}
233                 }
234                 return result{pkg, nil}
235         }).(result)
236         return r.pkg, r.err
237 }
238
239 var errCorrupt = errors.New("corrupt index")
240
241 // protect marks the start of a large section of code that accesses the index.
242 // It should be used as:
243 //
244 //      defer unprotect(protect, &err)
245 //
246 // It should not be used for trivial accesses which would be
247 // dwarfed by the overhead of the defer.
248 func protect() bool {
249         return debug.SetPanicOnFault(true)
250 }
251
252 var isTest = false
253
254 // unprotect marks the end of a large section of code that accesses the index.
255 // It should be used as:
256 //
257 //      defer unprotect(protect, &err)
258 //
259 // end looks for panics due to errCorrupt or bad mmap accesses.
260 // When it finds them, it adds explanatory text, consumes the panic, and sets *errp instead.
261 // If errp is nil, end adds the explanatory text but then calls base.Fatalf.
262 func unprotect(old bool, errp *error) {
263         // SetPanicOnFault's errors _may_ satisfy this interface. Even though it's not guaranteed
264         // that all its errors satisfy this interface, we'll only check for these errors so that
265         // we don't suppress panics that could have been produced from other sources.
266         type addrer interface {
267                 Addr() uintptr
268         }
269
270         debug.SetPanicOnFault(old)
271
272         if e := recover(); e != nil {
273                 if _, ok := e.(addrer); ok || e == errCorrupt {
274                         // This panic was almost certainly caused by SetPanicOnFault or our panic(errCorrupt).
275                         err := fmt.Errorf("error reading module index: %v", e)
276                         if errp != nil {
277                                 *errp = err
278                                 return
279                         }
280                         if isTest {
281                                 panic(err)
282                         }
283                         base.Fatalf("%v", err)
284                 }
285                 // The panic was likely not caused by SetPanicOnFault.
286                 panic(e)
287         }
288 }
289
290 // fromBytes returns a *Module given the encoded representation.
291 func fromBytes(moddir string, data []byte) (m *Module, err error) {
292         if !enabled {
293                 panic("use of index")
294         }
295
296         defer unprotect(protect(), &err)
297
298         if !bytes.HasPrefix(data, []byte(indexVersion+"\n")) {
299                 return nil, errCorrupt
300         }
301
302         const hdr = len(indexVersion + "\n")
303         d := &decoder{data: data}
304         str := d.intAt(hdr)
305         if str < hdr+8 || len(d.data) < str {
306                 return nil, errCorrupt
307         }
308         d.data, d.str = data[:str], d.data[str:]
309         // Check that string table looks valid.
310         // First string is empty string (length 0),
311         // and we leave a marker byte 0xFF at the end
312         // just to make sure that the file is not truncated.
313         if len(d.str) == 0 || d.str[0] != 0 || d.str[len(d.str)-1] != 0xFF {
314                 return nil, errCorrupt
315         }
316
317         n := d.intAt(hdr + 4)
318         if n < 0 || n > (len(d.data)-8)/8 {
319                 return nil, errCorrupt
320         }
321
322         m = &Module{
323                 moddir,
324                 d,
325                 n,
326         }
327         return m, nil
328 }
329
330 // packageFromBytes returns a *IndexPackage given the encoded representation.
331 func packageFromBytes(modroot string, data []byte) (p *IndexPackage, err error) {
332         m, err := fromBytes(modroot, data)
333         if err != nil {
334                 return nil, err
335         }
336         if m.n != 1 {
337                 return nil, fmt.Errorf("corrupt single-package index")
338         }
339         return m.pkg(0), nil
340 }
341
342 // pkgDir returns the dir string of the i'th package in the index.
343 func (m *Module) pkgDir(i int) string {
344         if i < 0 || i >= m.n {
345                 panic(errCorrupt)
346         }
347         return m.d.stringAt(12 + 8 + 8*i)
348 }
349
350 // pkgOff returns the offset of the data for the i'th package in the index.
351 func (m *Module) pkgOff(i int) int {
352         if i < 0 || i >= m.n {
353                 panic(errCorrupt)
354         }
355         return m.d.intAt(12 + 8 + 8*i + 4)
356 }
357
358 // Walk calls f for each package in the index, passing the path to that package relative to the module root.
359 func (m *Module) Walk(f func(path string)) {
360         defer unprotect(protect(), nil)
361         for i := 0; i < m.n; i++ {
362                 f(m.pkgDir(i))
363         }
364 }
365
366 // relPath returns the path relative to the module's root.
367 func relPath(path, modroot string) string {
368         return str.TrimFilePathPrefix(filepath.Clean(path), filepath.Clean(modroot))
369 }
370
371 // Import is the equivalent of build.Import given the information in Module.
372 func (rp *IndexPackage) Import(bctxt build.Context, mode build.ImportMode) (p *build.Package, err error) {
373         defer unprotect(protect(), &err)
374
375         ctxt := (*Context)(&bctxt)
376
377         p = &build.Package{}
378
379         p.ImportPath = "."
380         p.Dir = filepath.Join(rp.modroot, rp.dir)
381
382         var pkgerr error
383         switch ctxt.Compiler {
384         case "gccgo", "gc":
385         default:
386                 // Save error for end of function.
387                 pkgerr = fmt.Errorf("import %q: unknown compiler %q", p.Dir, ctxt.Compiler)
388         }
389
390         if p.Dir == "" {
391                 return p, fmt.Errorf("import %q: import of unknown directory", p.Dir)
392         }
393
394         // goroot and gopath
395         inTestdata := func(sub string) bool {
396                 return strings.Contains(sub, "/testdata/") || strings.HasSuffix(sub, "/testdata") || str.HasPathPrefix(sub, "testdata")
397         }
398         if !inTestdata(rp.dir) {
399                 // In build.go, p.Root should only be set in the non-local-import case, or in
400                 // GOROOT or GOPATH. Since module mode only calls Import with path set to "."
401                 // and the module index doesn't apply outside modules, the GOROOT case is
402                 // the only case where p.Root needs to be set.
403                 if ctxt.GOROOT != "" && str.HasFilePathPrefix(p.Dir, cfg.GOROOTsrc) && p.Dir != cfg.GOROOTsrc {
404                         p.Root = ctxt.GOROOT
405                         p.Goroot = true
406                         modprefix := str.TrimFilePathPrefix(rp.modroot, cfg.GOROOTsrc)
407                         p.ImportPath = rp.dir
408                         if modprefix != "" {
409                                 p.ImportPath = filepath.Join(modprefix, p.ImportPath)
410                         }
411
412                         // Set GOROOT-specific fields (sometimes for modules in a GOPATH directory).
413                         // The fields set below (SrcRoot, PkgRoot, BinDir, PkgTargetRoot, and PkgObj)
414                         // are only set in build.Import if p.Root != "".
415                         var pkgtargetroot string
416                         var pkga string
417                         suffix := ""
418                         if ctxt.InstallSuffix != "" {
419                                 suffix = "_" + ctxt.InstallSuffix
420                         }
421                         switch ctxt.Compiler {
422                         case "gccgo":
423                                 pkgtargetroot = "pkg/gccgo_" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
424                                 dir, elem := path.Split(p.ImportPath)
425                                 pkga = pkgtargetroot + "/" + dir + "lib" + elem + ".a"
426                         case "gc":
427                                 pkgtargetroot = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
428                                 pkga = pkgtargetroot + "/" + p.ImportPath + ".a"
429                         }
430                         p.SrcRoot = ctxt.joinPath(p.Root, "src")
431                         p.PkgRoot = ctxt.joinPath(p.Root, "pkg")
432                         p.BinDir = ctxt.joinPath(p.Root, "bin")
433                         if pkga != "" {
434                                 p.PkgTargetRoot = ctxt.joinPath(p.Root, pkgtargetroot)
435                                 p.PkgObj = ctxt.joinPath(p.Root, pkga)
436                         }
437                 }
438         }
439
440         if rp.error != nil {
441                 if errors.Is(rp.error, errCannotFindPackage) && ctxt.Compiler == "gccgo" && p.Goroot {
442                         return p, nil
443                 }
444                 return p, rp.error
445         }
446
447         if mode&build.FindOnly != 0 {
448                 return p, pkgerr
449         }
450
451         // We need to do a second round of bad file processing.
452         var badGoError error
453         badFiles := make(map[string]bool)
454         badFile := func(name string, err error) {
455                 if badGoError == nil {
456                         badGoError = err
457                 }
458                 if !badFiles[name] {
459                         p.InvalidGoFiles = append(p.InvalidGoFiles, name)
460                         badFiles[name] = true
461                 }
462         }
463
464         var Sfiles []string // files with ".S"(capital S)/.sx(capital s equivalent for case insensitive filesystems)
465         var firstFile string
466         embedPos := make(map[string][]token.Position)
467         testEmbedPos := make(map[string][]token.Position)
468         xTestEmbedPos := make(map[string][]token.Position)
469         importPos := make(map[string][]token.Position)
470         testImportPos := make(map[string][]token.Position)
471         xTestImportPos := make(map[string][]token.Position)
472         allTags := make(map[string]bool)
473         for _, tf := range rp.sourceFiles {
474                 name := tf.name()
475                 if error := tf.error(); error != "" {
476                         badFile(name, errors.New(tf.error()))
477                         continue
478                 } else if parseError := tf.parseError(); parseError != "" {
479                         badFile(name, parseErrorFromString(tf.parseError()))
480                         // Fall through: we still want to list files with parse errors.
481                 }
482
483                 var shouldBuild = true
484                 if !ctxt.goodOSArchFile(name, allTags) && !ctxt.UseAllFiles {
485                         shouldBuild = false
486                 } else if goBuildConstraint := tf.goBuildConstraint(); goBuildConstraint != "" {
487                         x, err := constraint.Parse(goBuildConstraint)
488                         if err != nil {
489                                 return p, fmt.Errorf("%s: parsing //go:build line: %v", name, err)
490                         }
491                         shouldBuild = ctxt.eval(x, allTags)
492                 } else if plusBuildConstraints := tf.plusBuildConstraints(); len(plusBuildConstraints) > 0 {
493                         for _, text := range plusBuildConstraints {
494                                 if x, err := constraint.Parse(text); err == nil {
495                                         if !ctxt.eval(x, allTags) {
496                                                 shouldBuild = false
497                                         }
498                                 }
499                         }
500                 }
501
502                 ext := nameExt(name)
503                 if !shouldBuild || tf.ignoreFile() {
504                         if ext == ".go" {
505                                 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
506                         } else if fileListForExt((*Package)(p), ext) != nil {
507                                 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, name)
508                         }
509                         continue
510                 }
511
512                 // Going to save the file. For non-Go files, can stop here.
513                 switch ext {
514                 case ".go":
515                         // keep going
516                 case ".S", ".sx":
517                         // special case for cgo, handled at end
518                         Sfiles = append(Sfiles, name)
519                         continue
520                 default:
521                         if list := fileListForExt((*Package)(p), ext); list != nil {
522                                 *list = append(*list, name)
523                         }
524                         continue
525                 }
526
527                 pkg := tf.pkgName()
528                 if pkg == "documentation" {
529                         p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
530                         continue
531                 }
532                 isTest := strings.HasSuffix(name, "_test.go")
533                 isXTest := false
534                 if isTest && strings.HasSuffix(tf.pkgName(), "_test") && p.Name != tf.pkgName() {
535                         isXTest = true
536                         pkg = pkg[:len(pkg)-len("_test")]
537                 }
538
539                 if !isTest && tf.binaryOnly() {
540                         p.BinaryOnly = true
541                 }
542
543                 if p.Name == "" {
544                         p.Name = pkg
545                         firstFile = name
546                 } else if pkg != p.Name {
547                         // TODO(#45999): The choice of p.Name is arbitrary based on file iteration
548                         // order. Instead of resolving p.Name arbitrarily, we should clear out the
549                         // existing Name and mark the existing files as also invalid.
550                         badFile(name, &MultiplePackageError{
551                                 Dir:      p.Dir,
552                                 Packages: []string{p.Name, pkg},
553                                 Files:    []string{firstFile, name},
554                         })
555                 }
556                 // Grab the first package comment as docs, provided it is not from a test file.
557                 if p.Doc == "" && !isTest && !isXTest {
558                         if synopsis := tf.synopsis(); synopsis != "" {
559                                 p.Doc = synopsis
560                         }
561                 }
562
563                 // Record Imports and information about cgo.
564                 isCgo := false
565                 imports := tf.imports()
566                 for _, imp := range imports {
567                         if imp.path == "C" {
568                                 if isTest {
569                                         badFile(name, fmt.Errorf("use of cgo in test %s not supported", name))
570                                         continue
571                                 }
572                                 isCgo = true
573                         }
574                 }
575                 if directives := tf.cgoDirectives(); directives != "" {
576                         if err := ctxt.saveCgo(name, (*Package)(p), directives); err != nil {
577                                 badFile(name, err)
578                         }
579                 }
580
581                 var fileList *[]string
582                 var importMap, embedMap map[string][]token.Position
583                 switch {
584                 case isCgo:
585                         allTags["cgo"] = true
586                         if ctxt.CgoEnabled {
587                                 fileList = &p.CgoFiles
588                                 importMap = importPos
589                                 embedMap = embedPos
590                         } else {
591                                 // Ignore Imports and Embeds from cgo files if cgo is disabled.
592                                 fileList = &p.IgnoredGoFiles
593                         }
594                 case isXTest:
595                         fileList = &p.XTestGoFiles
596                         importMap = xTestImportPos
597                         embedMap = xTestEmbedPos
598                 case isTest:
599                         fileList = &p.TestGoFiles
600                         importMap = testImportPos
601                         embedMap = testEmbedPos
602                 default:
603                         fileList = &p.GoFiles
604                         importMap = importPos
605                         embedMap = embedPos
606                 }
607                 *fileList = append(*fileList, name)
608                 if importMap != nil {
609                         for _, imp := range imports {
610                                 importMap[imp.path] = append(importMap[imp.path], imp.position)
611                         }
612                 }
613                 if embedMap != nil {
614                         for _, e := range tf.embeds() {
615                                 embedMap[e.pattern] = append(embedMap[e.pattern], e.position)
616                         }
617                 }
618         }
619
620         p.EmbedPatterns, p.EmbedPatternPos = cleanDecls(embedPos)
621         p.TestEmbedPatterns, p.TestEmbedPatternPos = cleanDecls(testEmbedPos)
622         p.XTestEmbedPatterns, p.XTestEmbedPatternPos = cleanDecls(xTestEmbedPos)
623
624         p.Imports, p.ImportPos = cleanDecls(importPos)
625         p.TestImports, p.TestImportPos = cleanDecls(testImportPos)
626         p.XTestImports, p.XTestImportPos = cleanDecls(xTestImportPos)
627
628         for tag := range allTags {
629                 p.AllTags = append(p.AllTags, tag)
630         }
631         sort.Strings(p.AllTags)
632
633         if len(p.CgoFiles) > 0 {
634                 p.SFiles = append(p.SFiles, Sfiles...)
635                 sort.Strings(p.SFiles)
636         } else {
637                 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, Sfiles...)
638                 sort.Strings(p.IgnoredOtherFiles)
639         }
640
641         if badGoError != nil {
642                 return p, badGoError
643         }
644         if len(p.GoFiles)+len(p.CgoFiles)+len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
645                 return p, &build.NoGoError{Dir: p.Dir}
646         }
647         return p, pkgerr
648 }
649
650 // IsStandardPackage reports whether path is a standard package
651 // for the goroot and compiler using the module index if possible,
652 // and otherwise falling back to internal/goroot.IsStandardPackage
653 func IsStandardPackage(goroot_, compiler, path string) bool {
654         if !enabled || compiler != "gc" {
655                 return goroot.IsStandardPackage(goroot_, compiler, path)
656         }
657
658         reldir := filepath.FromSlash(path) // relative dir path in module index for package
659         modroot := filepath.Join(goroot_, "src")
660         if str.HasFilePathPrefix(reldir, "cmd") {
661                 reldir = str.TrimFilePathPrefix(reldir, "cmd")
662                 modroot = filepath.Join(modroot, "cmd")
663         }
664         if _, err := GetPackage(modroot, filepath.Join(modroot, reldir)); err == nil {
665                 // Note that goroot.IsStandardPackage doesn't check that the directory
666                 // actually contains any go files-- merely that it exists. GetPackage
667                 // returning a nil error is enough for us to know the directory exists.
668                 return true
669         } else if errors.Is(err, ErrNotIndexed) {
670                 // Fall back because package isn't indexable. (Probably because
671                 // a file was modified recently)
672                 return goroot.IsStandardPackage(goroot_, compiler, path)
673         }
674         return false
675 }
676
677 // IsDirWithGoFiles is the equivalent of fsys.IsDirWithGoFiles using the information in the index.
678 func (rp *IndexPackage) IsDirWithGoFiles() (_ bool, err error) {
679         defer func() {
680                 if e := recover(); e != nil {
681                         err = fmt.Errorf("error reading module index: %v", e)
682                 }
683         }()
684         for _, sf := range rp.sourceFiles {
685                 if strings.HasSuffix(sf.name(), ".go") {
686                         return true, nil
687                 }
688         }
689         return false, nil
690 }
691
692 // ScanDir implements imports.ScanDir using the information in the index.
693 func (rp *IndexPackage) ScanDir(tags map[string]bool) (sortedImports []string, sortedTestImports []string, err error) {
694         // TODO(matloob) dir should eventually be relative to indexed directory
695         // TODO(matloob): skip reading raw package and jump straight to data we need?
696
697         defer func() {
698                 if e := recover(); e != nil {
699                         err = fmt.Errorf("error reading module index: %v", e)
700                 }
701         }()
702
703         imports_ := make(map[string]bool)
704         testImports := make(map[string]bool)
705         numFiles := 0
706
707 Files:
708         for _, sf := range rp.sourceFiles {
709                 name := sf.name()
710                 if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") || !strings.HasSuffix(name, ".go") || !imports.MatchFile(name, tags) {
711                         continue
712                 }
713
714                 // The following section exists for backwards compatibility reasons:
715                 // scanDir ignores files with import "C" when collecting the list
716                 // of imports unless the "cgo" tag is provided. The following comment
717                 // is copied from the original.
718                 //
719                 // import "C" is implicit requirement of cgo tag.
720                 // When listing files on the command line (explicitFiles=true)
721                 // we do not apply build tag filtering but we still do apply
722                 // cgo filtering, so no explicitFiles check here.
723                 // Why? Because we always have, and it's not worth breaking
724                 // that behavior now.
725                 imps := sf.imports() // TODO(matloob): directly read import paths to avoid the extra strings?
726                 for _, imp := range imps {
727                         if imp.path == "C" && !tags["cgo"] && !tags["*"] {
728                                 continue Files
729                         }
730                 }
731
732                 if !shouldBuild(sf, tags) {
733                         continue
734                 }
735                 numFiles++
736                 m := imports_
737                 if strings.HasSuffix(name, "_test.go") {
738                         m = testImports
739                 }
740                 for _, p := range imps {
741                         m[p.path] = true
742                 }
743         }
744         if numFiles == 0 {
745                 return nil, nil, imports.ErrNoGo
746         }
747         return keys(imports_), keys(testImports), nil
748 }
749
750 func keys(m map[string]bool) []string {
751         list := make([]string, 0, len(m))
752         for k := range m {
753                 list = append(list, k)
754         }
755         sort.Strings(list)
756         return list
757 }
758
759 // implements imports.ShouldBuild in terms of an index sourcefile.
760 func shouldBuild(sf *sourceFile, tags map[string]bool) bool {
761         if goBuildConstraint := sf.goBuildConstraint(); goBuildConstraint != "" {
762                 x, err := constraint.Parse(goBuildConstraint)
763                 if err != nil {
764                         return false
765                 }
766                 return imports.Eval(x, tags, true)
767         }
768
769         plusBuildConstraints := sf.plusBuildConstraints()
770         for _, text := range plusBuildConstraints {
771                 if x, err := constraint.Parse(text); err == nil {
772                         if !imports.Eval(x, tags, true) {
773                                 return false
774                         }
775                 }
776         }
777
778         return true
779 }
780
781 // IndexPackage holds the information needed to access information in the
782 // index needed to load a package in a specific directory.
783 type IndexPackage struct {
784         error error
785         dir   string // directory of the package relative to the modroot
786
787         modroot string
788
789         // Source files
790         sourceFiles []*sourceFile
791 }
792
793 var errCannotFindPackage = errors.New("cannot find package")
794
795 // Package and returns finds the package with the given path (relative to the module root).
796 // If the package does not exist, Package returns an IndexPackage that will return an
797 // appropriate error from its methods.
798 func (m *Module) Package(path string) *IndexPackage {
799         defer unprotect(protect(), nil)
800
801         i, ok := sort.Find(m.n, func(i int) int {
802                 return strings.Compare(path, m.pkgDir(i))
803         })
804         if !ok {
805                 return &IndexPackage{error: fmt.Errorf("%w %q in:\n\t%s", errCannotFindPackage, path, filepath.Join(m.modroot, path))}
806         }
807         return m.pkg(i)
808 }
809
810 // pkgAt returns the i'th IndexPackage in m.
811 func (m *Module) pkg(i int) *IndexPackage {
812         r := m.d.readAt(m.pkgOff(i))
813         p := new(IndexPackage)
814         if errstr := r.string(); errstr != "" {
815                 p.error = errors.New(errstr)
816         }
817         p.dir = r.string()
818         p.sourceFiles = make([]*sourceFile, r.int())
819         for i := range p.sourceFiles {
820                 p.sourceFiles[i] = &sourceFile{
821                         d:   m.d,
822                         pos: r.int(),
823                 }
824         }
825         p.modroot = m.modroot
826         return p
827 }
828
829 // sourceFile represents the information of a given source file in the module index.
830 type sourceFile struct {
831         d               *decoder // encoding of this source file
832         pos             int      // start of sourceFile encoding in d
833         onceReadImports sync.Once
834         savedImports    []rawImport // saved imports so that they're only read once
835 }
836
837 // Offsets for fields in the sourceFile.
838 const (
839         sourceFileError = 4 * iota
840         sourceFileParseError
841         sourceFileSynopsis
842         sourceFileName
843         sourceFilePkgName
844         sourceFileIgnoreFile
845         sourceFileBinaryOnly
846         sourceFileCgoDirectives
847         sourceFileGoBuildConstraint
848         sourceFileNumPlusBuildConstraints
849 )
850
851 func (sf *sourceFile) error() string {
852         return sf.d.stringAt(sf.pos + sourceFileError)
853 }
854 func (sf *sourceFile) parseError() string {
855         return sf.d.stringAt(sf.pos + sourceFileParseError)
856 }
857 func (sf *sourceFile) synopsis() string {
858         return sf.d.stringAt(sf.pos + sourceFileSynopsis)
859 }
860 func (sf *sourceFile) name() string {
861         return sf.d.stringAt(sf.pos + sourceFileName)
862 }
863 func (sf *sourceFile) pkgName() string {
864         return sf.d.stringAt(sf.pos + sourceFilePkgName)
865 }
866 func (sf *sourceFile) ignoreFile() bool {
867         return sf.d.boolAt(sf.pos + sourceFileIgnoreFile)
868 }
869 func (sf *sourceFile) binaryOnly() bool {
870         return sf.d.boolAt(sf.pos + sourceFileBinaryOnly)
871 }
872 func (sf *sourceFile) cgoDirectives() string {
873         return sf.d.stringAt(sf.pos + sourceFileCgoDirectives)
874 }
875 func (sf *sourceFile) goBuildConstraint() string {
876         return sf.d.stringAt(sf.pos + sourceFileGoBuildConstraint)
877 }
878
879 func (sf *sourceFile) plusBuildConstraints() []string {
880         pos := sf.pos + sourceFileNumPlusBuildConstraints
881         n := sf.d.intAt(pos)
882         pos += 4
883         ret := make([]string, n)
884         for i := 0; i < n; i++ {
885                 ret[i] = sf.d.stringAt(pos)
886                 pos += 4
887         }
888         return ret
889 }
890
891 func (sf *sourceFile) importsOffset() int {
892         pos := sf.pos + sourceFileNumPlusBuildConstraints
893         n := sf.d.intAt(pos)
894         // each build constraint is 1 uint32
895         return pos + 4 + n*4
896 }
897
898 func (sf *sourceFile) embedsOffset() int {
899         pos := sf.importsOffset()
900         n := sf.d.intAt(pos)
901         // each import is 5 uint32s (string + tokpos)
902         return pos + 4 + n*(4*5)
903 }
904
905 func (sf *sourceFile) imports() []rawImport {
906         sf.onceReadImports.Do(func() {
907                 importsOffset := sf.importsOffset()
908                 r := sf.d.readAt(importsOffset)
909                 numImports := r.int()
910                 ret := make([]rawImport, numImports)
911                 for i := 0; i < numImports; i++ {
912                         ret[i] = rawImport{r.string(), r.tokpos()}
913                 }
914                 sf.savedImports = ret
915         })
916         return sf.savedImports
917 }
918
919 func (sf *sourceFile) embeds() []embed {
920         embedsOffset := sf.embedsOffset()
921         r := sf.d.readAt(embedsOffset)
922         numEmbeds := r.int()
923         ret := make([]embed, numEmbeds)
924         for i := range ret {
925                 ret[i] = embed{r.string(), r.tokpos()}
926         }
927         return ret
928 }
929
930 func asString(b []byte) string {
931         return unsafe.String(unsafe.SliceData(b), len(b))
932 }
933
934 // A decoder helps decode the index format.
935 type decoder struct {
936         data []byte // data after header
937         str  []byte // string table
938 }
939
940 // intAt returns the int at the given offset in d.data.
941 func (d *decoder) intAt(off int) int {
942         if off < 0 || len(d.data)-off < 4 {
943                 panic(errCorrupt)
944         }
945         i := binary.LittleEndian.Uint32(d.data[off : off+4])
946         if int32(i)>>31 != 0 {
947                 panic(errCorrupt)
948         }
949         return int(i)
950 }
951
952 // boolAt returns the bool at the given offset in d.data.
953 func (d *decoder) boolAt(off int) bool {
954         return d.intAt(off) != 0
955 }
956
957 // stringTableAt returns the string pointed at by the int at the given offset in d.data.
958 func (d *decoder) stringAt(off int) string {
959         return d.stringTableAt(d.intAt(off))
960 }
961
962 // stringTableAt returns the string at the given offset in the string table d.str.
963 func (d *decoder) stringTableAt(off int) string {
964         if off < 0 || off >= len(d.str) {
965                 panic(errCorrupt)
966         }
967         s := d.str[off:]
968         v, n := binary.Uvarint(s)
969         if n <= 0 || v > uint64(len(s[n:])) {
970                 panic(errCorrupt)
971         }
972         return asString(s[n : n+int(v)])
973 }
974
975 // A reader reads sequential fields from a section of the index format.
976 type reader struct {
977         d   *decoder
978         pos int
979 }
980
981 // readAt returns a reader starting at the given position in d.
982 func (d *decoder) readAt(pos int) *reader {
983         return &reader{d, pos}
984 }
985
986 // int reads the next int.
987 func (r *reader) int() int {
988         i := r.d.intAt(r.pos)
989         r.pos += 4
990         return i
991 }
992
993 // string reads the next string.
994 func (r *reader) string() string {
995         return r.d.stringTableAt(r.int())
996 }
997
998 // bool reads the next bool.
999 func (r *reader) bool() bool {
1000         return r.int() != 0
1001 }
1002
1003 // tokpos reads the next token.Position.
1004 func (r *reader) tokpos() token.Position {
1005         return token.Position{
1006                 Filename: r.string(),
1007                 Offset:   r.int(),
1008                 Line:     r.int(),
1009                 Column:   r.int(),
1010         }
1011 }