]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/build/build.go
all: REVERSE MERGE dev.boringcrypto (cdcb4b6) into master
[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         "internal/goroot"
17         "internal/goversion"
18         "io"
19         "io/fs"
20         "io/ioutil"
21         "os"
22         "os/exec"
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 func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error) {
538         p := &Package{
539                 ImportPath: path,
540         }
541         if path == "" {
542                 return p, fmt.Errorf("import %q: invalid import path", path)
543         }
544
545         var pkgtargetroot string
546         var pkga string
547         var pkgerr error
548         suffix := ""
549         if ctxt.InstallSuffix != "" {
550                 suffix = "_" + ctxt.InstallSuffix
551         }
552         switch ctxt.Compiler {
553         case "gccgo":
554                 pkgtargetroot = "pkg/gccgo_" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
555         case "gc":
556                 pkgtargetroot = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
557         default:
558                 // Save error for end of function.
559                 pkgerr = fmt.Errorf("import %q: unknown compiler %q", path, ctxt.Compiler)
560         }
561         setPkga := func() {
562                 switch ctxt.Compiler {
563                 case "gccgo":
564                         dir, elem := pathpkg.Split(p.ImportPath)
565                         pkga = pkgtargetroot + "/" + dir + "lib" + elem + ".a"
566                 case "gc":
567                         pkga = pkgtargetroot + "/" + p.ImportPath + ".a"
568                 }
569         }
570         setPkga()
571
572         binaryOnly := false
573         if IsLocalImport(path) {
574                 pkga = "" // local imports have no installed path
575                 if srcDir == "" {
576                         return p, fmt.Errorf("import %q: import relative to unknown directory", path)
577                 }
578                 if !ctxt.isAbsPath(path) {
579                         p.Dir = ctxt.joinPath(srcDir, path)
580                 }
581                 // p.Dir directory may or may not exist. Gather partial information first, check if it exists later.
582                 // Determine canonical import path, if any.
583                 // Exclude results where the import path would include /testdata/.
584                 inTestdata := func(sub string) bool {
585                         return strings.Contains(sub, "/testdata/") || strings.HasSuffix(sub, "/testdata") || strings.HasPrefix(sub, "testdata/") || sub == "testdata"
586                 }
587                 if ctxt.GOROOT != "" {
588                         root := ctxt.joinPath(ctxt.GOROOT, "src")
589                         if sub, ok := ctxt.hasSubdir(root, p.Dir); ok && !inTestdata(sub) {
590                                 p.Goroot = true
591                                 p.ImportPath = sub
592                                 p.Root = ctxt.GOROOT
593                                 setPkga() // p.ImportPath changed
594                                 goto Found
595                         }
596                 }
597                 all := ctxt.gopath()
598                 for i, root := range all {
599                         rootsrc := ctxt.joinPath(root, "src")
600                         if sub, ok := ctxt.hasSubdir(rootsrc, p.Dir); ok && !inTestdata(sub) {
601                                 // We found a potential import path for dir,
602                                 // but check that using it wouldn't find something
603                                 // else first.
604                                 if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
605                                         if dir := ctxt.joinPath(ctxt.GOROOT, "src", sub); ctxt.isDir(dir) {
606                                                 p.ConflictDir = dir
607                                                 goto Found
608                                         }
609                                 }
610                                 for _, earlyRoot := range all[:i] {
611                                         if dir := ctxt.joinPath(earlyRoot, "src", sub); ctxt.isDir(dir) {
612                                                 p.ConflictDir = dir
613                                                 goto Found
614                                         }
615                                 }
616
617                                 // sub would not name some other directory instead of this one.
618                                 // Record it.
619                                 p.ImportPath = sub
620                                 p.Root = root
621                                 setPkga() // p.ImportPath changed
622                                 goto Found
623                         }
624                 }
625                 // It's okay that we didn't find a root containing dir.
626                 // Keep going with the information we have.
627         } else {
628                 if strings.HasPrefix(path, "/") {
629                         return p, fmt.Errorf("import %q: cannot import absolute path", path)
630                 }
631
632                 if err := ctxt.importGo(p, path, srcDir, mode); err == nil {
633                         goto Found
634                 } else if err != errNoModules {
635                         return p, err
636                 }
637
638                 gopath := ctxt.gopath() // needed twice below; avoid computing many times
639
640                 // tried records the location of unsuccessful package lookups
641                 var tried struct {
642                         vendor []string
643                         goroot string
644                         gopath []string
645                 }
646
647                 // Vendor directories get first chance to satisfy import.
648                 if mode&IgnoreVendor == 0 && srcDir != "" {
649                         searchVendor := func(root string, isGoroot bool) bool {
650                                 sub, ok := ctxt.hasSubdir(root, srcDir)
651                                 if !ok || !strings.HasPrefix(sub, "src/") || strings.Contains(sub, "/testdata/") {
652                                         return false
653                                 }
654                                 for {
655                                         vendor := ctxt.joinPath(root, sub, "vendor")
656                                         if ctxt.isDir(vendor) {
657                                                 dir := ctxt.joinPath(vendor, path)
658                                                 if ctxt.isDir(dir) && hasGoFiles(ctxt, dir) {
659                                                         p.Dir = dir
660                                                         p.ImportPath = strings.TrimPrefix(pathpkg.Join(sub, "vendor", path), "src/")
661                                                         p.Goroot = isGoroot
662                                                         p.Root = root
663                                                         setPkga() // p.ImportPath changed
664                                                         return true
665                                                 }
666                                                 tried.vendor = append(tried.vendor, dir)
667                                         }
668                                         i := strings.LastIndex(sub, "/")
669                                         if i < 0 {
670                                                 break
671                                         }
672                                         sub = sub[:i]
673                                 }
674                                 return false
675                         }
676                         if ctxt.Compiler != "gccgo" && ctxt.GOROOT != "" && searchVendor(ctxt.GOROOT, true) {
677                                 goto Found
678                         }
679                         for _, root := range gopath {
680                                 if searchVendor(root, false) {
681                                         goto Found
682                                 }
683                         }
684                 }
685
686                 // Determine directory from import path.
687                 if ctxt.GOROOT != "" {
688                         // If the package path starts with "vendor/", only search GOROOT before
689                         // GOPATH if the importer is also within GOROOT. That way, if the user has
690                         // vendored in a package that is subsequently included in the standard
691                         // distribution, they'll continue to pick up their own vendored copy.
692                         gorootFirst := srcDir == "" || !strings.HasPrefix(path, "vendor/")
693                         if !gorootFirst {
694                                 _, gorootFirst = ctxt.hasSubdir(ctxt.GOROOT, srcDir)
695                         }
696                         if gorootFirst {
697                                 dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
698                                 if ctxt.Compiler != "gccgo" {
699                                         isDir := ctxt.isDir(dir)
700                                         binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
701                                         if isDir || binaryOnly {
702                                                 p.Dir = dir
703                                                 p.Goroot = true
704                                                 p.Root = ctxt.GOROOT
705                                                 goto Found
706                                         }
707                                 }
708                                 tried.goroot = dir
709                         }
710                         if ctxt.Compiler == "gccgo" && goroot.IsStandardPackage(ctxt.GOROOT, ctxt.Compiler, path) {
711                                 p.Dir = ctxt.joinPath(ctxt.GOROOT, "src", path)
712                                 p.Goroot = true
713                                 p.Root = ctxt.GOROOT
714                                 goto Found
715                         }
716                 }
717                 for _, root := range gopath {
718                         dir := ctxt.joinPath(root, "src", path)
719                         isDir := ctxt.isDir(dir)
720                         binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(root, pkga))
721                         if isDir || binaryOnly {
722                                 p.Dir = dir
723                                 p.Root = root
724                                 goto Found
725                         }
726                         tried.gopath = append(tried.gopath, dir)
727                 }
728
729                 // If we tried GOPATH first due to a "vendor/" prefix, fall back to GOPATH.
730                 // That way, the user can still get useful results from 'go list' for
731                 // standard-vendored paths passed on the command line.
732                 if ctxt.GOROOT != "" && tried.goroot == "" {
733                         dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
734                         if ctxt.Compiler != "gccgo" {
735                                 isDir := ctxt.isDir(dir)
736                                 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
737                                 if isDir || binaryOnly {
738                                         p.Dir = dir
739                                         p.Goroot = true
740                                         p.Root = ctxt.GOROOT
741                                         goto Found
742                                 }
743                         }
744                         tried.goroot = dir
745                 }
746
747                 // package was not found
748                 var paths []string
749                 format := "\t%s (vendor tree)"
750                 for _, dir := range tried.vendor {
751                         paths = append(paths, fmt.Sprintf(format, dir))
752                         format = "\t%s"
753                 }
754                 if tried.goroot != "" {
755                         paths = append(paths, fmt.Sprintf("\t%s (from $GOROOT)", tried.goroot))
756                 } else {
757                         paths = append(paths, "\t($GOROOT not set)")
758                 }
759                 format = "\t%s (from $GOPATH)"
760                 for _, dir := range tried.gopath {
761                         paths = append(paths, fmt.Sprintf(format, dir))
762                         format = "\t%s"
763                 }
764                 if len(tried.gopath) == 0 {
765                         paths = append(paths, "\t($GOPATH not set. For more details see: 'go help gopath')")
766                 }
767                 return p, fmt.Errorf("cannot find package %q in any of:\n%s", path, strings.Join(paths, "\n"))
768         }
769
770 Found:
771         if p.Root != "" {
772                 p.SrcRoot = ctxt.joinPath(p.Root, "src")
773                 p.PkgRoot = ctxt.joinPath(p.Root, "pkg")
774                 p.BinDir = ctxt.joinPath(p.Root, "bin")
775                 if pkga != "" {
776                         p.PkgTargetRoot = ctxt.joinPath(p.Root, pkgtargetroot)
777                         p.PkgObj = ctxt.joinPath(p.Root, pkga)
778                 }
779         }
780
781         // If it's a local import path, by the time we get here, we still haven't checked
782         // that p.Dir directory exists. This is the right time to do that check.
783         // We can't do it earlier, because we want to gather partial information for the
784         // non-nil *Package returned when an error occurs.
785         // We need to do this before we return early on FindOnly flag.
786         if IsLocalImport(path) && !ctxt.isDir(p.Dir) {
787                 if ctxt.Compiler == "gccgo" && p.Goroot {
788                         // gccgo has no sources for GOROOT packages.
789                         return p, nil
790                 }
791
792                 // package was not found
793                 return p, fmt.Errorf("cannot find package %q in:\n\t%s", p.ImportPath, p.Dir)
794         }
795
796         if mode&FindOnly != 0 {
797                 return p, pkgerr
798         }
799         if binaryOnly && (mode&AllowBinary) != 0 {
800                 return p, pkgerr
801         }
802
803         if ctxt.Compiler == "gccgo" && p.Goroot {
804                 // gccgo has no sources for GOROOT packages.
805                 return p, nil
806         }
807
808         dirs, err := ctxt.readDir(p.Dir)
809         if err != nil {
810                 return p, err
811         }
812
813         var badGoError error
814         badFiles := make(map[string]bool)
815         badFile := func(name string, err error) {
816                 if badGoError == nil {
817                         badGoError = err
818                 }
819                 if !badFiles[name] {
820                         p.InvalidGoFiles = append(p.InvalidGoFiles, name)
821                         badFiles[name] = true
822                 }
823         }
824
825         var Sfiles []string // files with ".S"(capital S)/.sx(capital s equivalent for case insensitive filesystems)
826         var firstFile, firstCommentFile string
827         embedPos := make(map[string][]token.Position)
828         testEmbedPos := make(map[string][]token.Position)
829         xTestEmbedPos := make(map[string][]token.Position)
830         importPos := make(map[string][]token.Position)
831         testImportPos := make(map[string][]token.Position)
832         xTestImportPos := make(map[string][]token.Position)
833         allTags := make(map[string]bool)
834         fset := token.NewFileSet()
835         for _, d := range dirs {
836                 if d.IsDir() {
837                         continue
838                 }
839                 if d.Mode()&fs.ModeSymlink != 0 {
840                         if ctxt.isDir(ctxt.joinPath(p.Dir, d.Name())) {
841                                 // Symlinks to directories are not source files.
842                                 continue
843                         }
844                 }
845
846                 name := d.Name()
847                 ext := nameExt(name)
848
849                 info, err := ctxt.matchFile(p.Dir, name, allTags, &p.BinaryOnly, fset)
850                 if err != nil {
851                         badFile(name, err)
852                         continue
853                 }
854                 if info == nil {
855                         if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
856                                 // not due to build constraints - don't report
857                         } else if ext == ".go" {
858                                 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
859                         } else if fileListForExt(p, ext) != nil {
860                                 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, name)
861                         }
862                         continue
863                 }
864                 data, filename := info.header, info.name
865
866                 // Going to save the file. For non-Go files, can stop here.
867                 switch ext {
868                 case ".go":
869                         // keep going
870                 case ".S", ".sx":
871                         // special case for cgo, handled at end
872                         Sfiles = append(Sfiles, name)
873                         continue
874                 default:
875                         if list := fileListForExt(p, ext); list != nil {
876                                 *list = append(*list, name)
877                         }
878                         continue
879                 }
880
881                 if info.parseErr != nil {
882                         badFile(name, info.parseErr)
883                         // Fall through: we might still have a partial AST in info.parsed,
884                         // and we want to list files with parse errors anyway.
885                 }
886
887                 var pkg string
888                 if info.parsed != nil {
889                         pkg = info.parsed.Name.Name
890                         if pkg == "documentation" {
891                                 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
892                                 continue
893                         }
894                 }
895
896                 isTest := strings.HasSuffix(name, "_test.go")
897                 isXTest := false
898                 if isTest && strings.HasSuffix(pkg, "_test") && p.Name != pkg {
899                         isXTest = true
900                         pkg = pkg[:len(pkg)-len("_test")]
901                 }
902
903                 if p.Name == "" {
904                         p.Name = pkg
905                         firstFile = name
906                 } else if pkg != p.Name {
907                         // TODO(#45999): The choice of p.Name is arbitrary based on file iteration
908                         // order. Instead of resolving p.Name arbitrarily, we should clear out the
909                         // existing name and mark the existing files as also invalid.
910                         badFile(name, &MultiplePackageError{
911                                 Dir:      p.Dir,
912                                 Packages: []string{p.Name, pkg},
913                                 Files:    []string{firstFile, name},
914                         })
915                 }
916                 // Grab the first package comment as docs, provided it is not from a test file.
917                 if info.parsed != nil && info.parsed.Doc != nil && p.Doc == "" && !isTest && !isXTest {
918                         p.Doc = doc.Synopsis(info.parsed.Doc.Text())
919                 }
920
921                 if mode&ImportComment != 0 {
922                         qcom, line := findImportComment(data)
923                         if line != 0 {
924                                 com, err := strconv.Unquote(qcom)
925                                 if err != nil {
926                                         badFile(name, fmt.Errorf("%s:%d: cannot parse import comment", filename, line))
927                                 } else if p.ImportComment == "" {
928                                         p.ImportComment = com
929                                         firstCommentFile = name
930                                 } else if p.ImportComment != com {
931                                         badFile(name, fmt.Errorf("found import comments %q (%s) and %q (%s) in %s", p.ImportComment, firstCommentFile, com, name, p.Dir))
932                                 }
933                         }
934                 }
935
936                 // Record imports and information about cgo.
937                 isCgo := false
938                 for _, imp := range info.imports {
939                         if imp.path == "C" {
940                                 if isTest {
941                                         badFile(name, fmt.Errorf("use of cgo in test %s not supported", filename))
942                                         continue
943                                 }
944                                 isCgo = true
945                                 if imp.doc != nil {
946                                         if err := ctxt.saveCgo(filename, p, imp.doc); err != nil {
947                                                 badFile(name, err)
948                                         }
949                                 }
950                         }
951                 }
952
953                 var fileList *[]string
954                 var importMap, embedMap map[string][]token.Position
955                 switch {
956                 case isCgo:
957                         allTags["cgo"] = true
958                         if ctxt.CgoEnabled {
959                                 fileList = &p.CgoFiles
960                                 importMap = importPos
961                                 embedMap = embedPos
962                         } else {
963                                 // Ignore imports and embeds from cgo files if cgo is disabled.
964                                 fileList = &p.IgnoredGoFiles
965                         }
966                 case isXTest:
967                         fileList = &p.XTestGoFiles
968                         importMap = xTestImportPos
969                         embedMap = xTestEmbedPos
970                 case isTest:
971                         fileList = &p.TestGoFiles
972                         importMap = testImportPos
973                         embedMap = testEmbedPos
974                 default:
975                         fileList = &p.GoFiles
976                         importMap = importPos
977                         embedMap = embedPos
978                 }
979                 *fileList = append(*fileList, name)
980                 if importMap != nil {
981                         for _, imp := range info.imports {
982                                 importMap[imp.path] = append(importMap[imp.path], fset.Position(imp.pos))
983                         }
984                 }
985                 if embedMap != nil {
986                         for _, emb := range info.embeds {
987                                 embedMap[emb.pattern] = append(embedMap[emb.pattern], emb.pos)
988                         }
989                 }
990         }
991
992         for tag := range allTags {
993                 p.AllTags = append(p.AllTags, tag)
994         }
995         sort.Strings(p.AllTags)
996
997         p.EmbedPatterns, p.EmbedPatternPos = cleanDecls(embedPos)
998         p.TestEmbedPatterns, p.TestEmbedPatternPos = cleanDecls(testEmbedPos)
999         p.XTestEmbedPatterns, p.XTestEmbedPatternPos = cleanDecls(xTestEmbedPos)
1000
1001         p.Imports, p.ImportPos = cleanDecls(importPos)
1002         p.TestImports, p.TestImportPos = cleanDecls(testImportPos)
1003         p.XTestImports, p.XTestImportPos = cleanDecls(xTestImportPos)
1004
1005         // add the .S/.sx files only if we are using cgo
1006         // (which means gcc will compile them).
1007         // The standard assemblers expect .s files.
1008         if len(p.CgoFiles) > 0 {
1009                 p.SFiles = append(p.SFiles, Sfiles...)
1010                 sort.Strings(p.SFiles)
1011         } else {
1012                 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, Sfiles...)
1013                 sort.Strings(p.IgnoredOtherFiles)
1014         }
1015
1016         if badGoError != nil {
1017                 return p, badGoError
1018         }
1019         if len(p.GoFiles)+len(p.CgoFiles)+len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
1020                 return p, &NoGoError{p.Dir}
1021         }
1022         return p, pkgerr
1023 }
1024
1025 func fileListForExt(p *Package, ext string) *[]string {
1026         switch ext {
1027         case ".c":
1028                 return &p.CFiles
1029         case ".cc", ".cpp", ".cxx":
1030                 return &p.CXXFiles
1031         case ".m":
1032                 return &p.MFiles
1033         case ".h", ".hh", ".hpp", ".hxx":
1034                 return &p.HFiles
1035         case ".f", ".F", ".for", ".f90":
1036                 return &p.FFiles
1037         case ".s", ".S", ".sx":
1038                 return &p.SFiles
1039         case ".swig":
1040                 return &p.SwigFiles
1041         case ".swigcxx":
1042                 return &p.SwigCXXFiles
1043         case ".syso":
1044                 return &p.SysoFiles
1045         }
1046         return nil
1047 }
1048
1049 func uniq(list []string) []string {
1050         if list == nil {
1051                 return nil
1052         }
1053         out := make([]string, len(list))
1054         copy(out, list)
1055         sort.Strings(out)
1056         uniq := out[:0]
1057         for _, x := range out {
1058                 if len(uniq) == 0 || uniq[len(uniq)-1] != x {
1059                         uniq = append(uniq, x)
1060                 }
1061         }
1062         return uniq
1063 }
1064
1065 var errNoModules = errors.New("not using modules")
1066
1067 // importGo checks whether it can use the go command to find the directory for path.
1068 // If using the go command is not appropriate, importGo returns errNoModules.
1069 // Otherwise, importGo tries using the go command and reports whether that succeeded.
1070 // Using the go command lets build.Import and build.Context.Import find code
1071 // in Go modules. In the long term we want tools to use go/packages (currently golang.org/x/tools/go/packages),
1072 // which will also use the go command.
1073 // Invoking the go command here is not very efficient in that it computes information
1074 // about the requested package and all dependencies and then only reports about the requested package.
1075 // Then we reinvoke it for every dependency. But this is still better than not working at all.
1076 // See golang.org/issue/26504.
1077 func (ctxt *Context) importGo(p *Package, path, srcDir string, mode ImportMode) error {
1078         // To invoke the go command,
1079         // we must not being doing special things like AllowBinary or IgnoreVendor,
1080         // and all the file system callbacks must be nil (we're meant to use the local file system).
1081         if mode&AllowBinary != 0 || mode&IgnoreVendor != 0 ||
1082                 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) {
1083                 return errNoModules
1084         }
1085
1086         // If ctxt.GOROOT is not set, we don't know which go command to invoke,
1087         // and even if we did we might return packages in GOROOT that we wouldn't otherwise find
1088         // (because we don't know to search in 'go env GOROOT' otherwise).
1089         if ctxt.GOROOT == "" {
1090                 return errNoModules
1091         }
1092
1093         // Predict whether module aware mode is enabled by checking the value of
1094         // GO111MODULE and looking for a go.mod file in the source directory or
1095         // one of its parents. Running 'go env GOMOD' in the source directory would
1096         // give a canonical answer, but we'd prefer not to execute another command.
1097         go111Module := os.Getenv("GO111MODULE")
1098         switch go111Module {
1099         case "off":
1100                 return errNoModules
1101         default: // "", "on", "auto", anything else
1102                 // Maybe use modules.
1103         }
1104
1105         if srcDir != "" {
1106                 var absSrcDir string
1107                 if filepath.IsAbs(srcDir) {
1108                         absSrcDir = srcDir
1109                 } else if ctxt.Dir != "" {
1110                         return fmt.Errorf("go/build: Dir is non-empty, so relative srcDir is not allowed: %v", srcDir)
1111                 } else {
1112                         // Find the absolute source directory. hasSubdir does not handle
1113                         // relative paths (and can't because the callbacks don't support this).
1114                         var err error
1115                         absSrcDir, err = filepath.Abs(srcDir)
1116                         if err != nil {
1117                                 return errNoModules
1118                         }
1119                 }
1120
1121                 // If the source directory is in GOROOT, then the in-process code works fine
1122                 // and we should keep using it. Moreover, the 'go list' approach below doesn't
1123                 // take standard-library vendoring into account and will fail.
1124                 if _, ok := ctxt.hasSubdir(filepath.Join(ctxt.GOROOT, "src"), absSrcDir); ok {
1125                         return errNoModules
1126                 }
1127         }
1128
1129         // For efficiency, if path is a standard library package, let the usual lookup code handle it.
1130         if dir := ctxt.joinPath(ctxt.GOROOT, "src", path); ctxt.isDir(dir) {
1131                 return errNoModules
1132         }
1133
1134         // If GO111MODULE=auto, look to see if there is a go.mod.
1135         // Since go1.13, it doesn't matter if we're inside GOPATH.
1136         if go111Module == "auto" {
1137                 var (
1138                         parent string
1139                         err    error
1140                 )
1141                 if ctxt.Dir == "" {
1142                         parent, err = os.Getwd()
1143                         if err != nil {
1144                                 // A nonexistent working directory can't be in a module.
1145                                 return errNoModules
1146                         }
1147                 } else {
1148                         parent, err = filepath.Abs(ctxt.Dir)
1149                         if err != nil {
1150                                 // If the caller passed a bogus Dir explicitly, that's materially
1151                                 // different from not having modules enabled.
1152                                 return err
1153                         }
1154                 }
1155                 for {
1156                         if f, err := ctxt.openFile(ctxt.joinPath(parent, "go.mod")); err == nil {
1157                                 buf := make([]byte, 100)
1158                                 _, err := f.Read(buf)
1159                                 f.Close()
1160                                 if err == nil || err == io.EOF {
1161                                         // go.mod exists and is readable (is a file, not a directory).
1162                                         break
1163                                 }
1164                         }
1165                         d := filepath.Dir(parent)
1166                         if len(d) >= len(parent) {
1167                                 return errNoModules // reached top of file system, no go.mod
1168                         }
1169                         parent = d
1170                 }
1171         }
1172
1173         goCmd := filepath.Join(ctxt.GOROOT, "bin", "go")
1174         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)
1175
1176         if ctxt.Dir != "" {
1177                 cmd.Dir = ctxt.Dir
1178         }
1179
1180         var stdout, stderr strings.Builder
1181         cmd.Stdout = &stdout
1182         cmd.Stderr = &stderr
1183
1184         cgo := "0"
1185         if ctxt.CgoEnabled {
1186                 cgo = "1"
1187         }
1188         cmd.Env = append(cmd.Environ(),
1189                 "GOOS="+ctxt.GOOS,
1190                 "GOARCH="+ctxt.GOARCH,
1191                 "GOROOT="+ctxt.GOROOT,
1192                 "GOPATH="+ctxt.GOPATH,
1193                 "CGO_ENABLED="+cgo,
1194         )
1195
1196         if err := cmd.Run(); err != nil {
1197                 return fmt.Errorf("go/build: go list %s: %v\n%s\n", path, err, stderr.String())
1198         }
1199
1200         f := strings.SplitN(stdout.String(), "\n", 5)
1201         if len(f) != 5 {
1202                 return fmt.Errorf("go/build: importGo %s: unexpected output:\n%s\n", path, stdout.String())
1203         }
1204         dir := f[0]
1205         errStr := strings.TrimSpace(f[4])
1206         if errStr != "" && dir == "" {
1207                 // If 'go list' could not locate the package (dir is empty),
1208                 // return the same error that 'go list' reported.
1209                 return errors.New(errStr)
1210         }
1211
1212         // If 'go list' did locate the package, ignore the error.
1213         // It was probably related to loading source files, and we'll
1214         // encounter it ourselves shortly if the FindOnly flag isn't set.
1215         p.Dir = dir
1216         p.ImportPath = f[1]
1217         p.Root = f[2]
1218         p.Goroot = f[3] == "true"
1219         return nil
1220 }
1221
1222 func equal(x, y []string) bool {
1223         if len(x) != len(y) {
1224                 return false
1225         }
1226         for i, xi := range x {
1227                 if xi != y[i] {
1228                         return false
1229                 }
1230         }
1231         return true
1232 }
1233
1234 // hasGoFiles reports whether dir contains any files with names ending in .go.
1235 // For a vendor check we must exclude directories that contain no .go files.
1236 // Otherwise it is not possible to vendor just a/b/c and still import the
1237 // non-vendored a/b. See golang.org/issue/13832.
1238 func hasGoFiles(ctxt *Context, dir string) bool {
1239         ents, _ := ctxt.readDir(dir)
1240         for _, ent := range ents {
1241                 if !ent.IsDir() && strings.HasSuffix(ent.Name(), ".go") {
1242                         return true
1243                 }
1244         }
1245         return false
1246 }
1247
1248 func findImportComment(data []byte) (s string, line int) {
1249         // expect keyword package
1250         word, data := parseWord(data)
1251         if string(word) != "package" {
1252                 return "", 0
1253         }
1254
1255         // expect package name
1256         _, data = parseWord(data)
1257
1258         // now ready for import comment, a // or /* */ comment
1259         // beginning and ending on the current line.
1260         for len(data) > 0 && (data[0] == ' ' || data[0] == '\t' || data[0] == '\r') {
1261                 data = data[1:]
1262         }
1263
1264         var comment []byte
1265         switch {
1266         case bytes.HasPrefix(data, slashSlash):
1267                 comment, _, _ = bytes.Cut(data[2:], newline)
1268         case bytes.HasPrefix(data, slashStar):
1269                 var ok bool
1270                 comment, _, ok = bytes.Cut(data[2:], starSlash)
1271                 if !ok {
1272                         // malformed comment
1273                         return "", 0
1274                 }
1275                 if bytes.Contains(comment, newline) {
1276                         return "", 0
1277                 }
1278         }
1279         comment = bytes.TrimSpace(comment)
1280
1281         // split comment into `import`, `"pkg"`
1282         word, arg := parseWord(comment)
1283         if string(word) != "import" {
1284                 return "", 0
1285         }
1286
1287         line = 1 + bytes.Count(data[:cap(data)-cap(arg)], newline)
1288         return strings.TrimSpace(string(arg)), line
1289 }
1290
1291 var (
1292         slashSlash = []byte("//")
1293         slashStar  = []byte("/*")
1294         starSlash  = []byte("*/")
1295         newline    = []byte("\n")
1296 )
1297
1298 // skipSpaceOrComment returns data with any leading spaces or comments removed.
1299 func skipSpaceOrComment(data []byte) []byte {
1300         for len(data) > 0 {
1301                 switch data[0] {
1302                 case ' ', '\t', '\r', '\n':
1303                         data = data[1:]
1304                         continue
1305                 case '/':
1306                         if bytes.HasPrefix(data, slashSlash) {
1307                                 i := bytes.Index(data, newline)
1308                                 if i < 0 {
1309                                         return nil
1310                                 }
1311                                 data = data[i+1:]
1312                                 continue
1313                         }
1314                         if bytes.HasPrefix(data, slashStar) {
1315                                 data = data[2:]
1316                                 i := bytes.Index(data, starSlash)
1317                                 if i < 0 {
1318                                         return nil
1319                                 }
1320                                 data = data[i+2:]
1321                                 continue
1322                         }
1323                 }
1324                 break
1325         }
1326         return data
1327 }
1328
1329 // parseWord skips any leading spaces or comments in data
1330 // and then parses the beginning of data as an identifier or keyword,
1331 // returning that word and what remains after the word.
1332 func parseWord(data []byte) (word, rest []byte) {
1333         data = skipSpaceOrComment(data)
1334
1335         // Parse past leading word characters.
1336         rest = data
1337         for {
1338                 r, size := utf8.DecodeRune(rest)
1339                 if unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' {
1340                         rest = rest[size:]
1341                         continue
1342                 }
1343                 break
1344         }
1345
1346         word = data[:len(data)-len(rest)]
1347         if len(word) == 0 {
1348                 return nil, nil
1349         }
1350
1351         return word, rest
1352 }
1353
1354 // MatchFile reports whether the file with the given name in the given directory
1355 // matches the context and would be included in a Package created by ImportDir
1356 // of that directory.
1357 //
1358 // MatchFile considers the name of the file and may use ctxt.OpenFile to
1359 // read some or all of the file's content.
1360 func (ctxt *Context) MatchFile(dir, name string) (match bool, err error) {
1361         info, err := ctxt.matchFile(dir, name, nil, nil, nil)
1362         return info != nil, err
1363 }
1364
1365 var dummyPkg Package
1366
1367 // fileInfo records information learned about a file included in a build.
1368 type fileInfo struct {
1369         name     string // full name including dir
1370         header   []byte
1371         fset     *token.FileSet
1372         parsed   *ast.File
1373         parseErr error
1374         imports  []fileImport
1375         embeds   []fileEmbed
1376 }
1377
1378 type fileImport struct {
1379         path string
1380         pos  token.Pos
1381         doc  *ast.CommentGroup
1382 }
1383
1384 type fileEmbed struct {
1385         pattern string
1386         pos     token.Position
1387 }
1388
1389 // matchFile determines whether the file with the given name in the given directory
1390 // should be included in the package being constructed.
1391 // If the file should be included, matchFile returns a non-nil *fileInfo (and a nil error).
1392 // Non-nil errors are reserved for unexpected problems.
1393 //
1394 // If name denotes a Go program, matchFile reads until the end of the
1395 // imports and returns that section of the file in the fileInfo's header field,
1396 // even though it only considers text until the first non-comment
1397 // for +build lines.
1398 //
1399 // If allTags is non-nil, matchFile records any encountered build tag
1400 // by setting allTags[tag] = true.
1401 func (ctxt *Context) matchFile(dir, name string, allTags map[string]bool, binaryOnly *bool, fset *token.FileSet) (*fileInfo, error) {
1402         if strings.HasPrefix(name, "_") ||
1403                 strings.HasPrefix(name, ".") {
1404                 return nil, nil
1405         }
1406
1407         i := strings.LastIndex(name, ".")
1408         if i < 0 {
1409                 i = len(name)
1410         }
1411         ext := name[i:]
1412
1413         if !ctxt.goodOSArchFile(name, allTags) && !ctxt.UseAllFiles {
1414                 return nil, nil
1415         }
1416
1417         if ext != ".go" && fileListForExt(&dummyPkg, ext) == nil {
1418                 // skip
1419                 return nil, nil
1420         }
1421
1422         info := &fileInfo{name: ctxt.joinPath(dir, name), fset: fset}
1423         if ext == ".syso" {
1424                 // binary, no reading
1425                 return info, nil
1426         }
1427
1428         f, err := ctxt.openFile(info.name)
1429         if err != nil {
1430                 return nil, err
1431         }
1432
1433         if strings.HasSuffix(name, ".go") {
1434                 err = readGoInfo(f, info)
1435                 if strings.HasSuffix(name, "_test.go") {
1436                         binaryOnly = nil // ignore //go:binary-only-package comments in _test.go files
1437                 }
1438         } else {
1439                 binaryOnly = nil // ignore //go:binary-only-package comments in non-Go sources
1440                 info.header, err = readComments(f)
1441         }
1442         f.Close()
1443         if err != nil {
1444                 return nil, fmt.Errorf("read %s: %v", info.name, err)
1445         }
1446
1447         // Look for +build comments to accept or reject the file.
1448         ok, sawBinaryOnly, err := ctxt.shouldBuild(info.header, allTags)
1449         if err != nil {
1450                 return nil, fmt.Errorf("%s: %v", name, err)
1451         }
1452         if !ok && !ctxt.UseAllFiles {
1453                 return nil, nil
1454         }
1455
1456         if binaryOnly != nil && sawBinaryOnly {
1457                 *binaryOnly = true
1458         }
1459
1460         return info, nil
1461 }
1462
1463 func cleanDecls(m map[string][]token.Position) ([]string, map[string][]token.Position) {
1464         all := make([]string, 0, len(m))
1465         for path := range m {
1466                 all = append(all, path)
1467         }
1468         sort.Strings(all)
1469         return all, m
1470 }
1471
1472 // Import is shorthand for Default.Import.
1473 func Import(path, srcDir string, mode ImportMode) (*Package, error) {
1474         return Default.Import(path, srcDir, mode)
1475 }
1476
1477 // ImportDir is shorthand for Default.ImportDir.
1478 func ImportDir(dir string, mode ImportMode) (*Package, error) {
1479         return Default.ImportDir(dir, mode)
1480 }
1481
1482 var (
1483         bSlashSlash = []byte(slashSlash)
1484         bStarSlash  = []byte(starSlash)
1485         bSlashStar  = []byte(slashStar)
1486         bPlusBuild  = []byte("+build")
1487
1488         goBuildComment = []byte("//go:build")
1489
1490         errGoBuildWithoutBuild = errors.New("//go:build comment without // +build comment")
1491         errMultipleGoBuild     = errors.New("multiple //go:build comments")
1492 )
1493
1494 func isGoBuildComment(line []byte) bool {
1495         if !bytes.HasPrefix(line, goBuildComment) {
1496                 return false
1497         }
1498         line = bytes.TrimSpace(line)
1499         rest := line[len(goBuildComment):]
1500         return len(rest) == 0 || len(bytes.TrimSpace(rest)) < len(rest)
1501 }
1502
1503 // Special comment denoting a binary-only package.
1504 // See https://golang.org/design/2775-binary-only-packages
1505 // for more about the design of binary-only packages.
1506 var binaryOnlyComment = []byte("//go:binary-only-package")
1507
1508 // shouldBuild reports whether it is okay to use this file,
1509 // The rule is that in the file's leading run of // comments
1510 // and blank lines, which must be followed by a blank line
1511 // (to avoid including a Go package clause doc comment),
1512 // lines beginning with '// +build' are taken as build directives.
1513 //
1514 // The file is accepted only if each such line lists something
1515 // matching the file. For example:
1516 //
1517 //      // +build windows linux
1518 //
1519 // marks the file as applicable only on Windows and Linux.
1520 //
1521 // For each build tag it consults, shouldBuild sets allTags[tag] = true.
1522 //
1523 // shouldBuild reports whether the file should be built
1524 // and whether a //go:binary-only-package comment was found.
1525 func (ctxt *Context) shouldBuild(content []byte, allTags map[string]bool) (shouldBuild, binaryOnly bool, err error) {
1526         // Identify leading run of // comments and blank lines,
1527         // which must be followed by a blank line.
1528         // Also identify any //go:build comments.
1529         content, goBuild, sawBinaryOnly, err := parseFileHeader(content)
1530         if err != nil {
1531                 return false, false, err
1532         }
1533
1534         // If //go:build line is present, it controls.
1535         // Otherwise fall back to +build processing.
1536         switch {
1537         case goBuild != nil:
1538                 x, err := constraint.Parse(string(goBuild))
1539                 if err != nil {
1540                         return false, false, fmt.Errorf("parsing //go:build line: %v", err)
1541                 }
1542                 shouldBuild = ctxt.eval(x, allTags)
1543
1544         default:
1545                 shouldBuild = true
1546                 p := content
1547                 for len(p) > 0 {
1548                         line := p
1549                         if i := bytes.IndexByte(line, '\n'); i >= 0 {
1550                                 line, p = line[:i], p[i+1:]
1551                         } else {
1552                                 p = p[len(p):]
1553                         }
1554                         line = bytes.TrimSpace(line)
1555                         if !bytes.HasPrefix(line, bSlashSlash) || !bytes.Contains(line, bPlusBuild) {
1556                                 continue
1557                         }
1558                         text := string(line)
1559                         if !constraint.IsPlusBuild(text) {
1560                                 continue
1561                         }
1562                         if x, err := constraint.Parse(text); err == nil {
1563                                 if !ctxt.eval(x, allTags) {
1564                                         shouldBuild = false
1565                                 }
1566                         }
1567                 }
1568         }
1569
1570         return shouldBuild, sawBinaryOnly, nil
1571 }
1572
1573 func parseFileHeader(content []byte) (trimmed, goBuild []byte, sawBinaryOnly bool, err error) {
1574         end := 0
1575         p := content
1576         ended := false       // found non-blank, non-// line, so stopped accepting // +build lines
1577         inSlashStar := false // in /* */ comment
1578
1579 Lines:
1580         for len(p) > 0 {
1581                 line := p
1582                 if i := bytes.IndexByte(line, '\n'); i >= 0 {
1583                         line, p = line[:i], p[i+1:]
1584                 } else {
1585                         p = p[len(p):]
1586                 }
1587                 line = bytes.TrimSpace(line)
1588                 if len(line) == 0 && !ended { // Blank line
1589                         // Remember position of most recent blank line.
1590                         // When we find the first non-blank, non-// line,
1591                         // this "end" position marks the latest file position
1592                         // where a // +build line can appear.
1593                         // (It must appear _before_ a blank line before the non-blank, non-// line.
1594                         // Yes, that's confusing, which is part of why we moved to //go:build lines.)
1595                         // Note that ended==false here means that inSlashStar==false,
1596                         // since seeing a /* would have set ended==true.
1597                         end = len(content) - len(p)
1598                         continue Lines
1599                 }
1600                 if !bytes.HasPrefix(line, slashSlash) { // Not comment line
1601                         ended = true
1602                 }
1603
1604                 if !inSlashStar && isGoBuildComment(line) {
1605                         if goBuild != nil {
1606                                 return nil, nil, false, errMultipleGoBuild
1607                         }
1608                         goBuild = line
1609                 }
1610                 if !inSlashStar && bytes.Equal(line, binaryOnlyComment) {
1611                         sawBinaryOnly = true
1612                 }
1613
1614         Comments:
1615                 for len(line) > 0 {
1616                         if inSlashStar {
1617                                 if i := bytes.Index(line, starSlash); i >= 0 {
1618                                         inSlashStar = false
1619                                         line = bytes.TrimSpace(line[i+len(starSlash):])
1620                                         continue Comments
1621                                 }
1622                                 continue Lines
1623                         }
1624                         if bytes.HasPrefix(line, bSlashSlash) {
1625                                 continue Lines
1626                         }
1627                         if bytes.HasPrefix(line, bSlashStar) {
1628                                 inSlashStar = true
1629                                 line = bytes.TrimSpace(line[len(bSlashStar):])
1630                                 continue Comments
1631                         }
1632                         // Found non-comment text.
1633                         break Lines
1634                 }
1635         }
1636
1637         return content[:end], goBuild, sawBinaryOnly, nil
1638 }
1639
1640 // saveCgo saves the information from the #cgo lines in the import "C" comment.
1641 // These lines set CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS and pkg-config directives
1642 // that affect the way cgo's C code is built.
1643 func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error {
1644         text := cg.Text()
1645         for _, line := range strings.Split(text, "\n") {
1646                 orig := line
1647
1648                 // Line is
1649                 //      #cgo [GOOS/GOARCH...] LDFLAGS: stuff
1650                 //
1651                 line = strings.TrimSpace(line)
1652                 if len(line) < 5 || line[:4] != "#cgo" || (line[4] != ' ' && line[4] != '\t') {
1653                         continue
1654                 }
1655
1656                 // Split at colon.
1657                 line, argstr, ok := strings.Cut(strings.TrimSpace(line[4:]), ":")
1658                 if !ok {
1659                         return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1660                 }
1661
1662                 // Parse GOOS/GOARCH stuff.
1663                 f := strings.Fields(line)
1664                 if len(f) < 1 {
1665                         return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1666                 }
1667
1668                 cond, verb := f[:len(f)-1], f[len(f)-1]
1669                 if len(cond) > 0 {
1670                         ok := false
1671                         for _, c := range cond {
1672                                 if ctxt.matchAuto(c, nil) {
1673                                         ok = true
1674                                         break
1675                                 }
1676                         }
1677                         if !ok {
1678                                 continue
1679                         }
1680                 }
1681
1682                 args, err := splitQuoted(argstr)
1683                 if err != nil {
1684                         return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1685                 }
1686                 for i, arg := range args {
1687                         if arg, ok = expandSrcDir(arg, di.Dir); !ok {
1688                                 return fmt.Errorf("%s: malformed #cgo argument: %s", filename, arg)
1689                         }
1690                         args[i] = arg
1691                 }
1692
1693                 switch verb {
1694                 case "CFLAGS", "CPPFLAGS", "CXXFLAGS", "FFLAGS", "LDFLAGS":
1695                         // Change relative paths to absolute.
1696                         ctxt.makePathsAbsolute(args, di.Dir)
1697                 }
1698
1699                 switch verb {
1700                 case "CFLAGS":
1701                         di.CgoCFLAGS = append(di.CgoCFLAGS, args...)
1702                 case "CPPFLAGS":
1703                         di.CgoCPPFLAGS = append(di.CgoCPPFLAGS, args...)
1704                 case "CXXFLAGS":
1705                         di.CgoCXXFLAGS = append(di.CgoCXXFLAGS, args...)
1706                 case "FFLAGS":
1707                         di.CgoFFLAGS = append(di.CgoFFLAGS, args...)
1708                 case "LDFLAGS":
1709                         di.CgoLDFLAGS = append(di.CgoLDFLAGS, args...)
1710                 case "pkg-config":
1711                         di.CgoPkgConfig = append(di.CgoPkgConfig, args...)
1712                 default:
1713                         return fmt.Errorf("%s: invalid #cgo verb: %s", filename, orig)
1714                 }
1715         }
1716         return nil
1717 }
1718
1719 // expandSrcDir expands any occurrence of ${SRCDIR}, making sure
1720 // the result is safe for the shell.
1721 func expandSrcDir(str string, srcdir string) (string, bool) {
1722         // "\" delimited paths cause safeCgoName to fail
1723         // so convert native paths with a different delimiter
1724         // to "/" before starting (eg: on windows).
1725         srcdir = filepath.ToSlash(srcdir)
1726
1727         chunks := strings.Split(str, "${SRCDIR}")
1728         if len(chunks) < 2 {
1729                 return str, safeCgoName(str)
1730         }
1731         ok := true
1732         for _, chunk := range chunks {
1733                 ok = ok && (chunk == "" || safeCgoName(chunk))
1734         }
1735         ok = ok && (srcdir == "" || safeCgoName(srcdir))
1736         res := strings.Join(chunks, srcdir)
1737         return res, ok && res != ""
1738 }
1739
1740 // makePathsAbsolute looks for compiler options that take paths and
1741 // makes them absolute. We do this because through the 1.8 release we
1742 // ran the compiler in the package directory, so any relative -I or -L
1743 // options would be relative to that directory. In 1.9 we changed to
1744 // running the compiler in the build directory, to get consistent
1745 // build results (issue #19964). To keep builds working, we change any
1746 // relative -I or -L options to be absolute.
1747 //
1748 // Using filepath.IsAbs and filepath.Join here means the results will be
1749 // different on different systems, but that's OK: -I and -L options are
1750 // inherently system-dependent.
1751 func (ctxt *Context) makePathsAbsolute(args []string, srcDir string) {
1752         nextPath := false
1753         for i, arg := range args {
1754                 if nextPath {
1755                         if !filepath.IsAbs(arg) {
1756                                 args[i] = filepath.Join(srcDir, arg)
1757                         }
1758                         nextPath = false
1759                 } else if strings.HasPrefix(arg, "-I") || strings.HasPrefix(arg, "-L") {
1760                         if len(arg) == 2 {
1761                                 nextPath = true
1762                         } else {
1763                                 if !filepath.IsAbs(arg[2:]) {
1764                                         args[i] = arg[:2] + filepath.Join(srcDir, arg[2:])
1765                                 }
1766                         }
1767                 }
1768         }
1769 }
1770
1771 // NOTE: $ is not safe for the shell, but it is allowed here because of linker options like -Wl,$ORIGIN.
1772 // We never pass these arguments to a shell (just to programs we construct argv for), so this should be okay.
1773 // See golang.org/issue/6038.
1774 // The @ is for OS X. See golang.org/issue/13720.
1775 // The % is for Jenkins. See golang.org/issue/16959.
1776 // The ! is because module paths may use them. See golang.org/issue/26716.
1777 // The ~ and ^ are for sr.ht. See golang.org/issue/32260.
1778 const safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$@%! ~^"
1779
1780 func safeCgoName(s string) bool {
1781         if s == "" {
1782                 return false
1783         }
1784         for i := 0; i < len(s); i++ {
1785                 if c := s[i]; c < utf8.RuneSelf && strings.IndexByte(safeString, c) < 0 {
1786                         return false
1787                 }
1788         }
1789         return true
1790 }
1791
1792 // splitQuoted splits the string s around each instance of one or more consecutive
1793 // white space characters while taking into account quotes and escaping, and
1794 // returns an array of substrings of s or an empty list if s contains only white space.
1795 // Single quotes and double quotes are recognized to prevent splitting within the
1796 // quoted region, and are removed from the resulting substrings. If a quote in s
1797 // isn't closed err will be set and r will have the unclosed argument as the
1798 // last element. The backslash is used for escaping.
1799 //
1800 // For example, the following string:
1801 //
1802 //      a b:"c d" 'e''f'  "g\""
1803 //
1804 // Would be parsed as:
1805 //
1806 //      []string{"a", "b:c d", "ef", `g"`}
1807 func splitQuoted(s string) (r []string, err error) {
1808         var args []string
1809         arg := make([]rune, len(s))
1810         escaped := false
1811         quoted := false
1812         quote := '\x00'
1813         i := 0
1814         for _, rune := range s {
1815                 switch {
1816                 case escaped:
1817                         escaped = false
1818                 case rune == '\\':
1819                         escaped = true
1820                         continue
1821                 case quote != '\x00':
1822                         if rune == quote {
1823                                 quote = '\x00'
1824                                 continue
1825                         }
1826                 case rune == '"' || rune == '\'':
1827                         quoted = true
1828                         quote = rune
1829                         continue
1830                 case unicode.IsSpace(rune):
1831                         if quoted || i > 0 {
1832                                 quoted = false
1833                                 args = append(args, string(arg[:i]))
1834                                 i = 0
1835                         }
1836                         continue
1837                 }
1838                 arg[i] = rune
1839                 i++
1840         }
1841         if quoted || i > 0 {
1842                 args = append(args, string(arg[:i]))
1843         }
1844         if quote != 0 {
1845                 err = errors.New("unclosed quote")
1846         } else if escaped {
1847                 err = errors.New("unfinished escaping")
1848         }
1849         return args, err
1850 }
1851
1852 // matchAuto interprets text as either a +build or //go:build expression (whichever works),
1853 // reporting whether the expression matches the build context.
1854 //
1855 // matchAuto is only used for testing of tag evaluation
1856 // and in #cgo lines, which accept either syntax.
1857 func (ctxt *Context) matchAuto(text string, allTags map[string]bool) bool {
1858         if strings.ContainsAny(text, "&|()") {
1859                 text = "//go:build " + text
1860         } else {
1861                 text = "// +build " + text
1862         }
1863         x, err := constraint.Parse(text)
1864         if err != nil {
1865                 return false
1866         }
1867         return ctxt.eval(x, allTags)
1868 }
1869
1870 func (ctxt *Context) eval(x constraint.Expr, allTags map[string]bool) bool {
1871         return x.Eval(func(tag string) bool { return ctxt.matchTag(tag, allTags) })
1872 }
1873
1874 // matchTag reports whether the name is one of:
1875 //
1876 //      cgo (if cgo is enabled)
1877 //      $GOOS
1878 //      $GOARCH
1879 //      boringcrypto
1880 //      ctxt.Compiler
1881 //      linux (if GOOS = android)
1882 //      solaris (if GOOS = illumos)
1883 //      tag (if tag is listed in ctxt.BuildTags or ctxt.ReleaseTags)
1884 //
1885 // It records all consulted tags in allTags.
1886 func (ctxt *Context) matchTag(name string, allTags map[string]bool) bool {
1887         if allTags != nil {
1888                 allTags[name] = true
1889         }
1890
1891         // special tags
1892         if ctxt.CgoEnabled && name == "cgo" {
1893                 return true
1894         }
1895         if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler {
1896                 return true
1897         }
1898         if ctxt.GOOS == "android" && name == "linux" {
1899                 return true
1900         }
1901         if ctxt.GOOS == "illumos" && name == "solaris" {
1902                 return true
1903         }
1904         if ctxt.GOOS == "ios" && name == "darwin" {
1905                 return true
1906         }
1907         if name == "unix" && unixOS[ctxt.GOOS] {
1908                 return true
1909         }
1910         if name == "boringcrypto" {
1911                 name = "goexperiment.boringcrypto" // boringcrypto is an old name for goexperiment.boringcrypto
1912         }
1913
1914         // other tags
1915         for _, tag := range ctxt.BuildTags {
1916                 if tag == name {
1917                         return true
1918                 }
1919         }
1920         for _, tag := range ctxt.ToolTags {
1921                 if tag == name {
1922                         return true
1923                 }
1924         }
1925         for _, tag := range ctxt.ReleaseTags {
1926                 if tag == name {
1927                         return true
1928                 }
1929         }
1930
1931         return false
1932 }
1933
1934 // goodOSArchFile returns false if the name contains a $GOOS or $GOARCH
1935 // suffix which does not match the current system.
1936 // The recognized name formats are:
1937 //
1938 //      name_$(GOOS).*
1939 //      name_$(GOARCH).*
1940 //      name_$(GOOS)_$(GOARCH).*
1941 //      name_$(GOOS)_test.*
1942 //      name_$(GOARCH)_test.*
1943 //      name_$(GOOS)_$(GOARCH)_test.*
1944 //
1945 // Exceptions:
1946 // if GOOS=android, then files with GOOS=linux are also matched.
1947 // if GOOS=illumos, then files with GOOS=solaris are also matched.
1948 // if GOOS=ios, then files with GOOS=darwin are also matched.
1949 func (ctxt *Context) goodOSArchFile(name string, allTags map[string]bool) bool {
1950         name, _, _ = strings.Cut(name, ".")
1951
1952         // Before Go 1.4, a file called "linux.go" would be equivalent to having a
1953         // build tag "linux" in that file. For Go 1.4 and beyond, we require this
1954         // auto-tagging to apply only to files with a non-empty prefix, so
1955         // "foo_linux.go" is tagged but "linux.go" is not. This allows new operating
1956         // systems, such as android, to arrive without breaking existing code with
1957         // innocuous source code in "android.go". The easiest fix: cut everything
1958         // in the name before the initial _.
1959         i := strings.Index(name, "_")
1960         if i < 0 {
1961                 return true
1962         }
1963         name = name[i:] // ignore everything before first _
1964
1965         l := strings.Split(name, "_")
1966         if n := len(l); n > 0 && l[n-1] == "test" {
1967                 l = l[:n-1]
1968         }
1969         n := len(l)
1970         if n >= 2 && knownOS[l[n-2]] && knownArch[l[n-1]] {
1971                 if allTags != nil {
1972                         // In case we short-circuit on l[n-1].
1973                         allTags[l[n-2]] = true
1974                 }
1975                 return ctxt.matchTag(l[n-1], allTags) && ctxt.matchTag(l[n-2], allTags)
1976         }
1977         if n >= 1 && (knownOS[l[n-1]] || knownArch[l[n-1]]) {
1978                 return ctxt.matchTag(l[n-1], allTags)
1979         }
1980         return true
1981 }
1982
1983 // ToolDir is the directory containing build tools.
1984 var ToolDir = getToolDir()
1985
1986 // IsLocalImport reports whether the import path is
1987 // a local import path, like ".", "..", "./foo", or "../foo".
1988 func IsLocalImport(path string) bool {
1989         return path == "." || path == ".." ||
1990                 strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../")
1991 }
1992
1993 // ArchChar returns "?" and an error.
1994 // In earlier versions of Go, the returned string was used to derive
1995 // the compiler and linker tool names, the default object file suffix,
1996 // and the default linker output name. As of Go 1.5, those strings
1997 // no longer vary by architecture; they are compile, link, .o, and a.out, respectively.
1998 func ArchChar(goarch string) (string, error) {
1999         return "?", errors.New("architecture letter no longer used")
2000 }