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