Debian Codegraph @

src/go/build/build.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package build
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "go/ast"
12 "go/build/constraint"
13 "go/doc"
14 "go/token"
15 "internal/buildcfg"
16 "internal/godebug"
17 "internal/goroot"
18 "internal/goversion"
19 "internal/platform"
20 "internal/syslist"
21 "io"
22 "io/fs"
23 "os"
24 "os/exec"
25 pathpkg "path"
26 "path/filepath"
27 "runtime"
28 "slices"
29 "strconv"
30 "strings"
31 "unicode"
32 "unicode/utf8"
33 _ "unsafe" // for linkname
34 )
35
36 // A Context specifies the supporting context for a build.
37 type Context struct {
38 GOARCH string // target architecture
39 GOOS string // target operating system
40 GOROOT string // Go root
41 GOPATH string // Go paths
42
43 // Dir is the caller's working directory, or the empty string to use
44 // the current directory of the running process. In module mode, this is used
45 // to locate the main module.
46 //
47 // If Dir is non-empty, directories passed to Import and ImportDir must
48 // be absolute.
49 Dir string
50
51 CgoEnabled bool // whether cgo files are included
52 UseAllFiles bool // use files regardless of go:build lines, file names
53 Compiler string // compiler to assume when computing target paths
54
55 // The build, tool, and release tags specify build constraints
56 // that should be considered satisfied when processing go:build lines.
57 // Clients creating a new context may customize BuildTags, which
58 // defaults to empty, but it is usually an error to customize ToolTags or ReleaseTags.
59 // ToolTags defaults to build tags appropriate to the current Go toolchain configuration.
60 // ReleaseTags defaults to the list of Go releases the current release is compatible with.
61 // BuildTags is not set for the Default build Context.
62 // In addition to the BuildTags, ToolTags, and ReleaseTags, build constraints
63 // consider the values of GOARCH and GOOS as satisfied tags.
64 // The last element in ReleaseTags is assumed to be the current release.
65 BuildTags []string
66 ToolTags []string
67 ReleaseTags []string
68
69 // The install suffix specifies a suffix to use in the name of the installation
70 // directory. By default it is empty, but custom builds that need to keep
71 // their outputs separate can set InstallSuffix to do so. For example, when
72 // using the race detector, the go command uses InstallSuffix = "race", so
73 // that on a Linux/386 system, packages are written to a directory named
74 // "linux_386_race" instead of the usual "linux_386".
75 InstallSuffix string
76
77 // By default, Import uses the operating system's file system calls
78 // to read directories and files. To read from other sources,
79 // callers can set the following functions. They all have default
80 // behaviors that use the local file system, so clients need only set
81 // the functions whose behaviors they wish to change.
82
83 // JoinPath joins the sequence of path fragments into a single path.
84 // If JoinPath is nil, Import uses filepath.Join.
85 JoinPath func(elem ...string) string
86
87 // SplitPathList splits the path list into a slice of individual paths.
88 // If SplitPathList is nil, Import uses filepath.SplitList.
89 SplitPathList func(list string) []string
90
91 // IsAbsPath reports whether path is an absolute path.
92 // If IsAbsPath is nil, Import uses filepath.IsAbs.
93 IsAbsPath func(path string) bool
94
95 // IsDir reports whether the path names a directory.
96 // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method.
97 IsDir func(path string) bool
98
99 // HasSubdir reports whether dir is lexically a subdirectory of
100 // root, perhaps multiple levels below. It does not try to check
101 // whether dir exists.
102 // If so, HasSubdir sets rel to a slash-separated path that
103 // can be joined to root to produce a path equivalent to dir.
104 // If HasSubdir is nil, Import uses an implementation built on
105 // filepath.EvalSymlinks.
106 HasSubdir func(root, dir string) (rel string, ok bool)
107
108 // ReadDir returns a slice of fs.FileInfo, sorted by Name,
109 // describing the content of the named directory.
110 // If ReadDir is nil, Import uses os.ReadDir.
111 ReadDir func(dir string) ([]fs.FileInfo, error)
112
113 // OpenFile opens a file (not a directory) for reading.
114 // If OpenFile is nil, Import uses os.Open.
115 OpenFile func(path string) (io.ReadCloser, error)
116 }
117
118 // joinPath calls ctxt.JoinPath (if not nil) or else filepath.Join.
119 func (ctxt *Context) joinPath(elem ...string) string {
120 if f := ctxt.JoinPath; f != nil {
121 return f(elem...)
122 }
123 return filepath.Join(elem...)
124 }
125
126 // splitPathList calls ctxt.SplitPathList (if not nil) or else filepath.SplitList.
127 func (ctxt *Context) splitPathList(s string) []string {
128 if f := ctxt.SplitPathList; f != nil {
129 return f(s)
130 }
131 return filepath.SplitList(s)
132 }
133
134 // isAbsPath calls ctxt.IsAbsPath (if not nil) or else filepath.IsAbs.
135 func (ctxt *Context) isAbsPath(path string) bool {
136 if f := ctxt.IsAbsPath; f != nil {
137 return f(path)
138 }
139 return filepath.IsAbs(path)
140 }
141
142 // isDir calls ctxt.IsDir (if not nil) or else uses os.Stat.
143 func (ctxt *Context) isDir(path string) bool {
144 if f := ctxt.IsDir; f != nil {
145 return f(path)
146 }
147 fi, err := os.Stat(path)
148 return err == nil && fi.IsDir()
149 }
150
151 // hasSubdir calls ctxt.HasSubdir (if not nil) or else uses
152 // the local file system to answer the question.
153 func (ctxt *Context) hasSubdir(root, dir string) (rel string, ok bool) {
154 if f := ctxt.HasSubdir; f != nil {
155 return f(root, dir)
156 }
157
158 // Try using paths we received.
159 if rel, ok = hasSubdir(root, dir); ok {
160 return
161 }
162
163 // Try expanding symlinks and comparing
164 // expanded against unexpanded and
165 // expanded against expanded.
166 rootSym, _ := filepath.EvalSymlinks(root)
167 dirSym, _ := filepath.EvalSymlinks(dir)
168
169 if rel, ok = hasSubdir(rootSym, dir); ok {
170 return
171 }
172 if rel, ok = hasSubdir(root, dirSym); ok {
173 return
174 }
175 return hasSubdir(rootSym, dirSym)
176 }
177
178 // hasSubdir reports if dir is within root by performing lexical analysis only.
179 func hasSubdir(root, dir string) (rel string, ok bool) {
180 const sep = string(filepath.Separator)
181 root = filepath.Clean(root)
182 if !strings.HasSuffix(root, sep) {
183 root += sep
184 }
185 dir = filepath.Clean(dir)
186 after, found := strings.CutPrefix(dir, root)
187 if !found {
188 return "", false
189 }
190 return filepath.ToSlash(after), true
191 }
192
193 // readDir calls ctxt.ReadDir (if not nil) or else os.ReadDir.
194 func (ctxt *Context) readDir(path string) ([]fs.DirEntry, error) {
195 // TODO: add a fs.DirEntry version of Context.ReadDir
196 if f := ctxt.ReadDir; f != nil {
197 fis, err := f(path)
198 if err != nil {
199 return nil, err
200 }
201 des := make([]fs.DirEntry, len(fis))
202 for i, fi := range fis {
203 des[i] = fs.FileInfoToDirEntry(fi)
204 }
205 return des, nil
206 }
207 return os.ReadDir(path)
208 }
209
210 // openFile calls ctxt.OpenFile (if not nil) or else os.Open.
211 func (ctxt *Context) openFile(path string) (io.ReadCloser, error) {
212 if fn := ctxt.OpenFile; fn != nil {
213 return fn(path)
214 }
215
216 f, err := os.Open(path)
217 if err != nil {
218 return nil, err // nil interface
219 }
220 return f, nil
221 }
222
223 // isFile determines whether path is a file by trying to open it.
224 // It reuses openFile instead of adding another function to the
225 // list in Context.
226 func (ctxt *Context) isFile(path string) bool {
227 f, err := ctxt.openFile(path)
228 if err != nil {
229 return false
230 }
231 f.Close()
232 return true
233 }
234
235 // gopath returns the list of Go path directories.
236 func (ctxt *Context) gopath() []string {
237 var all []string
238 for _, p := range ctxt.splitPathList(ctxt.GOPATH) {
239 if p == "" || p == ctxt.GOROOT {
240 // Empty paths are uninteresting.
241 // If the path is the GOROOT, ignore it.
242 // People sometimes set GOPATH=$GOROOT.
243 // Do not get confused by this common mistake.
244 continue
245 }
246 if strings.HasPrefix(p, "~") {
247 // Path segments starting with ~ on Unix are almost always
248 // users who have incorrectly quoted ~ while setting GOPATH,
249 // preventing it from expanding to $HOME.
250 // The situation is made more confusing by the fact that
251 // bash allows quoted ~ in $PATH (most shells do not).
252 // Do not get confused by this, and do not try to use the path.
253 // It does not exist, and printing errors about it confuses
254 // those users even more, because they think "sure ~ exists!".
255 // The go command diagnoses this situation and prints a
256 // useful error.
257 // On Windows, ~ is used in short names, such as c:\progra~1
258 // for c:\program files.
259 continue
260 }
261 all = append(all, p)
262 }
263 return all
264 }
265
266 // SrcDirs returns a list of package source root directories.
267 // It draws from the current Go root and Go path but omits directories
268 // that do not exist.
269 func (ctxt *Context) SrcDirs() []string {
270 var all []string
271 if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
272 dir := ctxt.joinPath(ctxt.GOROOT, "src")
273 if ctxt.isDir(dir) {
274 all = append(all, dir)
275 }
276 }
277 for _, p := range ctxt.gopath() {
278 dir := ctxt.joinPath(p, "src")
279 if ctxt.isDir(dir) {
280 all = append(all, dir)
281 }
282 }
283 return all
284 }
285
286 // Default is the default Context for builds.
287 // It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables
288 // if set, or else the compiled code's GOARCH, GOOS, and GOROOT.
289 var Default Context = defaultContext()
290
291 // Keep consistent with cmd/go/internal/cfg.defaultGOPATH.
292 func defaultGOPATH() string {
293 env := "HOME"
294 if runtime.GOOS == "windows" {
295 env = "USERPROFILE"
296 } else if runtime.GOOS == "plan9" {
297 env = "home"
298 }
299 if home := os.Getenv(env); home != "" {
300 def := filepath.Join(home, "go")
301 if filepath.Clean(def) == filepath.Clean(runtime.GOROOT()) {
302 // Don't set the default GOPATH to GOROOT,
303 // as that will trigger warnings from the go tool.
304 return ""
305 }
306 return def
307 }
308 return ""
309 }
310
311 // defaultToolTags should be an internal detail,
312 // but widely used packages access it using linkname.
313 // Notable members of the hall of shame include:
314 // - github.com/gopherjs/gopherjs
315 //
316 // Do not remove or change the type signature.
317 // See go.dev/issue/67401.
318 //
319 //go:linkname defaultToolTags
320 var defaultToolTags []string
321
322 // defaultReleaseTags should be an internal detail,
323 // but widely used packages access it using linkname.
324 // Notable members of the hall of shame include:
325 // - github.com/gopherjs/gopherjs
326 //
327 // Do not remove or change the type signature.
328 // See go.dev/issue/67401.
329 //
330 //go:linkname defaultReleaseTags
331 var defaultReleaseTags []string
332
333 func defaultContext() Context {
334 var c Context
335
336 c.GOARCH = buildcfg.GOARCH
337 c.GOOS = buildcfg.GOOS
338 if goroot := runtime.GOROOT(); goroot != "" {
339 c.GOROOT = filepath.Clean(goroot)
340 }
341 c.GOPATH = envOr("GOPATH", defaultGOPATH())
342 c.Compiler = runtime.Compiler
343 c.ToolTags = append(c.ToolTags, buildcfg.ToolTags...)
344
345 defaultToolTags = append([]string{}, c.ToolTags...) // our own private copy
346
347 // Each major Go release in the Go 1.x series adds a new
348 // "go1.x" release tag. That is, the go1.x tag is present in
349 // all releases >= Go 1.x. Code that requires Go 1.x or later
350 // should say "go:build go1.x", and code that should only be
351 // built before Go 1.x (perhaps it is the stub to use in that
352 // case) should say "go:build !go1.x".
353 // The last element in ReleaseTags is the current release.
354 for i := 1; i <= goversion.Version; i++ {
355 c.ReleaseTags = append(c.ReleaseTags, "go1."+strconv.Itoa(i))
356 }
357
358 defaultReleaseTags = append([]string{}, c.ReleaseTags...) // our own private copy
359
360 env := os.Getenv("CGO_ENABLED")
361 if env == "" {
362 env = buildcfg.DefaultCGO_ENABLED
363 }
364 switch env {
365 case "1":
366 c.CgoEnabled = true
367 case "0":
368 c.CgoEnabled = false
369 default:
370 // cgo must be explicitly enabled for cross compilation builds
371 if runtime.GOARCH == c.GOARCH && runtime.GOOS == c.GOOS {
372 c.CgoEnabled = platform.CgoSupported(c.GOOS, c.GOARCH)
373 break
374 }
375 c.CgoEnabled = false
376 }
377
378 return c
379 }
380
381 func envOr(name, def string) string {
382 s := os.Getenv(name)
383 if s == "" {
384 return def
385 }
386 return s
387 }
388
389 // An ImportMode controls the behavior of the Import method.
390 type ImportMode uint
391
392 const (
393 // If FindOnly is set, Import stops after locating the directory
394 // that should contain the sources for a package. It does not
395 // read any files in the directory.
396 FindOnly ImportMode = 1 << iota
397
398 // If AllowBinary is set, Import can be satisfied by a compiled
399 // package object without corresponding sources.
400 //
401 // Deprecated:
402 // The supported way to create a compiled-only package is to
403 // write source code containing a //go:binary-only-package comment at
404 // the top of the file. Such a package will be recognized
405 // regardless of this flag setting (because it has source code)
406 // and will have BinaryOnly set to true in the returned Package.
407 AllowBinary
408
409 // If ImportComment is set, parse import comments on package statements.
410 // Import returns an error if it finds a comment it cannot understand
411 // or finds conflicting comments in multiple source files.
412 // See golang.org/s/go14customimport for more information.
413 ImportComment
414
415 // By default, Import searches vendor directories
416 // that apply in the given source directory before searching
417 // the GOROOT and GOPATH roots.
418 // If an Import finds and returns a package using a vendor
419 // directory, the resulting ImportPath is the complete path
420 // to the package, including the path elements leading up
421 // to and including "vendor".
422 // For example, if Import("y", "x/subdir", 0) finds
423 // "x/vendor/y", the returned package's ImportPath is "x/vendor/y",
424 // not plain "y".
425 // See golang.org/s/go15vendor for more information.
426 //
427 // Setting IgnoreVendor ignores vendor directories.
428 //
429 // In contrast to the package's ImportPath,
430 // the returned package's Imports, TestImports, and XTestImports
431 // are always the exact import paths from the source files:
432 // Import makes no attempt to resolve or check those paths.
433 IgnoreVendor
434 )
435
436 // A Package describes the Go package found in a directory.
437 type Package struct {
438 Dir string // directory containing package sources
439 Name string // package name
440 ImportComment string // path in import comment on package statement
441 Doc string // documentation synopsis
442 ImportPath string // import path of package ("" if unknown)
443 Root string // root of Go tree where this package lives
444 SrcRoot string // package source root directory ("" if unknown)
445 PkgRoot string // package install root directory ("" if unknown)
446 PkgTargetRoot string // architecture dependent install root directory ("" if unknown)
447 BinDir string // command install directory ("" if unknown)
448 Goroot bool // package found in Go root
449 PkgObj string // installed .a file
450 AllTags []string // tags that can influence file selection in this directory
451 ConflictDir string // this directory shadows Dir in $GOPATH
452 BinaryOnly bool // cannot be rebuilt from source (has //go:binary-only-package comment)
453
454 // Source files
455 GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
456 CgoFiles []string // .go source files that import "C"
457 IgnoredGoFiles []string // .go source files ignored for this build (including ignored _test.go files)
458 InvalidGoFiles []string // .go source files with detected problems (parse error, wrong package name, and so on)
459 IgnoredOtherFiles []string // non-.go source files ignored for this build
460 CFiles []string // .c source files
461 CXXFiles []string // .cc, .cpp and .cxx source files
462 MFiles []string // .m (Objective-C) source files
463 HFiles []string // .h, .hh, .hpp and .hxx source files
464 FFiles []string // .f, .F, .for and .f90 Fortran source files
465 SFiles []string // .s source files
466 SwigFiles []string // .swig files
467 SwigCXXFiles []string // .swigcxx files
468 SysoFiles []string // .syso system object files to add to archive
469
470 // Cgo directives
471 CgoCFLAGS []string // Cgo CFLAGS directives
472 CgoCPPFLAGS []string // Cgo CPPFLAGS directives
473 CgoCXXFLAGS []string // Cgo CXXFLAGS directives
474 CgoFFLAGS []string // Cgo FFLAGS directives
475 CgoLDFLAGS []string // Cgo LDFLAGS directives
476 CgoPkgConfig []string // Cgo pkg-config directives
477
478 // Test information
479 TestGoFiles []string // _test.go files in package
480 XTestGoFiles []string // _test.go files outside package
481
482 // Go directive comments (//go:zzz...) found in source files.
483 Directives []Directive
484 TestDirectives []Directive
485 XTestDirectives []Directive
486
487 // Dependency information
488 Imports []string // import paths from GoFiles, CgoFiles
489 ImportPos map[string][]token.Position // line information for Imports
490 TestImports []string // import paths from TestGoFiles
491 TestImportPos map[string][]token.Position // line information for TestImports
492 XTestImports []string // import paths from XTestGoFiles
493 XTestImportPos map[string][]token.Position // line information for XTestImports
494
495 // //go:embed patterns found in Go source files
496 // For example, if a source file says
497 // //go:embed a* b.c
498 // then the list will contain those two strings as separate entries.
499 // (See package embed for more details about //go:embed.)
500 EmbedPatterns []string // patterns from GoFiles, CgoFiles
501 EmbedPatternPos map[string][]token.Position // line information for EmbedPatterns
502 TestEmbedPatterns []string // patterns from TestGoFiles
503 TestEmbedPatternPos map[string][]token.Position // line information for TestEmbedPatterns
504 XTestEmbedPatterns []string // patterns from XTestGoFiles
505 XTestEmbedPatternPos map[string][]token.Position // line information for XTestEmbedPatternPos
506 }
507
508 // A Directive is a Go directive comment (//go:zzz...) found in a source file.
509 type Directive struct {
510 Text string // full line comment including leading slashes
511 Pos token.Position // position of comment
512 }
513
514 // IsCommand reports whether the package is considered a
515 // command to be installed (not just a library).
516 // Packages named "main" are treated as commands.
517 func (p *Package) IsCommand() bool {
518 return p.Name == "main"
519 }
520
521 // ImportDir is like [Import] but processes the Go package found in
522 // the named directory.
523 func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error) {
524 return ctxt.Import(".", dir, mode)
525 }
526
527 // NoGoError is the error used by [Import] to describe a directory
528 // containing no buildable Go source files. (It may still contain
529 // test files, files hidden by build tags, and so on.)
530 type NoGoError struct {
531 Dir string
532 }
533
534 func (e *NoGoError) Error() string {
535 return "no buildable Go source files in " + e.Dir
536 }
537
538 // MultiplePackageError describes a directory containing
539 // multiple buildable Go source files for multiple packages.
540 type MultiplePackageError struct {
541 Dir string // directory containing files
542 Packages []string // package names found
543 Files []string // corresponding files: Files[i] declares package Packages[i]
544 }
545
546 func (e *MultiplePackageError) Error() string {
547 // Error string limited to two entries for compatibility.
548 return fmt.Sprintf("found packages %s (%s) and %s (%s) in %s", e.Packages[0], e.Files[0], e.Packages[1], e.Files[1], e.Dir)
549 }
550
551 func nameExt(name string) string {
552 i := strings.LastIndex(name, ".")
553 if i < 0 {
554 return ""
555 }
556 return name[i:]
557 }
558
559 var installgoroot = godebug.New("installgoroot")
560
561 // Import returns details about the Go package named by the import path,
562 // interpreting local import paths relative to the srcDir directory.
563 // If the path is a local import path naming a package that can be imported
564 // using a standard import path, the returned package will set p.ImportPath
565 // to that path.
566 //
567 // In the directory containing the package, .go, .c, .h, and .s files are
568 // considered part of the package except for:
569 //
570 // - .go files in package documentation
571 // - files starting with _ or . (likely editor temporary files)
572 // - files with build constraints not satisfied by the context
573 //
574 // If an error occurs, Import returns a non-nil error and a non-nil
575 // *[Package] containing partial information.
576 func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error) {
577 p := &Package{
578 ImportPath: path,
579 }
580 if path == "" {
581 return p, fmt.Errorf("import %q: invalid import path", path)
582 }
583
584 var pkgtargetroot string
585 var pkga string
586 var pkgerr error
587 suffix := ""
588 if ctxt.InstallSuffix != "" {
589 suffix = "_" + ctxt.InstallSuffix
590 }
591 switch ctxt.Compiler {
592 case "gccgo":
593 pkgtargetroot = "pkg/gccgo_" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
594 case "gc":
595 pkgtargetroot = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
596 default:
597 // Save error for end of function.
598 pkgerr = fmt.Errorf("import %q: unknown compiler %q", path, ctxt.Compiler)
599 }
600 setPkga := func() {
601 switch ctxt.Compiler {
602 case "gccgo":
603 dir, elem := pathpkg.Split(p.ImportPath)
604 pkga = pkgtargetroot + "/" + dir + "lib" + elem + ".a"
605 case "gc":
606 pkga = pkgtargetroot + "/" + p.ImportPath + ".a"
607 }
608 }
609 setPkga()
610
611 binaryOnly := false
612 if IsLocalImport(path) {
613 pkga = "" // local imports have no installed path
614 if srcDir == "" {
615 return p, fmt.Errorf("import %q: import relative to unknown directory", path)
616 }
617 if !ctxt.isAbsPath(path) {
618 p.Dir = ctxt.joinPath(srcDir, path)
619 }
620 // p.Dir directory may or may not exist. Gather partial information first, check if it exists later.
621 // Determine canonical import path, if any.
622 // Exclude results where the import path would include /testdata/.
623 inTestdata := func(sub string) bool {
624 return strings.Contains(sub, "/testdata/") || strings.HasSuffix(sub, "/testdata") || strings.HasPrefix(sub, "testdata/") || sub == "testdata"
625 }
626 if ctxt.GOROOT != "" {
627 root := ctxt.joinPath(ctxt.GOROOT, "src")
628 if sub, ok := ctxt.hasSubdir(root, p.Dir); ok && !inTestdata(sub) {
629 p.Goroot = true
630 p.ImportPath = sub
631 p.Root = ctxt.GOROOT
632 setPkga() // p.ImportPath changed
633 goto Found
634 }
635 }
636 all := ctxt.gopath()
637 for i, root := range all {
638 rootsrc := ctxt.joinPath(root, "src")
639 if sub, ok := ctxt.hasSubdir(rootsrc, p.Dir); ok && !inTestdata(sub) {
640 // We found a potential import path for dir,
641 // but check that using it wouldn't find something
642 // else first.
643 if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
644 if dir := ctxt.joinPath(ctxt.GOROOT, "src", sub); ctxt.isDir(dir) {
645 p.ConflictDir = dir
646 goto Found
647 }
648 }
649 for _, earlyRoot := range all[:i] {
650 if dir := ctxt.joinPath(earlyRoot, "src", sub); ctxt.isDir(dir) {
651 p.ConflictDir = dir
652 goto Found
653 }
654 }
655
656 // sub would not name some other directory instead of this one.
657 // Record it.
658 p.ImportPath = sub
659 p.Root = root
660 setPkga() // p.ImportPath changed
661 goto Found
662 }
663 }
664 // It's okay that we didn't find a root containing dir.
665 // Keep going with the information we have.
666 } else {
667 if strings.HasPrefix(path, "/") {
668 return p, fmt.Errorf("import %q: cannot import absolute path", path)
669 }
670
671 if err := ctxt.importGo(p, path, srcDir, mode); err == nil {
672 goto Found
673 } else if err != errNoModules {
674 return p, err
675 }
676
677 gopath := ctxt.gopath() // needed twice below; avoid computing many times
678
679 // tried records the location of unsuccessful package lookups
680 var tried struct {
681 vendor []string
682 goroot string
683 gopath []string
684 }
685
686 // Vendor directories get first chance to satisfy import.
687 if mode&IgnoreVendor == 0 && srcDir != "" {
688 searchVendor := func(root string, isGoroot bool) bool {
689 sub, ok := ctxt.hasSubdir(root, srcDir)
690 if !ok || !strings.HasPrefix(sub, "src/") || strings.Contains(sub, "/testdata/") {
691 return false
692 }
693 for {
694 vendor := ctxt.joinPath(root, sub, "vendor")
695 if ctxt.isDir(vendor) {
696 dir := ctxt.joinPath(vendor, path)
697 if ctxt.isDir(dir) && hasGoFiles(ctxt, dir) {
698 p.Dir = dir
699 p.ImportPath = strings.TrimPrefix(pathpkg.Join(sub, "vendor", path), "src/")
700 p.Goroot = isGoroot
701 p.Root = root
702 setPkga() // p.ImportPath changed
703 return true
704 }
705 tried.vendor = append(tried.vendor, dir)
706 }
707 i := strings.LastIndex(sub, "/")
708 if i < 0 {
709 break
710 }
711 sub = sub[:i]
712 }
713 return false
714 }
715 if ctxt.Compiler != "gccgo" && ctxt.GOROOT != "" && searchVendor(ctxt.GOROOT, true) {
716 goto Found
717 }
718 for _, root := range gopath {
719 if searchVendor(root, false) {
720 goto Found
721 }
722 }
723 }
724
725 // Determine directory from import path.
726 if ctxt.GOROOT != "" {
727 // If the package path starts with "vendor/", only search GOROOT before
728 // GOPATH if the importer is also within GOROOT. That way, if the user has
729 // vendored in a package that is subsequently included in the standard
730 // distribution, they'll continue to pick up their own vendored copy.
731 gorootFirst := srcDir == "" || !strings.HasPrefix(path, "vendor/")
732 if !gorootFirst {
733 _, gorootFirst = ctxt.hasSubdir(ctxt.GOROOT, srcDir)
734 }
735 if gorootFirst {
736 dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
737 if ctxt.Compiler != "gccgo" {
738 isDir := ctxt.isDir(dir)
739 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
740 if isDir || binaryOnly {
741 p.Dir = dir
742 p.Goroot = true
743 p.Root = ctxt.GOROOT
744 goto Found
745 }
746 }
747 tried.goroot = dir
748 }
749 if ctxt.Compiler == "gccgo" && goroot.IsStandardPackage(os.ReadDir, ctxt.GOROOT, ctxt.Compiler, path) {
750 // TODO(bcmills): Setting p.Dir here is misleading, because gccgo
751 // doesn't actually load its standard-library packages from this
752 // directory. See if we can leave it unset.
753 p.Dir = ctxt.joinPath(ctxt.GOROOT, "src", path)
754 p.Goroot = true
755 p.Root = ctxt.GOROOT
756 goto Found
757 }
758 }
759 for _, root := range gopath {
760 dir := ctxt.joinPath(root, "src", path)
761 isDir := ctxt.isDir(dir)
762 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(root, pkga))
763 if isDir || binaryOnly {
764 p.Dir = dir
765 p.Root = root
766 goto Found
767 }
768 tried.gopath = append(tried.gopath, dir)
769 }
770
771 // If we tried GOPATH first due to a "vendor/" prefix, fall back to GOPATH.
772 // That way, the user can still get useful results from 'go list' for
773 // standard-vendored paths passed on the command line.
774 if ctxt.GOROOT != "" && tried.goroot == "" {
775 dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
776 if ctxt.Compiler != "gccgo" {
777 isDir := ctxt.isDir(dir)
778 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
779 if isDir || binaryOnly {
780 p.Dir = dir
781 p.Goroot = true
782 p.Root = ctxt.GOROOT
783 goto Found
784 }
785 }
786 tried.goroot = dir
787 }
788
789 // package was not found
790 var paths []string
791 format := "\t%s (vendor tree)"
792 for _, dir := range tried.vendor {
793 paths = append(paths, fmt.Sprintf(format, dir))
794 format = "\t%s"
795 }
796 if tried.goroot != "" {
797 paths = append(paths, fmt.Sprintf("\t%s (from $GOROOT)", tried.goroot))
798 } else {
799 paths = append(paths, "\t($GOROOT not set)")
800 }
801 format = "\t%s (from $GOPATH)"
802 for _, dir := range tried.gopath {
803 paths = append(paths, fmt.Sprintf(format, dir))
804 format = "\t%s"
805 }
806 if len(tried.gopath) == 0 {
807 paths = append(paths, "\t($GOPATH not set. For more details see: 'go help gopath')")
808 }
809 return p, fmt.Errorf("cannot find package %q in any of:\n%s", path, strings.Join(paths, "\n"))
810 }
811
812 Found:
813 if p.Root != "" {
814 p.SrcRoot = ctxt.joinPath(p.Root, "src")
815 p.PkgRoot = ctxt.joinPath(p.Root, "pkg")
816 p.BinDir = ctxt.joinPath(p.Root, "bin")
817 if pkga != "" {
818 // Always set PkgTargetRoot. It might be used when building in shared
819 // mode.
820 p.PkgTargetRoot = ctxt.joinPath(p.Root, pkgtargetroot)
821
822 // Set the install target if applicable.
823 if !p.Goroot || (installgoroot.Value() == "all" && p.ImportPath != "unsafe" && p.ImportPath != "builtin") {
824 if p.Goroot {
825 installgoroot.IncNonDefault()
826 }
827 p.PkgObj = ctxt.joinPath(p.Root, pkga)
828 }
829 }
830 }
831
832 // If it's a local import path, by the time we get here, we still haven't checked
833 // that p.Dir directory exists. This is the right time to do that check.
834 // We can't do it earlier, because we want to gather partial information for the
835 // non-nil *Package returned when an error occurs.
836 // We need to do this before we return early on FindOnly flag.
837 if IsLocalImport(path) && !ctxt.isDir(p.Dir) {
838 if ctxt.Compiler == "gccgo" && p.Goroot {
839 // gccgo has no sources for GOROOT packages.
840 return p, nil
841 }
842
843 // package was not found
844 return p, fmt.Errorf("cannot find package %q in:\n\t%s", p.ImportPath, p.Dir)
845 }
846
847 if mode&FindOnly != 0 {
848 return p, pkgerr
849 }
850 if binaryOnly && (mode&AllowBinary) != 0 {
851 return p, pkgerr
852 }
853
854 if ctxt.Compiler == "gccgo" && p.Goroot {
855 // gccgo has no sources for GOROOT packages.
856 return p, nil
857 }
858
859 dirs, err := ctxt.readDir(p.Dir)
860 if err != nil {
861 return p, err
862 }
863
864 var badGoError error
865 badGoFiles := make(map[string]bool)
866 badGoFile := func(name string, err error) {
867 if badGoError == nil {
868 badGoError = err
869 }
870 if !badGoFiles[name] {
871 p.InvalidGoFiles = append(p.InvalidGoFiles, name)
872 badGoFiles[name] = true
873 }
874 }
875
876 var Sfiles []string // files with ".S"(capital S)/.sx(capital s equivalent for case insensitive filesystems)
877 var firstFile, firstCommentFile string
878 embedPos := make(map[string][]token.Position)
879 testEmbedPos := make(map[string][]token.Position)
880 xTestEmbedPos := make(map[string][]token.Position)
881 importPos := make(map[string][]token.Position)
882 testImportPos := make(map[string][]token.Position)
883 xTestImportPos := make(map[string][]token.Position)
884 allTags := make(map[string]bool)
885 fset := token.NewFileSet()
886 for _, d := range dirs {
887 if d.IsDir() {
888 continue
889 }
890 if d.Type() == fs.ModeSymlink {
891 if ctxt.isDir(ctxt.joinPath(p.Dir, d.Name())) {
892 // Symlinks to directories are not source files.
893 continue
894 }
895 }
896
897 name := d.Name()
898 ext := nameExt(name)
899
900 info, err := ctxt.matchFile(p.Dir, name, allTags, &p.BinaryOnly, fset)
901 if err != nil && strings.HasSuffix(name, ".go") {
902 badGoFile(name, err)
903 continue
904 }
905 if info == nil {
906 if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
907 // not due to build constraints - don't report
908 } else if ext == ".go" {
909 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
910 } else if fileListForExt(p, ext) != nil {
911 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, name)
912 }
913 continue
914 }
915
916 // Going to save the file. For non-Go files, can stop here.
917 switch ext {
918 case ".go":
919 // keep going
920 case ".S", ".sx":
921 // special case for cgo, handled at end
922 Sfiles = append(Sfiles, name)
923 continue
924 default:
925 if list := fileListForExt(p, ext); list != nil {
926 *list = append(*list, name)
927 }
928 continue
929 }
930
931 data, filename := info.header, info.name
932
933 if info.parseErr != nil {
934 badGoFile(name, info.parseErr)
935 // Fall through: we might still have a partial AST in info.parsed,
936 // and we want to list files with parse errors anyway.
937 }
938
939 var pkg string
940 if info.parsed != nil {
941 pkg = info.parsed.Name.Name
942 if pkg == "documentation" {
943 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
944 continue
945 }
946 }
947
948 isTest := strings.HasSuffix(name, "_test.go")
949 isXTest := false
950 if isTest && strings.HasSuffix(pkg, "_test") && p.Name != pkg {
951 isXTest = true
952 pkg = pkg[:len(pkg)-len("_test")]
953 }
954
955 if p.Name == "" {
956 p.Name = pkg
957 firstFile = name
958 } else if pkg != p.Name {
959 // TODO(#45999): The choice of p.Name is arbitrary based on file iteration
960 // order. Instead of resolving p.Name arbitrarily, we should clear out the
961 // existing name and mark the existing files as also invalid.
962 badGoFile(name, &MultiplePackageError{
963 Dir: p.Dir,
964 Packages: []string{p.Name, pkg},
965 Files: []string{firstFile, name},
966 })
967 }
968 // Grab the first package comment as docs, provided it is not from a test file.
969 if info.parsed != nil && info.parsed.Doc != nil && p.Doc == "" && !isTest && !isXTest {
970 p.Doc = doc.Synopsis(info.parsed.Doc.Text())
971 }
972
973 if mode&ImportComment != 0 {
974 qcom, line := findImportComment(data)
975 if line != 0 {
976 com, err := strconv.Unquote(qcom)
977 if err != nil {
978 badGoFile(name, fmt.Errorf("%s:%d: cannot parse import comment", filename, line))
979 } else if p.ImportComment == "" {
980 p.ImportComment = com
981 firstCommentFile = name
982 } else if p.ImportComment != com {
983 badGoFile(name, fmt.Errorf("found import comments %q (%s) and %q (%s) in %s", p.ImportComment, firstCommentFile, com, name, p.Dir))
984 }
985 }
986 }
987
988 // Record imports and information about cgo.
989 isCgo := false
990 for _, imp := range info.imports {
991 if imp.path == "C" {
992 if isTest {
993 badGoFile(name, fmt.Errorf("use of cgo in test %s not supported", filename))
994 continue
995 }
996 isCgo = true
997 if imp.doc != nil {
998 if err := ctxt.saveCgo(filename, p, imp.doc); err != nil {
999 badGoFile(name, err)
1000 }
1001 }
1002 }
1003 }
1004
1005 var fileList *[]string
1006 var importMap, embedMap map[string][]token.Position
1007 var directives *[]Directive
1008 switch {
1009 case isCgo:
1010 allTags["cgo"] = true
1011 if ctxt.CgoEnabled {
1012 fileList = &p.CgoFiles
1013 importMap = importPos
1014 embedMap = embedPos
1015 directives = &p.Directives
1016 } else {
1017 // Ignore imports and embeds from cgo files if cgo is disabled.
1018 fileList = &p.IgnoredGoFiles
1019 }
1020 case isXTest:
1021 fileList = &p.XTestGoFiles
1022 importMap = xTestImportPos
1023 embedMap = xTestEmbedPos
1024 directives = &p.XTestDirectives
1025 case isTest:
1026 fileList = &p.TestGoFiles
1027 importMap = testImportPos
1028 embedMap = testEmbedPos
1029 directives = &p.TestDirectives
1030 default:
1031 fileList = &p.GoFiles
1032 importMap = importPos
1033 embedMap = embedPos
1034 directives = &p.Directives
1035 }
1036 *fileList = append(*fileList, name)
1037 if importMap != nil {
1038 for _, imp := range info.imports {
1039 importMap[imp.path] = append(importMap[imp.path], fset.Position(imp.pos))
1040 }
1041 }
1042 if embedMap != nil {
1043 for _, emb := range info.embeds {
1044 embedMap[emb.pattern] = append(embedMap[emb.pattern], emb.pos)
1045 }
1046 }
1047 if directives != nil {
1048 *directives = append(*directives, info.directives...)
1049 }
1050 }
1051
1052 for tag := range allTags {
1053 p.AllTags = append(p.AllTags, tag)
1054 }
1055 slices.Sort(p.AllTags)
1056
1057 p.EmbedPatterns, p.EmbedPatternPos = cleanDecls(embedPos)
1058 p.TestEmbedPatterns, p.TestEmbedPatternPos = cleanDecls(testEmbedPos)
1059 p.XTestEmbedPatterns, p.XTestEmbedPatternPos = cleanDecls(xTestEmbedPos)
1060
1061 p.Imports, p.ImportPos = cleanDecls(importPos)
1062 p.TestImports, p.TestImportPos = cleanDecls(testImportPos)
1063 p.XTestImports, p.XTestImportPos = cleanDecls(xTestImportPos)
1064
1065 // add the .S/.sx files only if we are using cgo
1066 // (which means gcc will compile them).
1067 // The standard assemblers expect .s files.
1068 if len(p.CgoFiles) > 0 {
1069 p.SFiles = append(p.SFiles, Sfiles...)
1070 slices.Sort(p.SFiles)
1071 } else {
1072 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, Sfiles...)
1073 slices.Sort(p.IgnoredOtherFiles)
1074 }
1075
1076 if badGoError != nil {
1077 return p, badGoError
1078 }
1079 if len(p.GoFiles)+len(p.CgoFiles)+len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
1080 return p, &NoGoError{p.Dir}
1081 }
1082 return p, pkgerr
1083 }
1084
1085 func fileListForExt(p *Package, ext string) *[]string {
1086 switch ext {
1087 case ".c":
1088 return &p.CFiles
1089 case ".cc", ".cpp", ".cxx":
1090 return &p.CXXFiles
1091 case ".m":
1092 return &p.MFiles
1093 case ".h", ".hh", ".hpp", ".hxx":
1094 return &p.HFiles
1095 case ".f", ".F", ".for", ".f90":
1096 return &p.FFiles
1097 case ".s", ".S", ".sx":
1098 return &p.SFiles
1099 case ".swig":
1100 return &p.SwigFiles
1101 case ".swigcxx":
1102 return &p.SwigCXXFiles
1103 case ".syso":
1104 return &p.SysoFiles
1105 }
1106 return nil
1107 }
1108
1109 func uniq(list []string) []string {
1110 if list == nil {
1111 return nil
1112 }
1113 out := make([]string, len(list))
1114 copy(out, list)
1115 slices.Sort(out)
1116 uniq := out[:0]
1117 for _, x := range out {
1118 if len(uniq) == 0 || uniq[len(uniq)-1] != x {
1119 uniq = append(uniq, x)
1120 }
1121 }
1122 return uniq
1123 }
1124
1125 var errNoModules = errors.New("not using modules")
1126
1127 // importGo checks whether it can use the go command to find the directory for path.
1128 // If using the go command is not appropriate, importGo returns errNoModules.
1129 // Otherwise, importGo tries using the go command and reports whether that succeeded.
1130 // Using the go command lets build.Import and build.Context.Import find code
1131 // in Go modules. In the long term we want tools to use go/packages (currently golang.org/x/tools/go/packages),
1132 // which will also use the go command.
1133 // Invoking the go command here is not very efficient in that it computes information
1134 // about the requested package and all dependencies and then only reports about the requested package.
1135 // Then we reinvoke it for every dependency. But this is still better than not working at all.
1136 // See golang.org/issue/26504.
1137 func (ctxt *Context) importGo(p *Package, path, srcDir string, mode ImportMode) error {
1138 // To invoke the go command,
1139 // we must not being doing special things like AllowBinary or IgnoreVendor,
1140 // and all the file system callbacks must be nil (we're meant to use the local file system).
1141 if mode&AllowBinary != 0 || mode&IgnoreVendor != 0 ||
1142 ctxt.JoinPath != nil || ctxt.SplitPathList != nil || ctxt.IsAbsPath != nil || ctxt.IsDir != nil || ctxt.HasSubdir != nil || ctxt.ReadDir != nil || ctxt.OpenFile != nil || !slices.Equal(ctxt.ToolTags, defaultToolTags) || !slices.Equal(ctxt.ReleaseTags, defaultReleaseTags) {
1143 return errNoModules
1144 }
1145
1146 // If ctxt.GOROOT is not set, we don't know which go command to invoke,
1147 // and even if we did we might return packages in GOROOT that we wouldn't otherwise find
1148 // (because we don't know to search in 'go env GOROOT' otherwise).
1149 if ctxt.GOROOT == "" {
1150 return errNoModules
1151 }
1152
1153 // Predict whether module aware mode is enabled by checking the value of
1154 // GO111MODULE and looking for a go.mod file in the source directory or
1155 // one of its parents. Running 'go env GOMOD' in the source directory would
1156 // give a canonical answer, but we'd prefer not to execute another command.
1157 go111Module := os.Getenv("GO111MODULE")
1158 switch go111Module {
1159 case "off":
1160 return errNoModules
1161 default: // "", "on", "auto", anything else
1162 // Maybe use modules.
1163 }
1164
1165 if srcDir != "" {
1166 var absSrcDir string
1167 if filepath.IsAbs(srcDir) {
1168 absSrcDir = srcDir
1169 } else if ctxt.Dir != "" {
1170 return fmt.Errorf("go/build: Dir is non-empty, so relative srcDir is not allowed: %v", srcDir)
1171 } else {
1172 // Find the absolute source directory. hasSubdir does not handle
1173 // relative paths (and can't because the callbacks don't support this).
1174 var err error
1175 absSrcDir, err = filepath.Abs(srcDir)
1176 if err != nil {
1177 return errNoModules
1178 }
1179 }
1180
1181 // If the source directory is in GOROOT, then the in-process code works fine
1182 // and we should keep using it. Moreover, the 'go list' approach below doesn't
1183 // take standard-library vendoring into account and will fail.
1184 if _, ok := ctxt.hasSubdir(filepath.Join(ctxt.GOROOT, "src"), absSrcDir); ok {
1185 return errNoModules
1186 }
1187 }
1188
1189 // For efficiency, if path is a standard library package, let the usual lookup code handle it.
1190 if dir := ctxt.joinPath(ctxt.GOROOT, "src", path); ctxt.isDir(dir) {
1191 return errNoModules
1192 }
1193
1194 // If GO111MODULE=auto, look to see if there is a go.mod.
1195 // Since go1.13, it doesn't matter if we're inside GOPATH.
1196 if go111Module == "auto" {
1197 var (
1198 parent string
1199 err error
1200 )
1201 if ctxt.Dir == "" {
1202 parent, err = os.Getwd()
1203 if err != nil {
1204 // A nonexistent working directory can't be in a module.
1205 return errNoModules
1206 }
1207 } else {
1208 parent, err = filepath.Abs(ctxt.Dir)
1209 if err != nil {
1210 // If the caller passed a bogus Dir explicitly, that's materially
1211 // different from not having modules enabled.
1212 return err
1213 }
1214 }
1215 for {
1216 if f, err := ctxt.openFile(ctxt.joinPath(parent, "go.mod")); err == nil {
1217 buf := make([]byte, 100)
1218 _, err := f.Read(buf)
1219 f.Close()
1220 if err == nil || err == io.EOF {
1221 // go.mod exists and is readable (is a file, not a directory).
1222 break
1223 }
1224 }
1225 d := filepath.Dir(parent)
1226 if len(d) >= len(parent) {
1227 return errNoModules // reached top of file system, no go.mod
1228 }
1229 parent = d
1230 }
1231 }
1232
1233 goCmd := filepath.Join(ctxt.GOROOT, "bin", "go")
1234 cmd := exec.Command(goCmd, "list", "-e", "-compiler="+ctxt.Compiler, "-tags="+strings.Join(ctxt.BuildTags, ","), "-installsuffix="+ctxt.InstallSuffix, "-f={{.Dir}}\n{{.ImportPath}}\n{{.Root}}\n{{.Goroot}}\n{{if .Error}}{{.Error}}{{end}}\n", "--", path)
1235
1236 if ctxt.Dir != "" {
1237 cmd.Dir = ctxt.Dir
1238 }
1239
1240 var stdout, stderr strings.Builder
1241 cmd.Stdout = &stdout
1242 cmd.Stderr = &stderr
1243
1244 cgo := "0"
1245 if ctxt.CgoEnabled {
1246 cgo = "1"
1247 }
1248 cmd.Env = append(cmd.Environ(),
1249 "GOOS="+ctxt.GOOS,
1250 "GOARCH="+ctxt.GOARCH,
1251 "GOROOT="+ctxt.GOROOT,
1252 "GOPATH="+ctxt.GOPATH,
1253 "CGO_ENABLED="+cgo,
1254 )
1255
1256 if err := cmd.Run(); err != nil {
1257 return fmt.Errorf("go/build: go list %s: %v\n%s\n", path, err, stderr.String())
1258 }
1259
1260 f := strings.SplitN(stdout.String(), "\n", 5)
1261 if len(f) != 5 {
1262 return fmt.Errorf("go/build: importGo %s: unexpected output:\n%s\n", path, stdout.String())
1263 }
1264 dir := f[0]
1265 errStr := strings.TrimSpace(f[4])
1266 if errStr != "" && dir == "" {
1267 // If 'go list' could not locate the package (dir is empty),
1268 // return the same error that 'go list' reported.
1269 return errors.New(errStr)
1270 }
1271
1272 // If 'go list' did locate the package, ignore the error.
1273 // It was probably related to loading source files, and we'll
1274 // encounter it ourselves shortly if the FindOnly flag isn't set.
1275 p.Dir = dir
1276 p.ImportPath = f[1]
1277 p.Root = f[2]
1278 p.Goroot = f[3] == "true"
1279 return nil
1280 }
1281
1282 // hasGoFiles reports whether dir contains any files with names ending in .go.
1283 // For a vendor check we must exclude directories that contain no .go files.
1284 // Otherwise it is not possible to vendor just a/b/c and still import the
1285 // non-vendored a/b. See golang.org/issue/13832.
1286 func hasGoFiles(ctxt *Context, dir string) bool {
1287 ents, _ := ctxt.readDir(dir)
1288 for _, ent := range ents {
1289 if !ent.IsDir() && strings.HasSuffix(ent.Name(), ".go") {
1290 return true
1291 }
1292 }
1293 return false
1294 }
1295
1296 func findImportComment(data []byte) (s string, line int) {
1297 // expect keyword package
1298 word, data := parseWord(data)
1299 if string(word) != "package" {
1300 return "", 0
1301 }
1302
1303 // expect package name
1304 _, data = parseWord(data)
1305
1306 // now ready for import comment, a // or /* */ comment
1307 // beginning and ending on the current line.
1308 for len(data) > 0 && (data[0] == ' ' || data[0] == '\t' || data[0] == '\r') {
1309 data = data[1:]
1310 }
1311
1312 var comment []byte
1313 switch {
1314 case bytes.HasPrefix(data, slashSlash):
1315 comment, _, _ = bytes.Cut(data[2:], newline)
1316 case bytes.HasPrefix(data, slashStar):
1317 var ok bool
1318 comment, _, ok = bytes.Cut(data[2:], starSlash)
1319 if !ok {
1320 // malformed comment
1321 return "", 0
1322 }
1323 if bytes.Contains(comment, newline) {
1324 return "", 0
1325 }
1326 }
1327 comment = bytes.TrimSpace(comment)
1328
1329 // split comment into `import`, `"pkg"`
1330 word, arg := parseWord(comment)
1331 if string(word) != "import" {
1332 return "", 0
1333 }
1334
1335 line = 1 + bytes.Count(data[:cap(data)-cap(arg)], newline)
1336 return strings.TrimSpace(string(arg)), line
1337 }
1338
1339 var (
1340 slashSlash = []byte("//")
1341 slashStar = []byte("/*")
1342 starSlash = []byte("*/")
1343 newline = []byte("\n")
1344 )
1345
1346 // skipSpaceOrComment returns data with any leading spaces or comments removed.
1347 func skipSpaceOrComment(data []byte) []byte {
1348 for len(data) > 0 {
1349 switch data[0] {
1350 case ' ', '\t', '\r', '\n':
1351 data = data[1:]
1352 continue
1353 case '/':
1354 if bytes.HasPrefix(data, slashSlash) {
1355 i := bytes.Index(data, newline)
1356 if i < 0 {
1357 return nil
1358 }
1359 data = data[i+1:]
1360 continue
1361 }
1362 if bytes.HasPrefix(data, slashStar) {
1363 data = data[2:]
1364 i := bytes.Index(data, starSlash)
1365 if i < 0 {
1366 return nil
1367 }
1368 data = data[i+2:]
1369 continue
1370 }
1371 }
1372 break
1373 }
1374 return data
1375 }
1376
1377 // parseWord skips any leading spaces or comments in data
1378 // and then parses the beginning of data as an identifier or keyword,
1379 // returning that word and what remains after the word.
1380 func parseWord(data []byte) (word, rest []byte) {
1381 data = skipSpaceOrComment(data)
1382
1383 // Parse past leading word characters.
1384 rest = data
1385 for {
1386 r, size := utf8.DecodeRune(rest)
1387 if unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' {
1388 rest = rest[size:]
1389 continue
1390 }
1391 break
1392 }
1393
1394 word = data[:len(data)-len(rest)]
1395 if len(word) == 0 {
1396 return nil, nil
1397 }
1398
1399 return word, rest
1400 }
1401
1402 // MatchFile reports whether the file with the given name in the given directory
1403 // matches the context and would be included in a [Package] created by [ImportDir]
1404 // of that directory.
1405 //
1406 // MatchFile considers the name of the file and may use ctxt.OpenFile to
1407 // read some or all of the file's content.
1408 func (ctxt *Context) MatchFile(dir, name string) (match bool, err error) {
1409 info, err := ctxt.matchFile(dir, name, nil, nil, nil)
1410 return info != nil, err
1411 }
1412
1413 var dummyPkg Package
1414
1415 // fileInfo records information learned about a file included in a build.
1416 type fileInfo struct {
1417 name string // full name including dir
1418 header []byte
1419 fset *token.FileSet
1420 parsed *ast.File
1421 parseErr error
1422 imports []fileImport
1423 embeds []fileEmbed
1424 directives []Directive
1425 }
1426
1427 type fileImport struct {
1428 path string
1429 pos token.Pos
1430 doc *ast.CommentGroup
1431 }
1432
1433 type fileEmbed struct {
1434 pattern string
1435 pos token.Position
1436 }
1437
1438 // matchFile determines whether the file with the given name in the given directory
1439 // should be included in the package being constructed.
1440 // If the file should be included, matchFile returns a non-nil *fileInfo (and a nil error).
1441 // Non-nil errors are reserved for unexpected problems.
1442 //
1443 // If name denotes a Go program, matchFile reads until the end of the
1444 // imports and returns that section of the file in the fileInfo's header field,
1445 // even though it only considers text until the first non-comment
1446 // for go:build lines.
1447 //
1448 // If allTags is non-nil, matchFile records any encountered build tag
1449 // by setting allTags[tag] = true.
1450 func (ctxt *Context) matchFile(dir, name string, allTags map[string]bool, binaryOnly *bool, fset *token.FileSet) (*fileInfo, error) {
1451 if strings.HasPrefix(name, "_") ||
1452 strings.HasPrefix(name, ".") {
1453 return nil, nil
1454 }
1455
1456 i := strings.LastIndex(name, ".")
1457 if i < 0 {
1458 i = len(name)
1459 }
1460 ext := name[i:]
1461
1462 if ext != ".go" && fileListForExt(&dummyPkg, ext) == nil {
1463 // skip
1464 return nil, nil
1465 }
1466
1467 if !ctxt.goodOSArchFile(name, allTags) && !ctxt.UseAllFiles {
1468 return nil, nil
1469 }
1470
1471 info := &fileInfo{name: ctxt.joinPath(dir, name), fset: fset}
1472 if ext == ".syso" {
1473 // binary, no reading
1474 return info, nil
1475 }
1476
1477 f, err := ctxt.openFile(info.name)
1478 if err != nil {
1479 return nil, err
1480 }
1481
1482 if strings.HasSuffix(name, ".go") {
1483 err = readGoInfo(f, info)
1484 if strings.HasSuffix(name, "_test.go") {
1485 binaryOnly = nil // ignore //go:binary-only-package comments in _test.go files
1486 }
1487 } else {
1488 binaryOnly = nil // ignore //go:binary-only-package comments in non-Go sources
1489 info.header, err = readComments(f)
1490 }
1491 f.Close()
1492 if err != nil {
1493 return info, fmt.Errorf("read %s: %v", info.name, err)
1494 }
1495
1496 // Look for go:build comments to accept or reject the file.
1497 ok, sawBinaryOnly, err := ctxt.shouldBuild(info.header, allTags)
1498 if err != nil {
1499 return nil, fmt.Errorf("%s: %v", name, err)
1500 }
1501 if !ok && !ctxt.UseAllFiles {
1502 return nil, nil
1503 }
1504
1505 if binaryOnly != nil && sawBinaryOnly {
1506 *binaryOnly = true
1507 }
1508
1509 return info, nil
1510 }
1511
1512 func cleanDecls(m map[string][]token.Position) ([]string, map[string][]token.Position) {
1513 all := make([]string, 0, len(m))
1514 for path := range m {
1515 all = append(all, path)
1516 }
1517 slices.Sort(all)
1518 return all, m
1519 }
1520
1521 // Import is shorthand for Default.Import.
1522 func Import(path, srcDir string, mode ImportMode) (*Package, error) {
1523 return Default.Import(path, srcDir, mode)
1524 }
1525
1526 // ImportDir is shorthand for Default.ImportDir.
1527 func ImportDir(dir string, mode ImportMode) (*Package, error) {
1528 return Default.ImportDir(dir, mode)
1529 }
1530
1531 var (
1532 plusBuild = []byte("+build")
1533
1534 goBuildComment = []byte("//go:build")
1535
1536 errMultipleGoBuild = errors.New("multiple //go:build comments")
1537 )
1538
1539 func isGoBuildComment(line []byte) bool {
1540 if !bytes.HasPrefix(line, goBuildComment) {
1541 return false
1542 }
1543 line = bytes.TrimSpace(line)
1544 rest := line[len(goBuildComment):]
1545 return len(rest) == 0 || len(bytes.TrimSpace(rest)) < len(rest)
1546 }
1547
1548 // Special comment denoting a binary-only package.
1549 // See https://golang.org/design/2775-binary-only-packages
1550 // for more about the design of binary-only packages.
1551 var binaryOnlyComment = []byte("//go:binary-only-package")
1552
1553 // shouldBuild reports whether it is okay to use this file,
1554 // The rule is that in the file's leading run of // comments
1555 // and blank lines, which must be followed by a blank line
1556 // (to avoid including a Go package clause doc comment),
1557 // lines beginning with '//go:build' are taken as build directives.
1558 //
1559 // The file is accepted only if each such line lists something
1560 // matching the file. For example:
1561 //
1562 // //go:build windows linux
1563 //
1564 // marks the file as applicable only on Windows and Linux.
1565 //
1566 // For each build tag it consults, shouldBuild sets allTags[tag] = true.
1567 //
1568 // shouldBuild reports whether the file should be built
1569 // and whether a //go:binary-only-package comment was found.
1570 func (ctxt *Context) shouldBuild(content []byte, allTags map[string]bool) (shouldBuild, binaryOnly bool, err error) {
1571 // Identify leading run of // comments and blank lines,
1572 // which must be followed by a blank line.
1573 // Also identify any //go:build comments.
1574 content, goBuild, sawBinaryOnly, err := parseFileHeader(content)
1575 if err != nil {
1576 return false, false, err
1577 }
1578
1579 // If //go:build line is present, it controls.
1580 // Otherwise fall back to +build processing.
1581 switch {
1582 case goBuild != nil:
1583 x, err := constraint.Parse(string(goBuild))
1584 if err != nil {
1585 return false, false, fmt.Errorf("parsing //go:build line: %v", err)
1586 }
1587 shouldBuild = ctxt.eval(x, allTags)
1588
1589 default:
1590 shouldBuild = true
1591 p := content
1592 for len(p) > 0 {
1593 line := p
1594 if i := bytes.IndexByte(line, '\n'); i >= 0 {
1595 line, p = line[:i], p[i+1:]
1596 } else {
1597 p = p[len(p):]
1598 }
1599 line = bytes.TrimSpace(line)
1600 if !bytes.HasPrefix(line, slashSlash) || !bytes.Contains(line, plusBuild) {
1601 continue
1602 }
1603 text := string(line)
1604 if !constraint.IsPlusBuild(text) {
1605 continue
1606 }
1607 if x, err := constraint.Parse(text); err == nil {
1608 if !ctxt.eval(x, allTags) {
1609 shouldBuild = false
1610 }
1611 }
1612 }
1613 }
1614
1615 return shouldBuild, sawBinaryOnly, nil
1616 }
1617
1618 // parseFileHeader should be an internal detail,
1619 // but widely used packages access it using linkname.
1620 // Notable members of the hall of shame include:
1621 // - github.com/bazelbuild/bazel-gazelle
1622 //
1623 // Do not remove or change the type signature.
1624 // See go.dev/issue/67401.
1625 //
1626 //go:linkname parseFileHeader
1627 func parseFileHeader(content []byte) (trimmed, goBuild []byte, sawBinaryOnly bool, err error) {
1628 end := 0
1629 p := content
1630 ended := false // found non-blank, non-// line, so stopped accepting //go:build lines
1631 inSlashStar := false // in /* */ comment
1632
1633 Lines:
1634 for len(p) > 0 {
1635 line := p
1636 if i := bytes.IndexByte(line, '\n'); i >= 0 {
1637 line, p = line[:i], p[i+1:]
1638 } else {
1639 p = p[len(p):]
1640 }
1641 line = bytes.TrimSpace(line)
1642 if len(line) == 0 && !ended { // Blank line
1643 // Remember position of most recent blank line.
1644 // When we find the first non-blank, non-// line,
1645 // this "end" position marks the latest file position
1646 // where a //go:build line can appear.
1647 // (It must appear _before_ a blank line before the non-blank, non-// line.
1648 // Yes, that's confusing, which is part of why we moved to //go:build lines.)
1649 // Note that ended==false here means that inSlashStar==false,
1650 // since seeing a /* would have set ended==true.
1651 end = len(content) - len(p)
1652 continue Lines
1653 }
1654 if !bytes.HasPrefix(line, slashSlash) { // Not comment line
1655 ended = true
1656 }
1657
1658 if !inSlashStar && isGoBuildComment(line) {
1659 if goBuild != nil {
1660 return nil, nil, false, errMultipleGoBuild
1661 }
1662 goBuild = line
1663 }
1664 if !inSlashStar && bytes.Equal(line, binaryOnlyComment) {
1665 sawBinaryOnly = true
1666 }
1667
1668 Comments:
1669 for len(line) > 0 {
1670 if inSlashStar {
1671 if i := bytes.Index(line, starSlash); i >= 0 {
1672 inSlashStar = false
1673 line = bytes.TrimSpace(line[i+len(starSlash):])
1674 continue Comments
1675 }
1676 continue Lines
1677 }
1678 if bytes.HasPrefix(line, slashSlash) {
1679 continue Lines
1680 }
1681 if bytes.HasPrefix(line, slashStar) {
1682 inSlashStar = true
1683 line = bytes.TrimSpace(line[len(slashStar):])
1684 continue Comments
1685 }
1686 // Found non-comment text.
1687 break Lines
1688 }
1689 }
1690
1691 return content[:end], goBuild, sawBinaryOnly, nil
1692 }
1693
1694 // saveCgo saves the information from the #cgo lines in the import "C" comment.
1695 // These lines set CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS and pkg-config directives
1696 // that affect the way cgo's C code is built.
1697 func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error {
1698 text := cg.Text()
1699 for line := range strings.SplitSeq(text, "\n") {
1700 orig := line
1701
1702 // Line is
1703 // #cgo [GOOS/GOARCH...] LDFLAGS: stuff
1704 //
1705 line = strings.TrimSpace(line)
1706 if len(line) < 5 || line[:4] != "#cgo" || (line[4] != ' ' && line[4] != '\t') {
1707 continue
1708 }
1709
1710 // #cgo (nocallback|noescape) <function name>
1711 if fields := strings.Fields(line); len(fields) == 3 && (fields[1] == "nocallback" || fields[1] == "noescape") {
1712 continue
1713 }
1714
1715 // Split at colon.
1716 line, argstr, ok := strings.Cut(strings.TrimSpace(line[4:]), ":")
1717 if !ok {
1718 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1719 }
1720
1721 // Parse GOOS/GOARCH stuff.
1722 f := strings.Fields(line)
1723 if len(f) < 1 {
1724 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1725 }
1726
1727 cond, verb := f[:len(f)-1], f[len(f)-1]
1728 if len(cond) > 0 {
1729 ok := false
1730 for _, c := range cond {
1731 if ctxt.matchAuto(c, nil) {
1732 ok = true
1733 break
1734 }
1735 }
1736 if !ok {
1737 continue
1738 }
1739 }
1740
1741 args, err := splitQuoted(argstr)
1742 if err != nil {
1743 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1744 }
1745 for i, arg := range args {
1746 if arg, ok = expandSrcDir(arg, di.Dir); !ok {
1747 return fmt.Errorf("%s: malformed #cgo argument: %s", filename, arg)
1748 }
1749 args[i] = arg
1750 }
1751
1752 switch verb {
1753 case "CFLAGS", "CPPFLAGS", "CXXFLAGS", "FFLAGS", "LDFLAGS":
1754 // Change relative paths to absolute.
1755 ctxt.makePathsAbsolute(args, di.Dir)
1756 }
1757
1758 switch verb {
1759 case "CFLAGS":
1760 di.CgoCFLAGS = append(di.CgoCFLAGS, args...)
1761 case "CPPFLAGS":
1762 di.CgoCPPFLAGS = append(di.CgoCPPFLAGS, args...)
1763 case "CXXFLAGS":
1764 di.CgoCXXFLAGS = append(di.CgoCXXFLAGS, args...)
1765 case "FFLAGS":
1766 di.CgoFFLAGS = append(di.CgoFFLAGS, args...)
1767 case "LDFLAGS":
1768 di.CgoLDFLAGS = append(di.CgoLDFLAGS, args...)
1769 case "pkg-config":
1770 di.CgoPkgConfig = append(di.CgoPkgConfig, args...)
1771 default:
1772 return fmt.Errorf("%s: invalid #cgo verb: %s", filename, orig)
1773 }
1774 }
1775 return nil
1776 }
1777
1778 // expandSrcDir expands any occurrence of ${SRCDIR}, making sure
1779 // the result is safe for the shell.
1780 func expandSrcDir(str string, srcdir string) (string, bool) {
1781 // "\" delimited paths cause safeCgoName to fail
1782 // so convert native paths with a different delimiter
1783 // to "/" before starting (eg: on windows).
1784 srcdir = filepath.ToSlash(srcdir)
1785
1786 chunks := strings.Split(str, "${SRCDIR}")
1787 if len(chunks) < 2 {
1788 return str, safeCgoName(str)
1789 }
1790 ok := true
1791 for _, chunk := range chunks {
1792 ok = ok && (chunk == "" || safeCgoName(chunk))
1793 }
1794 ok = ok && (srcdir == "" || safeCgoName(srcdir))
1795 res := strings.Join(chunks, srcdir)
1796 return res, ok && res != ""
1797 }
1798
1799 // makePathsAbsolute looks for compiler options that take paths and
1800 // makes them absolute. We do this because through the 1.8 release we
1801 // ran the compiler in the package directory, so any relative -I or -L
1802 // options would be relative to that directory. In 1.9 we changed to
1803 // running the compiler in the build directory, to get consistent
1804 // build results (issue #19964). To keep builds working, we change any
1805 // relative -I or -L options to be absolute.
1806 //
1807 // Using filepath.IsAbs and filepath.Join here means the results will be
1808 // different on different systems, but that's OK: -I and -L options are
1809 // inherently system-dependent.
1810 func (ctxt *Context) makePathsAbsolute(args []string, srcDir string) {
1811 nextPath := false
1812 for i, arg := range args {
1813 if nextPath {
1814 if !filepath.IsAbs(arg) {
1815 args[i] = filepath.Join(srcDir, arg)
1816 }
1817 nextPath = false
1818 } else if strings.HasPrefix(arg, "-I") || strings.HasPrefix(arg, "-L") {
1819 if len(arg) == 2 {
1820 nextPath = true
1821 } else {
1822 if !filepath.IsAbs(arg[2:]) {
1823 args[i] = arg[:2] + filepath.Join(srcDir, arg[2:])
1824 }
1825 }
1826 }
1827 }
1828 }
1829
1830 // NOTE: $ is not safe for the shell, but it is allowed here because of linker options like -Wl,$ORIGIN.
1831 // We never pass these arguments to a shell (just to programs we construct argv for), so this should be okay.
1832 // See golang.org/issue/6038.
1833 // The @ is for OS X. See golang.org/issue/13720.
1834 // The % is for Jenkins. See golang.org/issue/16959.
1835 // The ! is because module paths may use them. See golang.org/issue/26716.
1836 // The ~ and ^ are for sr.ht. See golang.org/issue/32260.
1837 const safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$@%! ~^"
1838
1839 func safeCgoName(s string) bool {
1840 if s == "" {
1841 return false
1842 }
1843 for i := 0; i < len(s); i++ {
1844 if c := s[i]; c < utf8.RuneSelf && strings.IndexByte(safeString, c) < 0 {
1845 return false
1846 }
1847 }
1848 return true
1849 }
1850
1851 // splitQuoted splits the string s around each instance of one or more consecutive
1852 // white space characters while taking into account quotes and escaping, and
1853 // returns an array of substrings of s or an empty list if s contains only white space.
1854 // Single quotes and double quotes are recognized to prevent splitting within the
1855 // quoted region, and are removed from the resulting substrings. If a quote in s
1856 // isn't closed err will be set and r will have the unclosed argument as the
1857 // last element. The backslash is used for escaping.
1858 //
1859 // For example, the following string:
1860 //
1861 // a b:"c d" 'e''f' "g\""
1862 //
1863 // Would be parsed as:
1864 //
1865 // []string{"a", "b:c d", "ef", `g"`}
1866 func splitQuoted(s string) (r []string, err error) {
1867 var args []string
1868 arg := make([]rune, len(s))
1869 escaped := false
1870 quoted := false
1871 quote := '\x00'
1872 i := 0
1873 for _, rune := range s {
1874 switch {
1875 case escaped:
1876 escaped = false
1877 case rune == '\\':
1878 escaped = true
1879 continue
1880 case quote != '\x00':
1881 if rune == quote {
1882 quote = '\x00'
1883 continue
1884 }
1885 case rune == '"' || rune == '\'':
1886 quoted = true
1887 quote = rune
1888 continue
1889 case unicode.IsSpace(rune):
1890 if quoted || i > 0 {
1891 quoted = false
1892 args = append(args, string(arg[:i]))
1893 i = 0
1894 }
1895 continue
1896 }
1897 arg[i] = rune
1898 i++
1899 }
1900 if quoted || i > 0 {
1901 args = append(args, string(arg[:i]))
1902 }
1903 if quote != 0 {
1904 err = errors.New("unclosed quote")
1905 } else if escaped {
1906 err = errors.New("unfinished escaping")
1907 }
1908 return args, err
1909 }
1910
1911 // matchAuto interprets text as either a +build or //go:build expression (whichever works),
1912 // reporting whether the expression matches the build context.
1913 //
1914 // matchAuto is only used for testing of tag evaluation
1915 // and in #cgo lines, which accept either syntax.
1916 func (ctxt *Context) matchAuto(text string, allTags map[string]bool) bool {
1917 if strings.ContainsAny(text, "&|()") {
1918 text = "//go:build " + text
1919 } else {
1920 text = "// +build " + text
1921 }
1922 x, err := constraint.Parse(text)
1923 if err != nil {
1924 return false
1925 }
1926 return ctxt.eval(x, allTags)
1927 }
1928
1929 func (ctxt *Context) eval(x constraint.Expr, allTags map[string]bool) bool {
1930 return x.Eval(func(tag string) bool { return ctxt.matchTag(tag, allTags) })
1931 }
1932
1933 // matchTag reports whether the name is one of:
1934 //
1935 // cgo (if cgo is enabled)
1936 // $GOOS
1937 // $GOARCH
1938 // ctxt.Compiler
1939 // linux (if GOOS = android)
1940 // solaris (if GOOS = illumos)
1941 // darwin (if GOOS = ios)
1942 // unix (if this is a Unix GOOS)
1943 // boringcrypto (if GOEXPERIMENT=boringcrypto is enabled)
1944 // tag (if tag is listed in ctxt.BuildTags, ctxt.ToolTags, or ctxt.ReleaseTags)
1945 //
1946 // It records all consulted tags in allTags.
1947 func (ctxt *Context) matchTag(name string, allTags map[string]bool) bool {
1948 if allTags != nil {
1949 allTags[name] = true
1950 }
1951
1952 // special tags
1953 if ctxt.CgoEnabled && name == "cgo" {
1954 return true
1955 }
1956 if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler {
1957 return true
1958 }
1959 if ctxt.GOOS == "android" && name == "linux" {
1960 return true
1961 }
1962 if ctxt.GOOS == "illumos" && name == "solaris" {
1963 return true
1964 }
1965 if ctxt.GOOS == "ios" && name == "darwin" {
1966 return true
1967 }
1968 if name == "unix" && syslist.UnixOS[ctxt.GOOS] {
1969 return true
1970 }
1971 if name == "boringcrypto" {
1972 name = "goexperiment.boringcrypto" // boringcrypto is an old name for goexperiment.boringcrypto
1973 }
1974
1975 // other tags
1976 return slices.Contains(ctxt.BuildTags, name) || slices.Contains(ctxt.ToolTags, name) ||
1977 slices.Contains(ctxt.ReleaseTags, name)
1978 }
1979
1980 // goodOSArchFile returns false if the name contains a $GOOS or $GOARCH
1981 // suffix which does not match the current system.
1982 // The recognized name formats are:
1983 //
1984 // name_$(GOOS).*
1985 // name_$(GOARCH).*
1986 // name_$(GOOS)_$(GOARCH).*
1987 // name_$(GOOS)_test.*
1988 // name_$(GOARCH)_test.*
1989 // name_$(GOOS)_$(GOARCH)_test.*
1990 //
1991 // Exceptions:
1992 // if GOOS=android, then files with GOOS=linux are also matched.
1993 // if GOOS=illumos, then files with GOOS=solaris are also matched.
1994 // if GOOS=ios, then files with GOOS=darwin are also matched.
1995 func (ctxt *Context) goodOSArchFile(name string, allTags map[string]bool) bool {
1996 name, _, _ = strings.Cut(name, ".")
1997
1998 // Before Go 1.4, a file called "linux.go" would be equivalent to having a
1999 // build tag "linux" in that file. For Go 1.4 and beyond, we require this
2000 // auto-tagging to apply only to files with a non-empty prefix, so
2001 // "foo_linux.go" is tagged but "linux.go" is not. This allows new operating
2002 // systems, such as android, to arrive without breaking existing code with
2003 // innocuous source code in "android.go". The easiest fix: cut everything
2004 // in the name before the initial _.
2005 i := strings.Index(name, "_")
2006 if i < 0 {
2007 return true
2008 }
2009 name = name[i:] // ignore everything before first _
2010
2011 l := strings.Split(name, "_")
2012 if n := len(l); n > 0 && l[n-1] == "test" {
2013 l = l[:n-1]
2014 }
2015 n := len(l)
2016 if n >= 2 && syslist.KnownOS[l[n-2]] && syslist.KnownArch[l[n-1]] {
2017 if allTags != nil {
2018 // In case we short-circuit on l[n-1].
2019 allTags[l[n-2]] = true
2020 }
2021 return ctxt.matchTag(l[n-1], allTags) && ctxt.matchTag(l[n-2], allTags)
2022 }
2023 if n >= 1 && (syslist.KnownOS[l[n-1]] || syslist.KnownArch[l[n-1]]) {
2024 return ctxt.matchTag(l[n-1], allTags)
2025 }
2026 return true
2027 }
2028
2029 // ToolDir is the directory containing build tools.
2030 var ToolDir = getToolDir()
2031
2032 // IsLocalImport reports whether the import path is
2033 // a local import path, like ".", "..", "./foo", or "../foo".
2034 func IsLocalImport(path string) bool {
2035 return path == "." || path == ".." ||
2036 strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../")
2037 }
2038
2039 // ArchChar returns "?" and an error.
2040 // In earlier versions of Go, the returned string was used to derive
2041 // the compiler and linker tool names, the default object file suffix,
2042 // and the default linker output name. As of Go 1.5, those strings
2043 // no longer vary by architecture; they are compile, link, .o, and a.out, respectively.
2044 func ArchChar(goarch string) (string, error) {
2045 return "?", errors.New("architecture letter no longer used")
2046 }