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.
33 // A Context specifies the supporting context for a build.
35 GOARCH string // target architecture
36 GOOS string // target operating system
37 GOROOT string // Go root
38 GOPATH string // Go paths
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.
44 // If Dir is non-empty, directories passed to Import and ImportDir must
48 CgoEnabled bool // whether cgo files are included
49 UseAllFiles bool // use files regardless of go:build lines, file names
50 Compiler string // compiler to assume when computing target paths
52 // The build, tool, and release tags specify build constraints
53 // that should be considered satisfied when processing go: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.
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".
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.
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
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
88 // IsAbsPath reports whether path is an absolute path.
89 // If IsAbsPath is nil, Import uses filepath.IsAbs.
90 IsAbsPath func(path string) bool
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
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)
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 os.ReadDir.
108 ReadDir func(dir string) ([]fs.FileInfo, error)
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)
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 {
120 return filepath.Join(elem...)
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 {
128 return filepath.SplitList(s)
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 {
136 return filepath.IsAbs(path)
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 {
144 fi, err := os.Stat(path)
145 return err == nil && fi.IsDir()
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 {
155 // Try using paths we received.
156 if rel, ok = hasSubdir(root, dir); ok {
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)
166 if rel, ok = hasSubdir(rootSym, dir); ok {
169 if rel, ok = hasSubdir(root, dirSym); ok {
172 return hasSubdir(rootSym, dirSym)
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) {
182 dir = filepath.Clean(dir)
183 after, found := strings.CutPrefix(dir, root)
187 return filepath.ToSlash(after), true
190 // readDir calls ctxt.ReadDir (if not nil) or else os.ReadDir.
191 func (ctxt *Context) readDir(path string) ([]fs.DirEntry, error) {
192 // TODO: add a fs.DirEntry version of Context.ReadDir
193 if f := ctxt.ReadDir; f != nil {
198 des := make([]fs.DirEntry, len(fis))
199 for i, fi := range fis {
200 des[i] = fs.FileInfoToDirEntry(fi)
204 return os.ReadDir(path)
207 // openFile calls ctxt.OpenFile (if not nil) or else os.Open.
208 func (ctxt *Context) openFile(path string) (io.ReadCloser, error) {
209 if fn := ctxt.OpenFile; fn != nil {
213 f, err := os.Open(path)
215 return nil, err // nil interface
220 // isFile determines whether path is a file by trying to open it.
221 // It reuses openFile instead of adding another function to the
223 func (ctxt *Context) isFile(path string) bool {
224 f, err := ctxt.openFile(path)
232 // gopath returns the list of Go path directories.
233 func (ctxt *Context) gopath() []string {
235 for _, p := range ctxt.splitPathList(ctxt.GOPATH) {
236 if p == "" || p == ctxt.GOROOT {
237 // Empty paths are uninteresting.
238 // If the path is the GOROOT, ignore it.
239 // People sometimes set GOPATH=$GOROOT.
240 // Do not get confused by this common mistake.
243 if strings.HasPrefix(p, "~") {
244 // Path segments starting with ~ on Unix are almost always
245 // users who have incorrectly quoted ~ while setting GOPATH,
246 // preventing it from expanding to $HOME.
247 // The situation is made more confusing by the fact that
248 // bash allows quoted ~ in $PATH (most shells do not).
249 // Do not get confused by this, and do not try to use the path.
250 // It does not exist, and printing errors about it confuses
251 // those users even more, because they think "sure ~ exists!".
252 // The go command diagnoses this situation and prints a
254 // On Windows, ~ is used in short names, such as c:\progra~1
255 // for c:\program files.
263 // SrcDirs returns a list of package source root directories.
264 // It draws from the current Go root and Go path but omits directories
265 // that do not exist.
266 func (ctxt *Context) SrcDirs() []string {
268 if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
269 dir := ctxt.joinPath(ctxt.GOROOT, "src")
271 all = append(all, dir)
274 for _, p := range ctxt.gopath() {
275 dir := ctxt.joinPath(p, "src")
277 all = append(all, dir)
283 // Default is the default Context for builds.
284 // It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables
285 // if set, or else the compiled code's GOARCH, GOOS, and GOROOT.
286 var Default Context = defaultContext()
288 func defaultGOPATH() string {
290 if runtime.GOOS == "windows" {
292 } else if runtime.GOOS == "plan9" {
295 if home := os.Getenv(env); home != "" {
296 def := filepath.Join(home, "go")
297 if filepath.Clean(def) == filepath.Clean(runtime.GOROOT()) {
298 // Don't set the default GOPATH to GOROOT,
299 // as that will trigger warnings from the go tool.
307 var defaultToolTags, defaultReleaseTags []string
309 func defaultContext() Context {
312 c.GOARCH = buildcfg.GOARCH
313 c.GOOS = buildcfg.GOOS
314 if goroot := runtime.GOROOT(); goroot != "" {
315 c.GOROOT = filepath.Clean(goroot)
317 c.GOPATH = envOr("GOPATH", defaultGOPATH())
318 c.Compiler = runtime.Compiler
319 c.ToolTags = append(c.ToolTags, buildcfg.ToolTags...)
321 defaultToolTags = append([]string{}, c.ToolTags...) // our own private copy
323 // Each major Go release in the Go 1.x series adds a new
324 // "go1.x" release tag. That is, the go1.x tag is present in
325 // all releases >= Go 1.x. Code that requires Go 1.x or later
326 // should say "go:build go1.x", and code that should only be
327 // built before Go 1.x (perhaps it is the stub to use in that
328 // case) should say "go:build !go1.x".
329 // The last element in ReleaseTags is the current release.
330 for i := 1; i <= goversion.Version; i++ {
331 c.ReleaseTags = append(c.ReleaseTags, "go1."+strconv.Itoa(i))
334 defaultReleaseTags = append([]string{}, c.ReleaseTags...) // our own private copy
336 env := os.Getenv("CGO_ENABLED")
338 env = defaultCGO_ENABLED
346 // cgo must be explicitly enabled for cross compilation builds
347 if runtime.GOARCH == c.GOARCH && runtime.GOOS == c.GOOS {
348 c.CgoEnabled = cgoEnabled[c.GOOS+"/"+c.GOARCH]
357 func envOr(name, def string) string {
365 // An ImportMode controls the behavior of the Import method.
369 // If FindOnly is set, Import stops after locating the directory
370 // that should contain the sources for a package. It does not
371 // read any files in the directory.
372 FindOnly ImportMode = 1 << iota
374 // If AllowBinary is set, Import can be satisfied by a compiled
375 // package object without corresponding sources.
378 // The supported way to create a compiled-only package is to
379 // write source code containing a //go:binary-only-package comment at
380 // the top of the file. Such a package will be recognized
381 // regardless of this flag setting (because it has source code)
382 // and will have BinaryOnly set to true in the returned Package.
385 // If ImportComment is set, parse import comments on package statements.
386 // Import returns an error if it finds a comment it cannot understand
387 // or finds conflicting comments in multiple source files.
388 // See golang.org/s/go14customimport for more information.
391 // By default, Import searches vendor directories
392 // that apply in the given source directory before searching
393 // the GOROOT and GOPATH roots.
394 // If an Import finds and returns a package using a vendor
395 // directory, the resulting ImportPath is the complete path
396 // to the package, including the path elements leading up
397 // to and including "vendor".
398 // For example, if Import("y", "x/subdir", 0) finds
399 // "x/vendor/y", the returned package's ImportPath is "x/vendor/y",
401 // See golang.org/s/go15vendor for more information.
403 // Setting IgnoreVendor ignores vendor directories.
405 // In contrast to the package's ImportPath,
406 // the returned package's Imports, TestImports, and XTestImports
407 // are always the exact import paths from the source files:
408 // Import makes no attempt to resolve or check those paths.
412 // A Package describes the Go package found in a directory.
413 type Package struct {
414 Dir string // directory containing package sources
415 Name string // package name
416 ImportComment string // path in import comment on package statement
417 Doc string // documentation synopsis
418 ImportPath string // import path of package ("" if unknown)
419 Root string // root of Go tree where this package lives
420 SrcRoot string // package source root directory ("" if unknown)
421 PkgRoot string // package install root directory ("" if unknown)
422 PkgTargetRoot string // architecture dependent install root directory ("" if unknown)
423 BinDir string // command install directory ("" if unknown)
424 Goroot bool // package found in Go root
425 PkgObj string // installed .a file
426 AllTags []string // tags that can influence file selection in this directory
427 ConflictDir string // this directory shadows Dir in $GOPATH
428 BinaryOnly bool // cannot be rebuilt from source (has //go:binary-only-package comment)
431 GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
432 CgoFiles []string // .go source files that import "C"
433 IgnoredGoFiles []string // .go source files ignored for this build (including ignored _test.go files)
434 InvalidGoFiles []string // .go source files with detected problems (parse error, wrong package name, and so on)
435 IgnoredOtherFiles []string // non-.go source files ignored for this build
436 CFiles []string // .c source files
437 CXXFiles []string // .cc, .cpp and .cxx source files
438 MFiles []string // .m (Objective-C) source files
439 HFiles []string // .h, .hh, .hpp and .hxx source files
440 FFiles []string // .f, .F, .for and .f90 Fortran source files
441 SFiles []string // .s source files
442 SwigFiles []string // .swig files
443 SwigCXXFiles []string // .swigcxx files
444 SysoFiles []string // .syso system object files to add to archive
447 CgoCFLAGS []string // Cgo CFLAGS directives
448 CgoCPPFLAGS []string // Cgo CPPFLAGS directives
449 CgoCXXFLAGS []string // Cgo CXXFLAGS directives
450 CgoFFLAGS []string // Cgo FFLAGS directives
451 CgoLDFLAGS []string // Cgo LDFLAGS directives
452 CgoPkgConfig []string // Cgo pkg-config directives
455 TestGoFiles []string // _test.go files in package
456 XTestGoFiles []string // _test.go files outside package
458 // Dependency information
459 Imports []string // import paths from GoFiles, CgoFiles
460 ImportPos map[string][]token.Position // line information for Imports
461 TestImports []string // import paths from TestGoFiles
462 TestImportPos map[string][]token.Position // line information for TestImports
463 XTestImports []string // import paths from XTestGoFiles
464 XTestImportPos map[string][]token.Position // line information for XTestImports
466 // //go:embed patterns found in Go source files
467 // For example, if a source file says
469 // then the list will contain those two strings as separate entries.
470 // (See package embed for more details about //go:embed.)
471 EmbedPatterns []string // patterns from GoFiles, CgoFiles
472 EmbedPatternPos map[string][]token.Position // line information for EmbedPatterns
473 TestEmbedPatterns []string // patterns from TestGoFiles
474 TestEmbedPatternPos map[string][]token.Position // line information for TestEmbedPatterns
475 XTestEmbedPatterns []string // patterns from XTestGoFiles
476 XTestEmbedPatternPos map[string][]token.Position // line information for XTestEmbedPatternPos
479 // IsCommand reports whether the package is considered a
480 // command to be installed (not just a library).
481 // Packages named "main" are treated as commands.
482 func (p *Package) IsCommand() bool {
483 return p.Name == "main"
486 // ImportDir is like Import but processes the Go package found in
487 // the named directory.
488 func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error) {
489 return ctxt.Import(".", dir, mode)
492 // NoGoError is the error used by Import to describe a directory
493 // containing no buildable Go source files. (It may still contain
494 // test files, files hidden by build tags, and so on.)
495 type NoGoError struct {
499 func (e *NoGoError) Error() string {
500 return "no buildable Go source files in " + e.Dir
503 // MultiplePackageError describes a directory containing
504 // multiple buildable Go source files for multiple packages.
505 type MultiplePackageError struct {
506 Dir string // directory containing files
507 Packages []string // package names found
508 Files []string // corresponding files: Files[i] declares package Packages[i]
511 func (e *MultiplePackageError) Error() string {
512 // Error string limited to two entries for compatibility.
513 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)
516 func nameExt(name string) string {
517 i := strings.LastIndex(name, ".")
524 var installgoroot = godebug.New("installgoroot")
526 // Import returns details about the Go package named by the import path,
527 // interpreting local import paths relative to the srcDir directory.
528 // If the path is a local import path naming a package that can be imported
529 // using a standard import path, the returned package will set p.ImportPath
532 // In the directory containing the package, .go, .c, .h, and .s files are
533 // considered part of the package except for:
535 // - .go files in package documentation
536 // - files starting with _ or . (likely editor temporary files)
537 // - files with build constraints not satisfied by the context
539 // If an error occurs, Import returns a non-nil error and a non-nil
540 // *Package containing partial information.
541 func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error) {
546 return p, fmt.Errorf("import %q: invalid import path", path)
549 var pkgtargetroot string
553 if ctxt.InstallSuffix != "" {
554 suffix = "_" + ctxt.InstallSuffix
556 switch ctxt.Compiler {
558 pkgtargetroot = "pkg/gccgo_" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
560 pkgtargetroot = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
562 // Save error for end of function.
563 pkgerr = fmt.Errorf("import %q: unknown compiler %q", path, ctxt.Compiler)
566 switch ctxt.Compiler {
568 dir, elem := pathpkg.Split(p.ImportPath)
569 pkga = pkgtargetroot + "/" + dir + "lib" + elem + ".a"
571 pkga = pkgtargetroot + "/" + p.ImportPath + ".a"
577 if IsLocalImport(path) {
578 pkga = "" // local imports have no installed path
580 return p, fmt.Errorf("import %q: import relative to unknown directory", path)
582 if !ctxt.isAbsPath(path) {
583 p.Dir = ctxt.joinPath(srcDir, path)
585 // p.Dir directory may or may not exist. Gather partial information first, check if it exists later.
586 // Determine canonical import path, if any.
587 // Exclude results where the import path would include /testdata/.
588 inTestdata := func(sub string) bool {
589 return strings.Contains(sub, "/testdata/") || strings.HasSuffix(sub, "/testdata") || strings.HasPrefix(sub, "testdata/") || sub == "testdata"
591 if ctxt.GOROOT != "" {
592 root := ctxt.joinPath(ctxt.GOROOT, "src")
593 if sub, ok := ctxt.hasSubdir(root, p.Dir); ok && !inTestdata(sub) {
597 setPkga() // p.ImportPath changed
602 for i, root := range all {
603 rootsrc := ctxt.joinPath(root, "src")
604 if sub, ok := ctxt.hasSubdir(rootsrc, p.Dir); ok && !inTestdata(sub) {
605 // We found a potential import path for dir,
606 // but check that using it wouldn't find something
608 if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
609 if dir := ctxt.joinPath(ctxt.GOROOT, "src", sub); ctxt.isDir(dir) {
614 for _, earlyRoot := range all[:i] {
615 if dir := ctxt.joinPath(earlyRoot, "src", sub); ctxt.isDir(dir) {
621 // sub would not name some other directory instead of this one.
625 setPkga() // p.ImportPath changed
629 // It's okay that we didn't find a root containing dir.
630 // Keep going with the information we have.
632 if strings.HasPrefix(path, "/") {
633 return p, fmt.Errorf("import %q: cannot import absolute path", path)
636 if err := ctxt.importGo(p, path, srcDir, mode); err == nil {
638 } else if err != errNoModules {
642 gopath := ctxt.gopath() // needed twice below; avoid computing many times
644 // tried records the location of unsuccessful package lookups
651 // Vendor directories get first chance to satisfy import.
652 if mode&IgnoreVendor == 0 && srcDir != "" {
653 searchVendor := func(root string, isGoroot bool) bool {
654 sub, ok := ctxt.hasSubdir(root, srcDir)
655 if !ok || !strings.HasPrefix(sub, "src/") || strings.Contains(sub, "/testdata/") {
659 vendor := ctxt.joinPath(root, sub, "vendor")
660 if ctxt.isDir(vendor) {
661 dir := ctxt.joinPath(vendor, path)
662 if ctxt.isDir(dir) && hasGoFiles(ctxt, dir) {
664 p.ImportPath = strings.TrimPrefix(pathpkg.Join(sub, "vendor", path), "src/")
667 setPkga() // p.ImportPath changed
670 tried.vendor = append(tried.vendor, dir)
672 i := strings.LastIndex(sub, "/")
680 if ctxt.Compiler != "gccgo" && ctxt.GOROOT != "" && searchVendor(ctxt.GOROOT, true) {
683 for _, root := range gopath {
684 if searchVendor(root, false) {
690 // Determine directory from import path.
691 if ctxt.GOROOT != "" {
692 // If the package path starts with "vendor/", only search GOROOT before
693 // GOPATH if the importer is also within GOROOT. That way, if the user has
694 // vendored in a package that is subsequently included in the standard
695 // distribution, they'll continue to pick up their own vendored copy.
696 gorootFirst := srcDir == "" || !strings.HasPrefix(path, "vendor/")
698 _, gorootFirst = ctxt.hasSubdir(ctxt.GOROOT, srcDir)
701 dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
702 if ctxt.Compiler != "gccgo" {
703 isDir := ctxt.isDir(dir)
704 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
705 if isDir || binaryOnly {
714 if ctxt.Compiler == "gccgo" && goroot.IsStandardPackage(ctxt.GOROOT, ctxt.Compiler, path) {
715 // TODO(bcmills): Setting p.Dir here is misleading, because gccgo
716 // doesn't actually load its standard-library packages from this
717 // directory. See if we can leave it unset.
718 p.Dir = ctxt.joinPath(ctxt.GOROOT, "src", path)
724 for _, root := range gopath {
725 dir := ctxt.joinPath(root, "src", path)
726 isDir := ctxt.isDir(dir)
727 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(root, pkga))
728 if isDir || binaryOnly {
733 tried.gopath = append(tried.gopath, dir)
736 // If we tried GOPATH first due to a "vendor/" prefix, fall back to GOPATH.
737 // That way, the user can still get useful results from 'go list' for
738 // standard-vendored paths passed on the command line.
739 if ctxt.GOROOT != "" && tried.goroot == "" {
740 dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
741 if ctxt.Compiler != "gccgo" {
742 isDir := ctxt.isDir(dir)
743 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
744 if isDir || binaryOnly {
754 // package was not found
756 format := "\t%s (vendor tree)"
757 for _, dir := range tried.vendor {
758 paths = append(paths, fmt.Sprintf(format, dir))
761 if tried.goroot != "" {
762 paths = append(paths, fmt.Sprintf("\t%s (from $GOROOT)", tried.goroot))
764 paths = append(paths, "\t($GOROOT not set)")
766 format = "\t%s (from $GOPATH)"
767 for _, dir := range tried.gopath {
768 paths = append(paths, fmt.Sprintf(format, dir))
771 if len(tried.gopath) == 0 {
772 paths = append(paths, "\t($GOPATH not set. For more details see: 'go help gopath')")
774 return p, fmt.Errorf("cannot find package %q in any of:\n%s", path, strings.Join(paths, "\n"))
779 p.SrcRoot = ctxt.joinPath(p.Root, "src")
780 p.PkgRoot = ctxt.joinPath(p.Root, "pkg")
781 p.BinDir = ctxt.joinPath(p.Root, "bin")
783 // Always set PkgTargetRoot. It might be used when building in shared
785 p.PkgTargetRoot = ctxt.joinPath(p.Root, pkgtargetroot)
787 // Set the install target if applicable.
788 if !p.Goroot || (installgoroot.Value() == "all" && p.ImportPath != "unsafe" && p.ImportPath != "builtin") {
789 p.PkgObj = ctxt.joinPath(p.Root, pkga)
794 // If it's a local import path, by the time we get here, we still haven't checked
795 // that p.Dir directory exists. This is the right time to do that check.
796 // We can't do it earlier, because we want to gather partial information for the
797 // non-nil *Package returned when an error occurs.
798 // We need to do this before we return early on FindOnly flag.
799 if IsLocalImport(path) && !ctxt.isDir(p.Dir) {
800 if ctxt.Compiler == "gccgo" && p.Goroot {
801 // gccgo has no sources for GOROOT packages.
805 // package was not found
806 return p, fmt.Errorf("cannot find package %q in:\n\t%s", p.ImportPath, p.Dir)
809 if mode&FindOnly != 0 {
812 if binaryOnly && (mode&AllowBinary) != 0 {
816 if ctxt.Compiler == "gccgo" && p.Goroot {
817 // gccgo has no sources for GOROOT packages.
821 dirs, err := ctxt.readDir(p.Dir)
827 badGoFiles := make(map[string]bool)
828 badGoFile := func(name string, err error) {
829 if badGoError == nil {
832 if !badGoFiles[name] {
833 p.InvalidGoFiles = append(p.InvalidGoFiles, name)
834 badGoFiles[name] = true
838 var Sfiles []string // files with ".S"(capital S)/.sx(capital s equivalent for case insensitive filesystems)
839 var firstFile, firstCommentFile string
840 embedPos := make(map[string][]token.Position)
841 testEmbedPos := make(map[string][]token.Position)
842 xTestEmbedPos := make(map[string][]token.Position)
843 importPos := make(map[string][]token.Position)
844 testImportPos := make(map[string][]token.Position)
845 xTestImportPos := make(map[string][]token.Position)
846 allTags := make(map[string]bool)
847 fset := token.NewFileSet()
848 for _, d := range dirs {
852 if d.Type() == fs.ModeSymlink {
853 if ctxt.isDir(ctxt.joinPath(p.Dir, d.Name())) {
854 // Symlinks to directories are not source files.
862 info, err := ctxt.matchFile(p.Dir, name, allTags, &p.BinaryOnly, fset)
863 if err != nil && strings.HasSuffix(name, ".go") {
868 if strings.HasPrefix(name, "_") || strings.HasPrefix(name, ".") {
869 // not due to build constraints - don't report
870 } else if ext == ".go" {
871 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
872 } else if fileListForExt(p, ext) != nil {
873 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, name)
878 // Going to save the file. For non-Go files, can stop here.
883 // special case for cgo, handled at end
884 Sfiles = append(Sfiles, name)
887 if list := fileListForExt(p, ext); list != nil {
888 *list = append(*list, name)
893 data, filename := info.header, info.name
895 if info.parseErr != nil {
896 badGoFile(name, info.parseErr)
897 // Fall through: we might still have a partial AST in info.parsed,
898 // and we want to list files with parse errors anyway.
902 if info.parsed != nil {
903 pkg = info.parsed.Name.Name
904 if pkg == "documentation" {
905 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
910 isTest := strings.HasSuffix(name, "_test.go")
912 if isTest && strings.HasSuffix(pkg, "_test") && p.Name != pkg {
914 pkg = pkg[:len(pkg)-len("_test")]
920 } else if pkg != p.Name {
921 // TODO(#45999): The choice of p.Name is arbitrary based on file iteration
922 // order. Instead of resolving p.Name arbitrarily, we should clear out the
923 // existing name and mark the existing files as also invalid.
924 badGoFile(name, &MultiplePackageError{
926 Packages: []string{p.Name, pkg},
927 Files: []string{firstFile, name},
930 // Grab the first package comment as docs, provided it is not from a test file.
931 if info.parsed != nil && info.parsed.Doc != nil && p.Doc == "" && !isTest && !isXTest {
932 p.Doc = doc.Synopsis(info.parsed.Doc.Text())
935 if mode&ImportComment != 0 {
936 qcom, line := findImportComment(data)
938 com, err := strconv.Unquote(qcom)
940 badGoFile(name, fmt.Errorf("%s:%d: cannot parse import comment", filename, line))
941 } else if p.ImportComment == "" {
942 p.ImportComment = com
943 firstCommentFile = name
944 } else if p.ImportComment != com {
945 badGoFile(name, fmt.Errorf("found import comments %q (%s) and %q (%s) in %s", p.ImportComment, firstCommentFile, com, name, p.Dir))
950 // Record imports and information about cgo.
952 for _, imp := range info.imports {
955 badGoFile(name, fmt.Errorf("use of cgo in test %s not supported", filename))
960 if err := ctxt.saveCgo(filename, p, imp.doc); err != nil {
967 var fileList *[]string
968 var importMap, embedMap map[string][]token.Position
971 allTags["cgo"] = true
973 fileList = &p.CgoFiles
974 importMap = importPos
977 // Ignore imports and embeds from cgo files if cgo is disabled.
978 fileList = &p.IgnoredGoFiles
981 fileList = &p.XTestGoFiles
982 importMap = xTestImportPos
983 embedMap = xTestEmbedPos
985 fileList = &p.TestGoFiles
986 importMap = testImportPos
987 embedMap = testEmbedPos
989 fileList = &p.GoFiles
990 importMap = importPos
993 *fileList = append(*fileList, name)
994 if importMap != nil {
995 for _, imp := range info.imports {
996 importMap[imp.path] = append(importMap[imp.path], fset.Position(imp.pos))
1000 for _, emb := range info.embeds {
1001 embedMap[emb.pattern] = append(embedMap[emb.pattern], emb.pos)
1006 // Now that p.CgoFiles has been set, use it to determine whether
1007 // a package in GOROOT gets an install target:
1008 if len(p.CgoFiles) != 0 && p.Root != "" && p.Goroot && pkga != "" {
1009 p.PkgObj = ctxt.joinPath(p.Root, pkga)
1012 for tag := range allTags {
1013 p.AllTags = append(p.AllTags, tag)
1015 sort.Strings(p.AllTags)
1017 p.EmbedPatterns, p.EmbedPatternPos = cleanDecls(embedPos)
1018 p.TestEmbedPatterns, p.TestEmbedPatternPos = cleanDecls(testEmbedPos)
1019 p.XTestEmbedPatterns, p.XTestEmbedPatternPos = cleanDecls(xTestEmbedPos)
1021 p.Imports, p.ImportPos = cleanDecls(importPos)
1022 p.TestImports, p.TestImportPos = cleanDecls(testImportPos)
1023 p.XTestImports, p.XTestImportPos = cleanDecls(xTestImportPos)
1025 // add the .S/.sx files only if we are using cgo
1026 // (which means gcc will compile them).
1027 // The standard assemblers expect .s files.
1028 if len(p.CgoFiles) > 0 {
1029 p.SFiles = append(p.SFiles, Sfiles...)
1030 sort.Strings(p.SFiles)
1032 p.IgnoredOtherFiles = append(p.IgnoredOtherFiles, Sfiles...)
1033 sort.Strings(p.IgnoredOtherFiles)
1036 if badGoError != nil {
1037 return p, badGoError
1039 if len(p.GoFiles)+len(p.CgoFiles)+len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
1040 return p, &NoGoError{p.Dir}
1045 func fileListForExt(p *Package, ext string) *[]string {
1049 case ".cc", ".cpp", ".cxx":
1053 case ".h", ".hh", ".hpp", ".hxx":
1055 case ".f", ".F", ".for", ".f90":
1057 case ".s", ".S", ".sx":
1062 return &p.SwigCXXFiles
1069 func uniq(list []string) []string {
1073 out := make([]string, len(list))
1077 for _, x := range out {
1078 if len(uniq) == 0 || uniq[len(uniq)-1] != x {
1079 uniq = append(uniq, x)
1085 var errNoModules = errors.New("not using modules")
1087 // importGo checks whether it can use the go command to find the directory for path.
1088 // If using the go command is not appropriate, importGo returns errNoModules.
1089 // Otherwise, importGo tries using the go command and reports whether that succeeded.
1090 // Using the go command lets build.Import and build.Context.Import find code
1091 // in Go modules. In the long term we want tools to use go/packages (currently golang.org/x/tools/go/packages),
1092 // which will also use the go command.
1093 // Invoking the go command here is not very efficient in that it computes information
1094 // about the requested package and all dependencies and then only reports about the requested package.
1095 // Then we reinvoke it for every dependency. But this is still better than not working at all.
1096 // See golang.org/issue/26504.
1097 func (ctxt *Context) importGo(p *Package, path, srcDir string, mode ImportMode) error {
1098 // To invoke the go command,
1099 // we must not being doing special things like AllowBinary or IgnoreVendor,
1100 // and all the file system callbacks must be nil (we're meant to use the local file system).
1101 if mode&AllowBinary != 0 || mode&IgnoreVendor != 0 ||
1102 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) {
1106 // If ctxt.GOROOT is not set, we don't know which go command to invoke,
1107 // and even if we did we might return packages in GOROOT that we wouldn't otherwise find
1108 // (because we don't know to search in 'go env GOROOT' otherwise).
1109 if ctxt.GOROOT == "" {
1113 // Predict whether module aware mode is enabled by checking the value of
1114 // GO111MODULE and looking for a go.mod file in the source directory or
1115 // one of its parents. Running 'go env GOMOD' in the source directory would
1116 // give a canonical answer, but we'd prefer not to execute another command.
1117 go111Module := os.Getenv("GO111MODULE")
1118 switch go111Module {
1121 default: // "", "on", "auto", anything else
1122 // Maybe use modules.
1126 var absSrcDir string
1127 if filepath.IsAbs(srcDir) {
1129 } else if ctxt.Dir != "" {
1130 return fmt.Errorf("go/build: Dir is non-empty, so relative srcDir is not allowed: %v", srcDir)
1132 // Find the absolute source directory. hasSubdir does not handle
1133 // relative paths (and can't because the callbacks don't support this).
1135 absSrcDir, err = filepath.Abs(srcDir)
1141 // If the source directory is in GOROOT, then the in-process code works fine
1142 // and we should keep using it. Moreover, the 'go list' approach below doesn't
1143 // take standard-library vendoring into account and will fail.
1144 if _, ok := ctxt.hasSubdir(filepath.Join(ctxt.GOROOT, "src"), absSrcDir); ok {
1149 // For efficiency, if path is a standard library package, let the usual lookup code handle it.
1150 if dir := ctxt.joinPath(ctxt.GOROOT, "src", path); ctxt.isDir(dir) {
1154 // If GO111MODULE=auto, look to see if there is a go.mod.
1155 // Since go1.13, it doesn't matter if we're inside GOPATH.
1156 if go111Module == "auto" {
1162 parent, err = os.Getwd()
1164 // A nonexistent working directory can't be in a module.
1168 parent, err = filepath.Abs(ctxt.Dir)
1170 // If the caller passed a bogus Dir explicitly, that's materially
1171 // different from not having modules enabled.
1176 if f, err := ctxt.openFile(ctxt.joinPath(parent, "go.mod")); err == nil {
1177 buf := make([]byte, 100)
1178 _, err := f.Read(buf)
1180 if err == nil || err == io.EOF {
1181 // go.mod exists and is readable (is a file, not a directory).
1185 d := filepath.Dir(parent)
1186 if len(d) >= len(parent) {
1187 return errNoModules // reached top of file system, no go.mod
1193 goCmd := filepath.Join(ctxt.GOROOT, "bin", "go")
1194 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)
1200 var stdout, stderr strings.Builder
1201 cmd.Stdout = &stdout
1202 cmd.Stderr = &stderr
1205 if ctxt.CgoEnabled {
1208 cmd.Env = append(cmd.Environ(),
1210 "GOARCH="+ctxt.GOARCH,
1211 "GOROOT="+ctxt.GOROOT,
1212 "GOPATH="+ctxt.GOPATH,
1216 if err := cmd.Run(); err != nil {
1217 return fmt.Errorf("go/build: go list %s: %v\n%s\n", path, err, stderr.String())
1220 f := strings.SplitN(stdout.String(), "\n", 5)
1222 return fmt.Errorf("go/build: importGo %s: unexpected output:\n%s\n", path, stdout.String())
1225 errStr := strings.TrimSpace(f[4])
1226 if errStr != "" && dir == "" {
1227 // If 'go list' could not locate the package (dir is empty),
1228 // return the same error that 'go list' reported.
1229 return errors.New(errStr)
1232 // If 'go list' did locate the package, ignore the error.
1233 // It was probably related to loading source files, and we'll
1234 // encounter it ourselves shortly if the FindOnly flag isn't set.
1238 p.Goroot = f[3] == "true"
1242 func equal(x, y []string) bool {
1243 if len(x) != len(y) {
1246 for i, xi := range x {
1254 // hasGoFiles reports whether dir contains any files with names ending in .go.
1255 // For a vendor check we must exclude directories that contain no .go files.
1256 // Otherwise it is not possible to vendor just a/b/c and still import the
1257 // non-vendored a/b. See golang.org/issue/13832.
1258 func hasGoFiles(ctxt *Context, dir string) bool {
1259 ents, _ := ctxt.readDir(dir)
1260 for _, ent := range ents {
1261 if !ent.IsDir() && strings.HasSuffix(ent.Name(), ".go") {
1268 func findImportComment(data []byte) (s string, line int) {
1269 // expect keyword package
1270 word, data := parseWord(data)
1271 if string(word) != "package" {
1275 // expect package name
1276 _, data = parseWord(data)
1278 // now ready for import comment, a // or /* */ comment
1279 // beginning and ending on the current line.
1280 for len(data) > 0 && (data[0] == ' ' || data[0] == '\t' || data[0] == '\r') {
1286 case bytes.HasPrefix(data, slashSlash):
1287 comment, _, _ = bytes.Cut(data[2:], newline)
1288 case bytes.HasPrefix(data, slashStar):
1290 comment, _, ok = bytes.Cut(data[2:], starSlash)
1292 // malformed comment
1295 if bytes.Contains(comment, newline) {
1299 comment = bytes.TrimSpace(comment)
1301 // split comment into `import`, `"pkg"`
1302 word, arg := parseWord(comment)
1303 if string(word) != "import" {
1307 line = 1 + bytes.Count(data[:cap(data)-cap(arg)], newline)
1308 return strings.TrimSpace(string(arg)), line
1312 slashSlash = []byte("//")
1313 slashStar = []byte("/*")
1314 starSlash = []byte("*/")
1315 newline = []byte("\n")
1318 // skipSpaceOrComment returns data with any leading spaces or comments removed.
1319 func skipSpaceOrComment(data []byte) []byte {
1322 case ' ', '\t', '\r', '\n':
1326 if bytes.HasPrefix(data, slashSlash) {
1327 i := bytes.Index(data, newline)
1334 if bytes.HasPrefix(data, slashStar) {
1336 i := bytes.Index(data, starSlash)
1349 // parseWord skips any leading spaces or comments in data
1350 // and then parses the beginning of data as an identifier or keyword,
1351 // returning that word and what remains after the word.
1352 func parseWord(data []byte) (word, rest []byte) {
1353 data = skipSpaceOrComment(data)
1355 // Parse past leading word characters.
1358 r, size := utf8.DecodeRune(rest)
1359 if unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' {
1366 word = data[:len(data)-len(rest)]
1374 // MatchFile reports whether the file with the given name in the given directory
1375 // matches the context and would be included in a Package created by ImportDir
1376 // of that directory.
1378 // MatchFile considers the name of the file and may use ctxt.OpenFile to
1379 // read some or all of the file's content.
1380 func (ctxt *Context) MatchFile(dir, name string) (match bool, err error) {
1381 info, err := ctxt.matchFile(dir, name, nil, nil, nil)
1382 return info != nil, err
1385 var dummyPkg Package
1387 // fileInfo records information learned about a file included in a build.
1388 type fileInfo struct {
1389 name string // full name including dir
1394 imports []fileImport
1398 type fileImport struct {
1401 doc *ast.CommentGroup
1404 type fileEmbed struct {
1409 // matchFile determines whether the file with the given name in the given directory
1410 // should be included in the package being constructed.
1411 // If the file should be included, matchFile returns a non-nil *fileInfo (and a nil error).
1412 // Non-nil errors are reserved for unexpected problems.
1414 // If name denotes a Go program, matchFile reads until the end of the
1415 // imports and returns that section of the file in the fileInfo's header field,
1416 // even though it only considers text until the first non-comment
1417 // for go:build lines.
1419 // If allTags is non-nil, matchFile records any encountered build tag
1420 // by setting allTags[tag] = true.
1421 func (ctxt *Context) matchFile(dir, name string, allTags map[string]bool, binaryOnly *bool, fset *token.FileSet) (*fileInfo, error) {
1422 if strings.HasPrefix(name, "_") ||
1423 strings.HasPrefix(name, ".") {
1427 i := strings.LastIndex(name, ".")
1433 if ext != ".go" && fileListForExt(&dummyPkg, ext) == nil {
1438 if !ctxt.goodOSArchFile(name, allTags) && !ctxt.UseAllFiles {
1442 info := &fileInfo{name: ctxt.joinPath(dir, name), fset: fset}
1444 // binary, no reading
1448 f, err := ctxt.openFile(info.name)
1453 if strings.HasSuffix(name, ".go") {
1454 err = readGoInfo(f, info)
1455 if strings.HasSuffix(name, "_test.go") {
1456 binaryOnly = nil // ignore //go:binary-only-package comments in _test.go files
1459 binaryOnly = nil // ignore //go:binary-only-package comments in non-Go sources
1460 info.header, err = readComments(f)
1464 return info, fmt.Errorf("read %s: %v", info.name, err)
1467 // Look for go:build comments to accept or reject the file.
1468 ok, sawBinaryOnly, err := ctxt.shouldBuild(info.header, allTags)
1470 return nil, fmt.Errorf("%s: %v", name, err)
1472 if !ok && !ctxt.UseAllFiles {
1476 if binaryOnly != nil && sawBinaryOnly {
1483 func cleanDecls(m map[string][]token.Position) ([]string, map[string][]token.Position) {
1484 all := make([]string, 0, len(m))
1485 for path := range m {
1486 all = append(all, path)
1492 // Import is shorthand for Default.Import.
1493 func Import(path, srcDir string, mode ImportMode) (*Package, error) {
1494 return Default.Import(path, srcDir, mode)
1497 // ImportDir is shorthand for Default.ImportDir.
1498 func ImportDir(dir string, mode ImportMode) (*Package, error) {
1499 return Default.ImportDir(dir, mode)
1503 plusBuild = []byte("+build")
1505 goBuildComment = []byte("//go:build")
1507 errMultipleGoBuild = errors.New("multiple //go:build comments")
1510 func isGoBuildComment(line []byte) bool {
1511 if !bytes.HasPrefix(line, goBuildComment) {
1514 line = bytes.TrimSpace(line)
1515 rest := line[len(goBuildComment):]
1516 return len(rest) == 0 || len(bytes.TrimSpace(rest)) < len(rest)
1519 // Special comment denoting a binary-only package.
1520 // See https://golang.org/design/2775-binary-only-packages
1521 // for more about the design of binary-only packages.
1522 var binaryOnlyComment = []byte("//go:binary-only-package")
1524 // shouldBuild reports whether it is okay to use this file,
1525 // The rule is that in the file's leading run of // comments
1526 // and blank lines, which must be followed by a blank line
1527 // (to avoid including a Go package clause doc comment),
1528 // lines beginning with '//go:build' are taken as build directives.
1530 // The file is accepted only if each such line lists something
1531 // matching the file. For example:
1533 // //go:build windows linux
1535 // marks the file as applicable only on Windows and Linux.
1537 // For each build tag it consults, shouldBuild sets allTags[tag] = true.
1539 // shouldBuild reports whether the file should be built
1540 // and whether a //go:binary-only-package comment was found.
1541 func (ctxt *Context) shouldBuild(content []byte, allTags map[string]bool) (shouldBuild, binaryOnly bool, err error) {
1542 // Identify leading run of // comments and blank lines,
1543 // which must be followed by a blank line.
1544 // Also identify any //go:build comments.
1545 content, goBuild, sawBinaryOnly, err := parseFileHeader(content)
1547 return false, false, err
1550 // If //go:build line is present, it controls.
1551 // Otherwise fall back to +build processing.
1553 case goBuild != nil:
1554 x, err := constraint.Parse(string(goBuild))
1556 return false, false, fmt.Errorf("parsing //go:build line: %v", err)
1558 shouldBuild = ctxt.eval(x, allTags)
1565 if i := bytes.IndexByte(line, '\n'); i >= 0 {
1566 line, p = line[:i], p[i+1:]
1570 line = bytes.TrimSpace(line)
1571 if !bytes.HasPrefix(line, slashSlash) || !bytes.Contains(line, plusBuild) {
1574 text := string(line)
1575 if !constraint.IsPlusBuild(text) {
1578 if x, err := constraint.Parse(text); err == nil {
1579 if !ctxt.eval(x, allTags) {
1586 return shouldBuild, sawBinaryOnly, nil
1589 func parseFileHeader(content []byte) (trimmed, goBuild []byte, sawBinaryOnly bool, err error) {
1592 ended := false // found non-blank, non-// line, so stopped accepting //go:build lines
1593 inSlashStar := false // in /* */ comment
1598 if i := bytes.IndexByte(line, '\n'); i >= 0 {
1599 line, p = line[:i], p[i+1:]
1603 line = bytes.TrimSpace(line)
1604 if len(line) == 0 && !ended { // Blank line
1605 // Remember position of most recent blank line.
1606 // When we find the first non-blank, non-// line,
1607 // this "end" position marks the latest file position
1608 // where a //go:build line can appear.
1609 // (It must appear _before_ a blank line before the non-blank, non-// line.
1610 // Yes, that's confusing, which is part of why we moved to //go:build lines.)
1611 // Note that ended==false here means that inSlashStar==false,
1612 // since seeing a /* would have set ended==true.
1613 end = len(content) - len(p)
1616 if !bytes.HasPrefix(line, slashSlash) { // Not comment line
1620 if !inSlashStar && isGoBuildComment(line) {
1622 return nil, nil, false, errMultipleGoBuild
1626 if !inSlashStar && bytes.Equal(line, binaryOnlyComment) {
1627 sawBinaryOnly = true
1633 if i := bytes.Index(line, starSlash); i >= 0 {
1635 line = bytes.TrimSpace(line[i+len(starSlash):])
1640 if bytes.HasPrefix(line, slashSlash) {
1643 if bytes.HasPrefix(line, slashStar) {
1645 line = bytes.TrimSpace(line[len(slashStar):])
1648 // Found non-comment text.
1653 return content[:end], goBuild, sawBinaryOnly, nil
1656 // saveCgo saves the information from the #cgo lines in the import "C" comment.
1657 // These lines set CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS and pkg-config directives
1658 // that affect the way cgo's C code is built.
1659 func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error {
1661 for _, line := range strings.Split(text, "\n") {
1665 // #cgo [GOOS/GOARCH...] LDFLAGS: stuff
1667 line = strings.TrimSpace(line)
1668 if len(line) < 5 || line[:4] != "#cgo" || (line[4] != ' ' && line[4] != '\t') {
1673 line, argstr, ok := strings.Cut(strings.TrimSpace(line[4:]), ":")
1675 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1678 // Parse GOOS/GOARCH stuff.
1679 f := strings.Fields(line)
1681 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1684 cond, verb := f[:len(f)-1], f[len(f)-1]
1687 for _, c := range cond {
1688 if ctxt.matchAuto(c, nil) {
1698 args, err := splitQuoted(argstr)
1700 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
1702 for i, arg := range args {
1703 if arg, ok = expandSrcDir(arg, di.Dir); !ok {
1704 return fmt.Errorf("%s: malformed #cgo argument: %s", filename, arg)
1710 case "CFLAGS", "CPPFLAGS", "CXXFLAGS", "FFLAGS", "LDFLAGS":
1711 // Change relative paths to absolute.
1712 ctxt.makePathsAbsolute(args, di.Dir)
1717 di.CgoCFLAGS = append(di.CgoCFLAGS, args...)
1719 di.CgoCPPFLAGS = append(di.CgoCPPFLAGS, args...)
1721 di.CgoCXXFLAGS = append(di.CgoCXXFLAGS, args...)
1723 di.CgoFFLAGS = append(di.CgoFFLAGS, args...)
1725 di.CgoLDFLAGS = append(di.CgoLDFLAGS, args...)
1727 di.CgoPkgConfig = append(di.CgoPkgConfig, args...)
1729 return fmt.Errorf("%s: invalid #cgo verb: %s", filename, orig)
1735 // expandSrcDir expands any occurrence of ${SRCDIR}, making sure
1736 // the result is safe for the shell.
1737 func expandSrcDir(str string, srcdir string) (string, bool) {
1738 // "\" delimited paths cause safeCgoName to fail
1739 // so convert native paths with a different delimiter
1740 // to "/" before starting (eg: on windows).
1741 srcdir = filepath.ToSlash(srcdir)
1743 chunks := strings.Split(str, "${SRCDIR}")
1744 if len(chunks) < 2 {
1745 return str, safeCgoName(str)
1748 for _, chunk := range chunks {
1749 ok = ok && (chunk == "" || safeCgoName(chunk))
1751 ok = ok && (srcdir == "" || safeCgoName(srcdir))
1752 res := strings.Join(chunks, srcdir)
1753 return res, ok && res != ""
1756 // makePathsAbsolute looks for compiler options that take paths and
1757 // makes them absolute. We do this because through the 1.8 release we
1758 // ran the compiler in the package directory, so any relative -I or -L
1759 // options would be relative to that directory. In 1.9 we changed to
1760 // running the compiler in the build directory, to get consistent
1761 // build results (issue #19964). To keep builds working, we change any
1762 // relative -I or -L options to be absolute.
1764 // Using filepath.IsAbs and filepath.Join here means the results will be
1765 // different on different systems, but that's OK: -I and -L options are
1766 // inherently system-dependent.
1767 func (ctxt *Context) makePathsAbsolute(args []string, srcDir string) {
1769 for i, arg := range args {
1771 if !filepath.IsAbs(arg) {
1772 args[i] = filepath.Join(srcDir, arg)
1775 } else if strings.HasPrefix(arg, "-I") || strings.HasPrefix(arg, "-L") {
1779 if !filepath.IsAbs(arg[2:]) {
1780 args[i] = arg[:2] + filepath.Join(srcDir, arg[2:])
1787 // NOTE: $ is not safe for the shell, but it is allowed here because of linker options like -Wl,$ORIGIN.
1788 // We never pass these arguments to a shell (just to programs we construct argv for), so this should be okay.
1789 // See golang.org/issue/6038.
1790 // The @ is for OS X. See golang.org/issue/13720.
1791 // The % is for Jenkins. See golang.org/issue/16959.
1792 // The ! is because module paths may use them. See golang.org/issue/26716.
1793 // The ~ and ^ are for sr.ht. See golang.org/issue/32260.
1794 const safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$@%! ~^"
1796 func safeCgoName(s string) bool {
1800 for i := 0; i < len(s); i++ {
1801 if c := s[i]; c < utf8.RuneSelf && strings.IndexByte(safeString, c) < 0 {
1808 // splitQuoted splits the string s around each instance of one or more consecutive
1809 // white space characters while taking into account quotes and escaping, and
1810 // returns an array of substrings of s or an empty list if s contains only white space.
1811 // Single quotes and double quotes are recognized to prevent splitting within the
1812 // quoted region, and are removed from the resulting substrings. If a quote in s
1813 // isn't closed err will be set and r will have the unclosed argument as the
1814 // last element. The backslash is used for escaping.
1816 // For example, the following string:
1818 // a b:"c d" 'e''f' "g\""
1820 // Would be parsed as:
1822 // []string{"a", "b:c d", "ef", `g"`}
1823 func splitQuoted(s string) (r []string, err error) {
1825 arg := make([]rune, len(s))
1830 for _, rune := range s {
1837 case quote != '\x00':
1842 case rune == '"' || rune == '\'':
1846 case unicode.IsSpace(rune):
1847 if quoted || i > 0 {
1849 args = append(args, string(arg[:i]))
1857 if quoted || i > 0 {
1858 args = append(args, string(arg[:i]))
1861 err = errors.New("unclosed quote")
1863 err = errors.New("unfinished escaping")
1868 // matchAuto interprets text as either a +build or //go:build expression (whichever works),
1869 // reporting whether the expression matches the build context.
1871 // matchAuto is only used for testing of tag evaluation
1872 // and in #cgo lines, which accept either syntax.
1873 func (ctxt *Context) matchAuto(text string, allTags map[string]bool) bool {
1874 if strings.ContainsAny(text, "&|()") {
1875 text = "//go:build " + text
1877 text = "// +build " + text
1879 x, err := constraint.Parse(text)
1883 return ctxt.eval(x, allTags)
1886 func (ctxt *Context) eval(x constraint.Expr, allTags map[string]bool) bool {
1887 return x.Eval(func(tag string) bool { return ctxt.matchTag(tag, allTags) })
1890 // matchTag reports whether the name is one of:
1892 // cgo (if cgo is enabled)
1896 // linux (if GOOS = android)
1897 // solaris (if GOOS = illumos)
1898 // darwin (if GOOS = ios)
1899 // unix (if this is a Unix GOOS)
1900 // boringcrypto (if GOEXPERIMENT=boringcrypto is enabled)
1901 // tag (if tag is listed in ctxt.BuildTags, ctxt.ToolTags, or ctxt.ReleaseTags)
1903 // It records all consulted tags in allTags.
1904 func (ctxt *Context) matchTag(name string, allTags map[string]bool) bool {
1906 allTags[name] = true
1910 if ctxt.CgoEnabled && name == "cgo" {
1913 if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler {
1916 if ctxt.GOOS == "android" && name == "linux" {
1919 if ctxt.GOOS == "illumos" && name == "solaris" {
1922 if ctxt.GOOS == "ios" && name == "darwin" {
1925 if name == "unix" && unixOS[ctxt.GOOS] {
1928 if name == "boringcrypto" {
1929 name = "goexperiment.boringcrypto" // boringcrypto is an old name for goexperiment.boringcrypto
1933 for _, tag := range ctxt.BuildTags {
1938 for _, tag := range ctxt.ToolTags {
1943 for _, tag := range ctxt.ReleaseTags {
1952 // goodOSArchFile returns false if the name contains a $GOOS or $GOARCH
1953 // suffix which does not match the current system.
1954 // The recognized name formats are:
1958 // name_$(GOOS)_$(GOARCH).*
1959 // name_$(GOOS)_test.*
1960 // name_$(GOARCH)_test.*
1961 // name_$(GOOS)_$(GOARCH)_test.*
1964 // if GOOS=android, then files with GOOS=linux are also matched.
1965 // if GOOS=illumos, then files with GOOS=solaris are also matched.
1966 // if GOOS=ios, then files with GOOS=darwin are also matched.
1967 func (ctxt *Context) goodOSArchFile(name string, allTags map[string]bool) bool {
1968 name, _, _ = strings.Cut(name, ".")
1970 // Before Go 1.4, a file called "linux.go" would be equivalent to having a
1971 // build tag "linux" in that file. For Go 1.4 and beyond, we require this
1972 // auto-tagging to apply only to files with a non-empty prefix, so
1973 // "foo_linux.go" is tagged but "linux.go" is not. This allows new operating
1974 // systems, such as android, to arrive without breaking existing code with
1975 // innocuous source code in "android.go". The easiest fix: cut everything
1976 // in the name before the initial _.
1977 i := strings.Index(name, "_")
1981 name = name[i:] // ignore everything before first _
1983 l := strings.Split(name, "_")
1984 if n := len(l); n > 0 && l[n-1] == "test" {
1988 if n >= 2 && knownOS[l[n-2]] && knownArch[l[n-1]] {
1990 // In case we short-circuit on l[n-1].
1991 allTags[l[n-2]] = true
1993 return ctxt.matchTag(l[n-1], allTags) && ctxt.matchTag(l[n-2], allTags)
1995 if n >= 1 && (knownOS[l[n-1]] || knownArch[l[n-1]]) {
1996 return ctxt.matchTag(l[n-1], allTags)
2001 // ToolDir is the directory containing build tools.
2002 var ToolDir = getToolDir()
2004 // IsLocalImport reports whether the import path is
2005 // a local import path, like ".", "..", "./foo", or "../foo".
2006 func IsLocalImport(path string) bool {
2007 return path == "." || path == ".." ||
2008 strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../")
2011 // ArchChar returns "?" and an error.
2012 // In earlier versions of Go, the returned string was used to derive
2013 // the compiler and linker tool names, the default object file suffix,
2014 // and the default linker output name. As of Go 1.5, those strings
2015 // no longer vary by architecture; they are compile, link, .o, and a.out, respectively.
2016 func ArchChar(goarch string) (string, error) {
2017 return "?", errors.New("architecture letter no longer used")