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

View as plain text