Source file src/cmd/go/internal/load/pkg.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 load loads packages.
     6  package load
     7  
     8  import (
     9  	"bytes"
    10  	"context"
    11  	"encoding/json"
    12  	"errors"
    13  	"fmt"
    14  	"go/build"
    15  	"go/scanner"
    16  	"go/token"
    17  	"internal/goroot"
    18  	"io/fs"
    19  	"os"
    20  	"os/exec"
    21  	"path"
    22  	pathpkg "path"
    23  	"path/filepath"
    24  	"runtime"
    25  	"runtime/debug"
    26  	"sort"
    27  	"strconv"
    28  	"strings"
    29  	"time"
    30  	"unicode"
    31  	"unicode/utf8"
    32  
    33  	"cmd/go/internal/base"
    34  	"cmd/go/internal/cfg"
    35  	"cmd/go/internal/fsys"
    36  	"cmd/go/internal/imports"
    37  	"cmd/go/internal/modfetch"
    38  	"cmd/go/internal/modinfo"
    39  	"cmd/go/internal/modload"
    40  	"cmd/go/internal/par"
    41  	"cmd/go/internal/search"
    42  	"cmd/go/internal/str"
    43  	"cmd/go/internal/trace"
    44  	"cmd/go/internal/vcs"
    45  	"cmd/internal/sys"
    46  
    47  	"golang.org/x/mod/modfile"
    48  	"golang.org/x/mod/module"
    49  )
    50  
    51  // A Package describes a single package found in a directory.
    52  type Package struct {
    53  	PackagePublic                 // visible in 'go list'
    54  	Internal      PackageInternal // for use inside go command only
    55  }
    56  
    57  type PackagePublic struct {
    58  	// Note: These fields are part of the go command's public API.
    59  	// See list.go. It is okay to add fields, but not to change or
    60  	// remove existing ones. Keep in sync with list.go
    61  	Dir           string                `json:",omitempty"` // directory containing package sources
    62  	ImportPath    string                `json:",omitempty"` // import path of package in dir
    63  	ImportComment string                `json:",omitempty"` // path in import comment on package statement
    64  	Name          string                `json:",omitempty"` // package name
    65  	Doc           string                `json:",omitempty"` // package documentation string
    66  	Target        string                `json:",omitempty"` // installed target for this package (may be executable)
    67  	Shlib         string                `json:",omitempty"` // the shared library that contains this package (only set when -linkshared)
    68  	Root          string                `json:",omitempty"` // Go root, Go path dir, or module root dir containing this package
    69  	ConflictDir   string                `json:",omitempty"` // Dir is hidden by this other directory
    70  	ForTest       string                `json:",omitempty"` // package is only for use in named test
    71  	Export        string                `json:",omitempty"` // file containing export data (set by go list -export)
    72  	BuildID       string                `json:",omitempty"` // build ID of the compiled package (set by go list -export)
    73  	Module        *modinfo.ModulePublic `json:",omitempty"` // info about package's module, if any
    74  	Match         []string              `json:",omitempty"` // command-line patterns matching this package
    75  	Goroot        bool                  `json:",omitempty"` // is this package found in the Go root?
    76  	Standard      bool                  `json:",omitempty"` // is this package part of the standard Go library?
    77  	DepOnly       bool                  `json:",omitempty"` // package is only as a dependency, not explicitly listed
    78  	BinaryOnly    bool                  `json:",omitempty"` // package cannot be recompiled
    79  	Incomplete    bool                  `json:",omitempty"` // was there an error loading this package or dependencies?
    80  
    81  	// Stale and StaleReason remain here *only* for the list command.
    82  	// They are only initialized in preparation for list execution.
    83  	// The regular build determines staleness on the fly during action execution.
    84  	Stale       bool   `json:",omitempty"` // would 'go install' do anything for this package?
    85  	StaleReason string `json:",omitempty"` // why is Stale true?
    86  
    87  	// Source files
    88  	// If you add to this list you MUST add to p.AllFiles (below) too.
    89  	// Otherwise file name security lists will not apply to any new additions.
    90  	GoFiles           []string `json:",omitempty"` // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
    91  	CgoFiles          []string `json:",omitempty"` // .go source files that import "C"
    92  	CompiledGoFiles   []string `json:",omitempty"` // .go output from running cgo on CgoFiles
    93  	IgnoredGoFiles    []string `json:",omitempty"` // .go source files ignored due to build constraints
    94  	InvalidGoFiles    []string `json:",omitempty"` // .go source files with detected problems (parse error, wrong package name, and so on)
    95  	IgnoredOtherFiles []string `json:",omitempty"` // non-.go source files ignored due to build constraints
    96  	CFiles            []string `json:",omitempty"` // .c source files
    97  	CXXFiles          []string `json:",omitempty"` // .cc, .cpp and .cxx source files
    98  	MFiles            []string `json:",omitempty"` // .m source files
    99  	HFiles            []string `json:",omitempty"` // .h, .hh, .hpp and .hxx source files
   100  	FFiles            []string `json:",omitempty"` // .f, .F, .for and .f90 Fortran source files
   101  	SFiles            []string `json:",omitempty"` // .s source files
   102  	SwigFiles         []string `json:",omitempty"` // .swig files
   103  	SwigCXXFiles      []string `json:",omitempty"` // .swigcxx files
   104  	SysoFiles         []string `json:",omitempty"` // .syso system object files added to package
   105  
   106  	// Embedded files
   107  	EmbedPatterns []string `json:",omitempty"` // //go:embed patterns
   108  	EmbedFiles    []string `json:",omitempty"` // files matched by EmbedPatterns
   109  
   110  	// Cgo directives
   111  	CgoCFLAGS    []string `json:",omitempty"` // cgo: flags for C compiler
   112  	CgoCPPFLAGS  []string `json:",omitempty"` // cgo: flags for C preprocessor
   113  	CgoCXXFLAGS  []string `json:",omitempty"` // cgo: flags for C++ compiler
   114  	CgoFFLAGS    []string `json:",omitempty"` // cgo: flags for Fortran compiler
   115  	CgoLDFLAGS   []string `json:",omitempty"` // cgo: flags for linker
   116  	CgoPkgConfig []string `json:",omitempty"` // cgo: pkg-config names
   117  
   118  	// Dependency information
   119  	Imports   []string          `json:",omitempty"` // import paths used by this package
   120  	ImportMap map[string]string `json:",omitempty"` // map from source import to ImportPath (identity entries omitted)
   121  	Deps      []string          `json:",omitempty"` // all (recursively) imported dependencies
   122  
   123  	// Error information
   124  	// Incomplete is above, packed into the other bools
   125  	Error      *PackageError   `json:",omitempty"` // error loading this package (not dependencies)
   126  	DepsErrors []*PackageError `json:",omitempty"` // errors loading dependencies
   127  
   128  	// Test information
   129  	// If you add to this list you MUST add to p.AllFiles (below) too.
   130  	// Otherwise file name security lists will not apply to any new additions.
   131  	TestGoFiles        []string `json:",omitempty"` // _test.go files in package
   132  	TestImports        []string `json:",omitempty"` // imports from TestGoFiles
   133  	TestEmbedPatterns  []string `json:",omitempty"` // //go:embed patterns
   134  	TestEmbedFiles     []string `json:",omitempty"` // files matched by TestEmbedPatterns
   135  	XTestGoFiles       []string `json:",omitempty"` // _test.go files outside package
   136  	XTestImports       []string `json:",omitempty"` // imports from XTestGoFiles
   137  	XTestEmbedPatterns []string `json:",omitempty"` // //go:embed patterns
   138  	XTestEmbedFiles    []string `json:",omitempty"` // files matched by XTestEmbedPatterns
   139  }
   140  
   141  // AllFiles returns the names of all the files considered for the package.
   142  // This is used for sanity and security checks, so we include all files,
   143  // even IgnoredGoFiles, because some subcommands consider them.
   144  // The go/build package filtered others out (like foo_wrongGOARCH.s)
   145  // and that's OK.
   146  func (p *Package) AllFiles() []string {
   147  	files := str.StringList(
   148  		p.GoFiles,
   149  		p.CgoFiles,
   150  		// no p.CompiledGoFiles, because they are from GoFiles or generated by us
   151  		p.IgnoredGoFiles,
   152  		// no p.InvalidGoFiles, because they are from GoFiles
   153  		p.IgnoredOtherFiles,
   154  		p.CFiles,
   155  		p.CXXFiles,
   156  		p.MFiles,
   157  		p.HFiles,
   158  		p.FFiles,
   159  		p.SFiles,
   160  		p.SwigFiles,
   161  		p.SwigCXXFiles,
   162  		p.SysoFiles,
   163  		p.TestGoFiles,
   164  		p.XTestGoFiles,
   165  	)
   166  
   167  	// EmbedFiles may overlap with the other files.
   168  	// Dedup, but delay building the map as long as possible.
   169  	// Only files in the current directory (no slash in name)
   170  	// need to be checked against the files variable above.
   171  	var have map[string]bool
   172  	for _, file := range p.EmbedFiles {
   173  		if !strings.Contains(file, "/") {
   174  			if have == nil {
   175  				have = make(map[string]bool)
   176  				for _, file := range files {
   177  					have[file] = true
   178  				}
   179  			}
   180  			if have[file] {
   181  				continue
   182  			}
   183  		}
   184  		files = append(files, file)
   185  	}
   186  	return files
   187  }
   188  
   189  // Desc returns the package "description", for use in b.showOutput.
   190  func (p *Package) Desc() string {
   191  	if p.ForTest != "" {
   192  		return p.ImportPath + " [" + p.ForTest + ".test]"
   193  	}
   194  	return p.ImportPath
   195  }
   196  
   197  // IsTestOnly reports whether p is a test-only package.
   198  //
   199  // A “test-only” package is one that:
   200  //   - is a test-only variant of an ordinary package, or
   201  //   - is a synthesized "main" package for a test binary, or
   202  //   - contains only _test.go files.
   203  func (p *Package) IsTestOnly() bool {
   204  	return p.ForTest != "" ||
   205  		p.Internal.TestmainGo != nil ||
   206  		len(p.TestGoFiles)+len(p.XTestGoFiles) > 0 && len(p.GoFiles)+len(p.CgoFiles) == 0
   207  }
   208  
   209  type PackageInternal struct {
   210  	// Unexported fields are not part of the public API.
   211  	Build             *build.Package
   212  	Imports           []*Package           // this package's direct imports
   213  	CompiledImports   []string             // additional Imports necessary when using CompiledGoFiles (all from standard library); 1:1 with the end of PackagePublic.Imports
   214  	RawImports        []string             // this package's original imports as they appear in the text of the program; 1:1 with the end of PackagePublic.Imports
   215  	ForceLibrary      bool                 // this package is a library (even if named "main")
   216  	CmdlineFiles      bool                 // package built from files listed on command line
   217  	CmdlinePkg        bool                 // package listed on command line
   218  	CmdlinePkgLiteral bool                 // package listed as literal on command line (not via wildcard)
   219  	Local             bool                 // imported via local path (./ or ../)
   220  	LocalPrefix       string               // interpret ./ and ../ imports relative to this prefix
   221  	ExeName           string               // desired name for temporary executable
   222  	FuzzInstrument    bool                 // package should be instrumented for fuzzing
   223  	CoverMode         string               // preprocess Go source files with the coverage tool in this mode
   224  	CoverVars         map[string]*CoverVar // variables created by coverage analysis
   225  	OmitDebug         bool                 // tell linker not to write debug information
   226  	GobinSubdir       bool                 // install target would be subdir of GOBIN
   227  	BuildInfo         string               // add this info to package main
   228  	TestmainGo        *[]byte              // content for _testmain.go
   229  	Embed             map[string][]string  // //go:embed comment mapping
   230  	OrigImportPath    string               // original import path before adding '_test' suffix
   231  
   232  	Asmflags   []string // -asmflags for this package
   233  	Gcflags    []string // -gcflags for this package
   234  	Ldflags    []string // -ldflags for this package
   235  	Gccgoflags []string // -gccgoflags for this package
   236  }
   237  
   238  // A NoGoError indicates that no Go files for the package were applicable to the
   239  // build for that package.
   240  //
   241  // That may be because there were no files whatsoever, or because all files were
   242  // excluded, or because all non-excluded files were test sources.
   243  type NoGoError struct {
   244  	Package *Package
   245  }
   246  
   247  func (e *NoGoError) Error() string {
   248  	if len(e.Package.IgnoredGoFiles) > 0 {
   249  		// Go files exist, but they were ignored due to build constraints.
   250  		return "build constraints exclude all Go files in " + e.Package.Dir
   251  	}
   252  	if len(e.Package.TestGoFiles)+len(e.Package.XTestGoFiles) > 0 {
   253  		// Test Go files exist, but we're not interested in them.
   254  		// The double-negative is unfortunate but we want e.Package.Dir
   255  		// to appear at the end of error message.
   256  		return "no non-test Go files in " + e.Package.Dir
   257  	}
   258  	return "no Go files in " + e.Package.Dir
   259  }
   260  
   261  // setLoadPackageDataError presents an error found when loading package data
   262  // as a *PackageError. It has special cases for some common errors to improve
   263  // messages shown to users and reduce redundancy.
   264  //
   265  // setLoadPackageDataError returns true if it's safe to load information about
   266  // imported packages, for example, if there was a parse error loading imports
   267  // in one file, but other files are okay.
   268  func (p *Package) setLoadPackageDataError(err error, path string, stk *ImportStack, importPos []token.Position) {
   269  	matchErr, isMatchErr := err.(*search.MatchError)
   270  	if isMatchErr && matchErr.Match.Pattern() == path {
   271  		if matchErr.Match.IsLiteral() {
   272  			// The error has a pattern has a pattern similar to the import path.
   273  			// It may be slightly different (./foo matching example.com/foo),
   274  			// but close enough to seem redundant.
   275  			// Unwrap the error so we don't show the pattern.
   276  			err = matchErr.Err
   277  		}
   278  	}
   279  
   280  	// Replace (possibly wrapped) *build.NoGoError with *load.NoGoError.
   281  	// The latter is more specific about the cause.
   282  	var nogoErr *build.NoGoError
   283  	if errors.As(err, &nogoErr) {
   284  		if p.Dir == "" && nogoErr.Dir != "" {
   285  			p.Dir = nogoErr.Dir
   286  		}
   287  		err = &NoGoError{Package: p}
   288  	}
   289  
   290  	// Take only the first error from a scanner.ErrorList. PackageError only
   291  	// has room for one position, so we report the first error with a position
   292  	// instead of all of the errors without a position.
   293  	var pos string
   294  	var isScanErr bool
   295  	if scanErr, ok := err.(scanner.ErrorList); ok && len(scanErr) > 0 {
   296  		isScanErr = true // For stack push/pop below.
   297  
   298  		scanPos := scanErr[0].Pos
   299  		scanPos.Filename = base.ShortPath(scanPos.Filename)
   300  		pos = scanPos.String()
   301  		err = errors.New(scanErr[0].Msg)
   302  	}
   303  
   304  	// Report the error on the importing package if the problem is with the import declaration
   305  	// for example, if the package doesn't exist or if the import path is malformed.
   306  	// On the other hand, don't include a position if the problem is with the imported package,
   307  	// for example there are no Go files (NoGoError), or there's a problem in the imported
   308  	// package's source files themselves (scanner errors).
   309  	//
   310  	// TODO(matloob): Perhaps make each of those the errors in the first group
   311  	// (including modload.ImportMissingError, ImportMissingSumError, and the
   312  	// corresponding "cannot find package %q in any of" GOPATH-mode error
   313  	// produced in build.(*Context).Import; modload.AmbiguousImportError,
   314  	// and modload.PackageNotInModuleError; and the malformed module path errors
   315  	// produced in golang.org/x/mod/module.CheckMod) implement an interface
   316  	// to make it easier to check for them? That would save us from having to
   317  	// move the modload errors into this package to avoid a package import cycle,
   318  	// and from having to export an error type for the errors produced in build.
   319  	if !isMatchErr && (nogoErr != nil || isScanErr) {
   320  		stk.Push(path)
   321  		defer stk.Pop()
   322  	}
   323  
   324  	p.Error = &PackageError{
   325  		ImportStack: stk.Copy(),
   326  		Pos:         pos,
   327  		Err:         err,
   328  	}
   329  
   330  	if path != stk.Top() {
   331  		p.Error.setPos(importPos)
   332  	}
   333  }
   334  
   335  // Resolve returns the resolved version of imports,
   336  // which should be p.TestImports or p.XTestImports, NOT p.Imports.
   337  // The imports in p.TestImports and p.XTestImports are not recursively
   338  // loaded during the initial load of p, so they list the imports found in
   339  // the source file, but most processing should be over the vendor-resolved
   340  // import paths. We do this resolution lazily both to avoid file system work
   341  // and because the eventual real load of the test imports (during 'go test')
   342  // can produce better error messages if it starts with the original paths.
   343  // The initial load of p loads all the non-test imports and rewrites
   344  // the vendored paths, so nothing should ever call p.vendored(p.Imports).
   345  func (p *Package) Resolve(imports []string) []string {
   346  	if len(imports) > 0 && len(p.Imports) > 0 && &imports[0] == &p.Imports[0] {
   347  		panic("internal error: p.Resolve(p.Imports) called")
   348  	}
   349  	seen := make(map[string]bool)
   350  	var all []string
   351  	for _, path := range imports {
   352  		path = ResolveImportPath(p, path)
   353  		if !seen[path] {
   354  			seen[path] = true
   355  			all = append(all, path)
   356  		}
   357  	}
   358  	sort.Strings(all)
   359  	return all
   360  }
   361  
   362  // CoverVar holds the name of the generated coverage variables targeting the named file.
   363  type CoverVar struct {
   364  	File string // local file name
   365  	Var  string // name of count struct
   366  }
   367  
   368  func (p *Package) copyBuild(opts PackageOpts, pp *build.Package) {
   369  	p.Internal.Build = pp
   370  
   371  	if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
   372  		old := pp.PkgTargetRoot
   373  		pp.PkgRoot = cfg.BuildPkgdir
   374  		pp.PkgTargetRoot = cfg.BuildPkgdir
   375  		pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
   376  	}
   377  
   378  	p.Dir = pp.Dir
   379  	p.ImportPath = pp.ImportPath
   380  	p.ImportComment = pp.ImportComment
   381  	p.Name = pp.Name
   382  	p.Doc = pp.Doc
   383  	p.Root = pp.Root
   384  	p.ConflictDir = pp.ConflictDir
   385  	p.BinaryOnly = pp.BinaryOnly
   386  
   387  	// TODO? Target
   388  	p.Goroot = pp.Goroot
   389  	p.Standard = p.Goroot && p.ImportPath != "" && search.IsStandardImportPath(p.ImportPath)
   390  	p.GoFiles = pp.GoFiles
   391  	p.CgoFiles = pp.CgoFiles
   392  	p.IgnoredGoFiles = pp.IgnoredGoFiles
   393  	p.InvalidGoFiles = pp.InvalidGoFiles
   394  	p.IgnoredOtherFiles = pp.IgnoredOtherFiles
   395  	p.CFiles = pp.CFiles
   396  	p.CXXFiles = pp.CXXFiles
   397  	p.MFiles = pp.MFiles
   398  	p.HFiles = pp.HFiles
   399  	p.FFiles = pp.FFiles
   400  	p.SFiles = pp.SFiles
   401  	p.SwigFiles = pp.SwigFiles
   402  	p.SwigCXXFiles = pp.SwigCXXFiles
   403  	p.SysoFiles = pp.SysoFiles
   404  	p.CgoCFLAGS = pp.CgoCFLAGS
   405  	p.CgoCPPFLAGS = pp.CgoCPPFLAGS
   406  	p.CgoCXXFLAGS = pp.CgoCXXFLAGS
   407  	p.CgoFFLAGS = pp.CgoFFLAGS
   408  	p.CgoLDFLAGS = pp.CgoLDFLAGS
   409  	p.CgoPkgConfig = pp.CgoPkgConfig
   410  	// We modify p.Imports in place, so make copy now.
   411  	p.Imports = make([]string, len(pp.Imports))
   412  	copy(p.Imports, pp.Imports)
   413  	p.Internal.RawImports = pp.Imports
   414  	p.TestGoFiles = pp.TestGoFiles
   415  	p.TestImports = pp.TestImports
   416  	p.XTestGoFiles = pp.XTestGoFiles
   417  	p.XTestImports = pp.XTestImports
   418  	if opts.IgnoreImports {
   419  		p.Imports = nil
   420  		p.Internal.RawImports = nil
   421  		p.TestImports = nil
   422  		p.XTestImports = nil
   423  	}
   424  	p.EmbedPatterns = pp.EmbedPatterns
   425  	p.TestEmbedPatterns = pp.TestEmbedPatterns
   426  	p.XTestEmbedPatterns = pp.XTestEmbedPatterns
   427  	p.Internal.OrigImportPath = pp.ImportPath
   428  }
   429  
   430  // A PackageError describes an error loading information about a package.
   431  type PackageError struct {
   432  	ImportStack      []string // shortest path from package named on command line to this one
   433  	Pos              string   // position of error
   434  	Err              error    // the error itself
   435  	IsImportCycle    bool     // the error is an import cycle
   436  	Hard             bool     // whether the error is soft or hard; soft errors are ignored in some places
   437  	alwaysPrintStack bool     // whether to always print the ImportStack
   438  }
   439  
   440  func (p *PackageError) Error() string {
   441  	// TODO(#43696): decide when to print the stack or the position based on
   442  	// the error type and whether the package is in the main module.
   443  	// Document the rationale.
   444  	if p.Pos != "" && (len(p.ImportStack) == 0 || !p.alwaysPrintStack) {
   445  		// Omit import stack. The full path to the file where the error
   446  		// is the most important thing.
   447  		return p.Pos + ": " + p.Err.Error()
   448  	}
   449  
   450  	// If the error is an ImportPathError, and the last path on the stack appears
   451  	// in the error message, omit that path from the stack to avoid repetition.
   452  	// If an ImportPathError wraps another ImportPathError that matches the
   453  	// last path on the stack, we don't omit the path. An error like
   454  	// "package A imports B: error loading C caused by B" would not be clearer
   455  	// if "imports B" were omitted.
   456  	if len(p.ImportStack) == 0 {
   457  		return p.Err.Error()
   458  	}
   459  	var optpos string
   460  	if p.Pos != "" {
   461  		optpos = "\n\t" + p.Pos
   462  	}
   463  	return "package " + strings.Join(p.ImportStack, "\n\timports ") + optpos + ": " + p.Err.Error()
   464  }
   465  
   466  func (p *PackageError) Unwrap() error { return p.Err }
   467  
   468  // PackageError implements MarshalJSON so that Err is marshaled as a string
   469  // and non-essential fields are omitted.
   470  func (p *PackageError) MarshalJSON() ([]byte, error) {
   471  	perr := struct {
   472  		ImportStack []string
   473  		Pos         string
   474  		Err         string
   475  	}{p.ImportStack, p.Pos, p.Err.Error()}
   476  	return json.Marshal(perr)
   477  }
   478  
   479  func (p *PackageError) setPos(posList []token.Position) {
   480  	if len(posList) == 0 {
   481  		return
   482  	}
   483  	pos := posList[0]
   484  	pos.Filename = base.ShortPath(pos.Filename)
   485  	p.Pos = pos.String()
   486  }
   487  
   488  // ImportPathError is a type of error that prevents a package from being loaded
   489  // for a given import path. When such a package is loaded, a *Package is
   490  // returned with Err wrapping an ImportPathError: the error is attached to
   491  // the imported package, not the importing package.
   492  //
   493  // The string returned by ImportPath must appear in the string returned by
   494  // Error. Errors that wrap ImportPathError (such as PackageError) may omit
   495  // the import path.
   496  type ImportPathError interface {
   497  	error
   498  	ImportPath() string
   499  }
   500  
   501  var (
   502  	_ ImportPathError = (*importError)(nil)
   503  	_ ImportPathError = (*mainPackageError)(nil)
   504  	_ ImportPathError = (*modload.ImportMissingError)(nil)
   505  	_ ImportPathError = (*modload.ImportMissingSumError)(nil)
   506  	_ ImportPathError = (*modload.DirectImportFromImplicitDependencyError)(nil)
   507  )
   508  
   509  type importError struct {
   510  	importPath string
   511  	err        error // created with fmt.Errorf
   512  }
   513  
   514  func ImportErrorf(path, format string, args ...any) ImportPathError {
   515  	err := &importError{importPath: path, err: fmt.Errorf(format, args...)}
   516  	if errStr := err.Error(); !strings.Contains(errStr, path) {
   517  		panic(fmt.Sprintf("path %q not in error %q", path, errStr))
   518  	}
   519  	return err
   520  }
   521  
   522  func (e *importError) Error() string {
   523  	return e.err.Error()
   524  }
   525  
   526  func (e *importError) Unwrap() error {
   527  	// Don't return e.err directly, since we're only wrapping an error if %w
   528  	// was passed to ImportErrorf.
   529  	return errors.Unwrap(e.err)
   530  }
   531  
   532  func (e *importError) ImportPath() string {
   533  	return e.importPath
   534  }
   535  
   536  // An ImportStack is a stack of import paths, possibly with the suffix " (test)" appended.
   537  // The import path of a test package is the import path of the corresponding
   538  // non-test package with the suffix "_test" added.
   539  type ImportStack []string
   540  
   541  func (s *ImportStack) Push(p string) {
   542  	*s = append(*s, p)
   543  }
   544  
   545  func (s *ImportStack) Pop() {
   546  	*s = (*s)[0 : len(*s)-1]
   547  }
   548  
   549  func (s *ImportStack) Copy() []string {
   550  	return append([]string{}, *s...)
   551  }
   552  
   553  func (s *ImportStack) Top() string {
   554  	if len(*s) == 0 {
   555  		return ""
   556  	}
   557  	return (*s)[len(*s)-1]
   558  }
   559  
   560  // shorterThan reports whether sp is shorter than t.
   561  // We use this to record the shortest import sequence
   562  // that leads to a particular package.
   563  func (sp *ImportStack) shorterThan(t []string) bool {
   564  	s := *sp
   565  	if len(s) != len(t) {
   566  		return len(s) < len(t)
   567  	}
   568  	// If they are the same length, settle ties using string ordering.
   569  	for i := range s {
   570  		if s[i] != t[i] {
   571  			return s[i] < t[i]
   572  		}
   573  	}
   574  	return false // they are equal
   575  }
   576  
   577  // packageCache is a lookup cache for LoadImport,
   578  // so that if we look up a package multiple times
   579  // we return the same pointer each time.
   580  var packageCache = map[string]*Package{}
   581  
   582  // ClearPackageCache clears the in-memory package cache and the preload caches.
   583  // It is only for use by GOPATH-based "go get".
   584  // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
   585  func ClearPackageCache() {
   586  	for name := range packageCache {
   587  		delete(packageCache, name)
   588  	}
   589  	resolvedImportCache.Clear()
   590  	packageDataCache.Clear()
   591  }
   592  
   593  // ClearPackageCachePartial clears packages with the given import paths from the
   594  // in-memory package cache and the preload caches. It is only for use by
   595  // GOPATH-based "go get".
   596  // TODO(jayconrod): When GOPATH-based "go get" is removed, delete this function.
   597  func ClearPackageCachePartial(args []string) {
   598  	shouldDelete := make(map[string]bool)
   599  	for _, arg := range args {
   600  		shouldDelete[arg] = true
   601  		if p := packageCache[arg]; p != nil {
   602  			delete(packageCache, arg)
   603  		}
   604  	}
   605  	resolvedImportCache.DeleteIf(func(key any) bool {
   606  		return shouldDelete[key.(importSpec).path]
   607  	})
   608  	packageDataCache.DeleteIf(func(key any) bool {
   609  		return shouldDelete[key.(string)]
   610  	})
   611  }
   612  
   613  // ReloadPackageNoFlags is like LoadImport but makes sure
   614  // not to use the package cache.
   615  // It is only for use by GOPATH-based "go get".
   616  // TODO(rsc): When GOPATH-based "go get" is removed, delete this function.
   617  func ReloadPackageNoFlags(arg string, stk *ImportStack) *Package {
   618  	p := packageCache[arg]
   619  	if p != nil {
   620  		delete(packageCache, arg)
   621  		resolvedImportCache.DeleteIf(func(key any) bool {
   622  			return key.(importSpec).path == p.ImportPath
   623  		})
   624  		packageDataCache.Delete(p.ImportPath)
   625  	}
   626  	return LoadImport(context.TODO(), PackageOpts{}, arg, base.Cwd(), nil, stk, nil, 0)
   627  }
   628  
   629  // dirToImportPath returns the pseudo-import path we use for a package
   630  // outside the Go path. It begins with _/ and then contains the full path
   631  // to the directory. If the package lives in c:\home\gopher\my\pkg then
   632  // the pseudo-import path is _/c_/home/gopher/my/pkg.
   633  // Using a pseudo-import path like this makes the ./ imports no longer
   634  // a special case, so that all the code to deal with ordinary imports works
   635  // automatically.
   636  func dirToImportPath(dir string) string {
   637  	return pathpkg.Join("_", strings.Map(makeImportValid, filepath.ToSlash(dir)))
   638  }
   639  
   640  func makeImportValid(r rune) rune {
   641  	// Should match Go spec, compilers, and ../../go/parser/parser.go:/isValidImport.
   642  	const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
   643  	if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
   644  		return '_'
   645  	}
   646  	return r
   647  }
   648  
   649  // Mode flags for loadImport and download (in get.go).
   650  const (
   651  	// ResolveImport means that loadImport should do import path expansion.
   652  	// That is, ResolveImport means that the import path came from
   653  	// a source file and has not been expanded yet to account for
   654  	// vendoring or possible module adjustment.
   655  	// Every import path should be loaded initially with ResolveImport,
   656  	// and then the expanded version (for example with the /vendor/ in it)
   657  	// gets recorded as the canonical import path. At that point, future loads
   658  	// of that package must not pass ResolveImport, because
   659  	// disallowVendor will reject direct use of paths containing /vendor/.
   660  	ResolveImport = 1 << iota
   661  
   662  	// ResolveModule is for download (part of "go get") and indicates
   663  	// that the module adjustment should be done, but not vendor adjustment.
   664  	ResolveModule
   665  
   666  	// GetTestDeps is for download (part of "go get") and indicates
   667  	// that test dependencies should be fetched too.
   668  	GetTestDeps
   669  )
   670  
   671  // LoadImport scans the directory named by path, which must be an import path,
   672  // but possibly a local import path (an absolute file system path or one beginning
   673  // with ./ or ../). A local relative path is interpreted relative to srcDir.
   674  // It returns a *Package describing the package found in that directory.
   675  // LoadImport does not set tool flags and should only be used by
   676  // this package, as part of a bigger load operation, and by GOPATH-based "go get".
   677  // TODO(rsc): When GOPATH-based "go get" is removed, unexport this function.
   678  func LoadImport(ctx context.Context, opts PackageOpts, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
   679  	return loadImport(ctx, opts, nil, path, srcDir, parent, stk, importPos, mode)
   680  }
   681  
   682  func loadImport(ctx context.Context, opts PackageOpts, pre *preload, path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
   683  	if path == "" {
   684  		panic("LoadImport called with empty package path")
   685  	}
   686  
   687  	var parentPath, parentRoot string
   688  	parentIsStd := false
   689  	if parent != nil {
   690  		parentPath = parent.ImportPath
   691  		parentRoot = parent.Root
   692  		parentIsStd = parent.Standard
   693  	}
   694  	bp, loaded, err := loadPackageData(ctx, path, parentPath, srcDir, parentRoot, parentIsStd, mode)
   695  	if loaded && pre != nil && !opts.IgnoreImports {
   696  		pre.preloadImports(ctx, opts, bp.Imports, bp)
   697  	}
   698  	if bp == nil {
   699  		p := &Package{
   700  			PackagePublic: PackagePublic{
   701  				ImportPath: path,
   702  				Incomplete: true,
   703  			},
   704  		}
   705  		if importErr, ok := err.(ImportPathError); !ok || importErr.ImportPath() != path {
   706  			// Only add path to the error's import stack if it's not already present
   707  			// in the error.
   708  			//
   709  			// TODO(bcmills): setLoadPackageDataError itself has a similar Push / Pop
   710  			// sequence that empirically doesn't trigger for these errors, guarded by
   711  			// a somewhat complex condition. Figure out how to generalize that
   712  			// condition and eliminate the explicit calls here.
   713  			stk.Push(path)
   714  			defer stk.Pop()
   715  		}
   716  		p.setLoadPackageDataError(err, path, stk, nil)
   717  		return p
   718  	}
   719  
   720  	importPath := bp.ImportPath
   721  	p := packageCache[importPath]
   722  	if p != nil {
   723  		stk.Push(path)
   724  		p = reusePackage(p, stk)
   725  		stk.Pop()
   726  	} else {
   727  		p = new(Package)
   728  		p.Internal.Local = build.IsLocalImport(path)
   729  		p.ImportPath = importPath
   730  		packageCache[importPath] = p
   731  
   732  		// Load package.
   733  		// loadPackageData may return bp != nil even if an error occurs,
   734  		// in order to return partial information.
   735  		p.load(ctx, opts, path, stk, importPos, bp, err)
   736  
   737  		if !cfg.ModulesEnabled && path != cleanImport(path) {
   738  			p.Error = &PackageError{
   739  				ImportStack: stk.Copy(),
   740  				Err:         ImportErrorf(path, "non-canonical import path %q: should be %q", path, pathpkg.Clean(path)),
   741  			}
   742  			p.Incomplete = true
   743  			p.Error.setPos(importPos)
   744  		}
   745  	}
   746  
   747  	// Checked on every import because the rules depend on the code doing the importing.
   748  	if perr := disallowInternal(ctx, srcDir, parent, parentPath, p, stk); perr != p {
   749  		perr.Error.setPos(importPos)
   750  		return perr
   751  	}
   752  	if mode&ResolveImport != 0 {
   753  		if perr := disallowVendor(srcDir, path, parentPath, p, stk); perr != p {
   754  			perr.Error.setPos(importPos)
   755  			return perr
   756  		}
   757  	}
   758  
   759  	if p.Name == "main" && parent != nil && parent.Dir != p.Dir {
   760  		perr := *p
   761  		perr.Error = &PackageError{
   762  			ImportStack: stk.Copy(),
   763  			Err:         ImportErrorf(path, "import %q is a program, not an importable package", path),
   764  		}
   765  		perr.Error.setPos(importPos)
   766  		return &perr
   767  	}
   768  
   769  	if p.Internal.Local && parent != nil && !parent.Internal.Local {
   770  		perr := *p
   771  		var err error
   772  		if path == "." {
   773  			err = ImportErrorf(path, "%s: cannot import current directory", path)
   774  		} else {
   775  			err = ImportErrorf(path, "local import %q in non-local package", path)
   776  		}
   777  		perr.Error = &PackageError{
   778  			ImportStack: stk.Copy(),
   779  			Err:         err,
   780  		}
   781  		perr.Error.setPos(importPos)
   782  		return &perr
   783  	}
   784  
   785  	return p
   786  }
   787  
   788  // loadPackageData loads information needed to construct a *Package. The result
   789  // is cached, and later calls to loadPackageData for the same package will return
   790  // the same data.
   791  //
   792  // loadPackageData returns a non-nil package even if err is non-nil unless
   793  // the package path is malformed (for example, the path contains "mod/" or "@").
   794  //
   795  // loadPackageData returns a boolean, loaded, which is true if this is the
   796  // first time the package was loaded. Callers may preload imports in this case.
   797  func loadPackageData(ctx context.Context, path, parentPath, parentDir, parentRoot string, parentIsStd bool, mode int) (bp *build.Package, loaded bool, err error) {
   798  	if path == "" {
   799  		panic("loadPackageData called with empty package path")
   800  	}
   801  
   802  	if strings.HasPrefix(path, "mod/") {
   803  		// Paths beginning with "mod/" might accidentally
   804  		// look in the module cache directory tree in $GOPATH/pkg/mod/.
   805  		// This prefix is owned by the Go core for possible use in the
   806  		// standard library (since it does not begin with a domain name),
   807  		// so it's OK to disallow entirely.
   808  		return nil, false, fmt.Errorf("disallowed import path %q", path)
   809  	}
   810  
   811  	if strings.Contains(path, "@") {
   812  		return nil, false, errors.New("can only use path@version syntax with 'go get' and 'go install' in module-aware mode")
   813  	}
   814  
   815  	// Determine canonical package path and directory.
   816  	// For a local import the identifier is the pseudo-import path
   817  	// we create from the full directory to the package.
   818  	// Otherwise it is the usual import path.
   819  	// For vendored imports, it is the expanded form.
   820  	//
   821  	// Note that when modules are enabled, local import paths are normally
   822  	// canonicalized by modload.LoadPackages before now. However, if there's an
   823  	// error resolving a local path, it will be returned untransformed
   824  	// so that 'go list -e' reports something useful.
   825  	importKey := importSpec{
   826  		path:        path,
   827  		parentPath:  parentPath,
   828  		parentDir:   parentDir,
   829  		parentRoot:  parentRoot,
   830  		parentIsStd: parentIsStd,
   831  		mode:        mode,
   832  	}
   833  	r := resolvedImportCache.Do(importKey, func() any {
   834  		var r resolvedImport
   835  		if cfg.ModulesEnabled {
   836  			r.dir, r.path, r.err = modload.Lookup(parentPath, parentIsStd, path)
   837  		} else if build.IsLocalImport(path) {
   838  			r.dir = filepath.Join(parentDir, path)
   839  			r.path = dirToImportPath(r.dir)
   840  		} else if mode&ResolveImport != 0 {
   841  			// We do our own path resolution, because we want to
   842  			// find out the key to use in packageCache without the
   843  			// overhead of repeated calls to buildContext.Import.
   844  			// The code is also needed in a few other places anyway.
   845  			r.path = resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
   846  		} else if mode&ResolveModule != 0 {
   847  			r.path = moduleImportPath(path, parentPath, parentDir, parentRoot)
   848  		}
   849  		if r.path == "" {
   850  			r.path = path
   851  		}
   852  		return r
   853  	}).(resolvedImport)
   854  	// Invariant: r.path is set to the resolved import path. If the path cannot
   855  	// be resolved, r.path is set to path, the source import path.
   856  	// r.path is never empty.
   857  
   858  	// Load the package from its directory. If we already found the package's
   859  	// directory when resolving its import path, use that.
   860  	data := packageDataCache.Do(r.path, func() any {
   861  		loaded = true
   862  		var data packageData
   863  		if r.dir != "" {
   864  			var buildMode build.ImportMode
   865  			if !cfg.ModulesEnabled {
   866  				buildMode = build.ImportComment
   867  			}
   868  			data.p, data.err = cfg.BuildContext.ImportDir(r.dir, buildMode)
   869  			if cfg.ModulesEnabled {
   870  				// Override data.p.Root, since ImportDir sets it to $GOPATH, if
   871  				// the module is inside $GOPATH/src.
   872  				if info := modload.PackageModuleInfo(ctx, path); info != nil {
   873  					data.p.Root = info.Dir
   874  				}
   875  			}
   876  			if r.err != nil {
   877  				if data.err != nil {
   878  					// ImportDir gave us one error, and the module loader gave us another.
   879  					// We arbitrarily choose to keep the error from ImportDir because
   880  					// that's what our tests already expect, and it seems to provide a bit
   881  					// more detail in most cases.
   882  				} else if errors.Is(r.err, imports.ErrNoGo) {
   883  					// ImportDir said there were files in the package, but the module
   884  					// loader said there weren't. Which one is right?
   885  					// Without this special-case hack, the TestScript/test_vet case fails
   886  					// on the vetfail/p1 package (added in CL 83955).
   887  					// Apparently, imports.ShouldBuild biases toward rejecting files
   888  					// with invalid build constraints, whereas ImportDir biases toward
   889  					// accepting them.
   890  					//
   891  					// TODO(#41410: Figure out how this actually ought to work and fix
   892  					// this mess.
   893  				} else {
   894  					data.err = r.err
   895  				}
   896  			}
   897  		} else if r.err != nil {
   898  			data.p = new(build.Package)
   899  			data.err = r.err
   900  		} else if cfg.ModulesEnabled && path != "unsafe" {
   901  			data.p = new(build.Package)
   902  			data.err = fmt.Errorf("unknown import path %q: internal error: module loader did not resolve import", r.path)
   903  		} else {
   904  			buildMode := build.ImportComment
   905  			if mode&ResolveImport == 0 || r.path != path {
   906  				// Not vendoring, or we already found the vendored path.
   907  				buildMode |= build.IgnoreVendor
   908  			}
   909  			data.p, data.err = cfg.BuildContext.Import(r.path, parentDir, buildMode)
   910  		}
   911  		data.p.ImportPath = r.path
   912  
   913  		// Set data.p.BinDir in cases where go/build.Context.Import
   914  		// may give us a path we don't want.
   915  		if !data.p.Goroot {
   916  			if cfg.GOBIN != "" {
   917  				data.p.BinDir = cfg.GOBIN
   918  			} else if cfg.ModulesEnabled {
   919  				data.p.BinDir = modload.BinDir()
   920  			}
   921  		}
   922  
   923  		if !cfg.ModulesEnabled && data.err == nil &&
   924  			data.p.ImportComment != "" && data.p.ImportComment != path &&
   925  			!strings.Contains(path, "/vendor/") && !strings.HasPrefix(path, "vendor/") {
   926  			data.err = fmt.Errorf("code in directory %s expects import %q", data.p.Dir, data.p.ImportComment)
   927  		}
   928  		return data
   929  	}).(packageData)
   930  
   931  	return data.p, loaded, data.err
   932  }
   933  
   934  // importSpec describes an import declaration in source code. It is used as a
   935  // cache key for resolvedImportCache.
   936  type importSpec struct {
   937  	path                              string
   938  	parentPath, parentDir, parentRoot string
   939  	parentIsStd                       bool
   940  	mode                              int
   941  }
   942  
   943  // resolvedImport holds a canonical identifier for a package. It may also contain
   944  // a path to the package's directory and an error if one occurred. resolvedImport
   945  // is the value type in resolvedImportCache.
   946  type resolvedImport struct {
   947  	path, dir string
   948  	err       error
   949  }
   950  
   951  // packageData holds information loaded from a package. It is the value type
   952  // in packageDataCache.
   953  type packageData struct {
   954  	p   *build.Package
   955  	err error
   956  }
   957  
   958  // resolvedImportCache maps import strings (importSpec) to canonical package names
   959  // (resolvedImport).
   960  var resolvedImportCache par.Cache
   961  
   962  // packageDataCache maps canonical package names (string) to package metadata
   963  // (packageData).
   964  var packageDataCache par.Cache
   965  
   966  // preloadWorkerCount is the number of concurrent goroutines that can load
   967  // packages. Experimentally, there are diminishing returns with more than
   968  // 4 workers. This was measured on the following machines.
   969  //
   970  // * MacBookPro with a 4-core Intel Core i7 CPU
   971  // * Linux workstation with 6-core Intel Xeon CPU
   972  // * Linux workstation with 24-core Intel Xeon CPU
   973  //
   974  // It is very likely (though not confirmed) that this workload is limited
   975  // by memory bandwidth. We don't have a good way to determine the number of
   976  // workers that would saturate the bus though, so runtime.GOMAXPROCS
   977  // seems like a reasonable default.
   978  var preloadWorkerCount = runtime.GOMAXPROCS(0)
   979  
   980  // preload holds state for managing concurrent preloading of package data.
   981  //
   982  // A preload should be created with newPreload before loading a large
   983  // package graph. flush must be called when package loading is complete
   984  // to ensure preload goroutines are no longer active. This is necessary
   985  // because of global mutable state that cannot safely be read and written
   986  // concurrently. In particular, packageDataCache may be cleared by "go get"
   987  // in GOPATH mode, and modload.loaded (accessed via modload.Lookup) may be
   988  // modified by modload.LoadPackages.
   989  type preload struct {
   990  	cancel chan struct{}
   991  	sema   chan struct{}
   992  }
   993  
   994  // newPreload creates a new preloader. flush must be called later to avoid
   995  // accessing global state while it is being modified.
   996  func newPreload() *preload {
   997  	pre := &preload{
   998  		cancel: make(chan struct{}),
   999  		sema:   make(chan struct{}, preloadWorkerCount),
  1000  	}
  1001  	return pre
  1002  }
  1003  
  1004  // preloadMatches loads data for package paths matched by patterns.
  1005  // When preloadMatches returns, some packages may not be loaded yet, but
  1006  // loadPackageData and loadImport are always safe to call.
  1007  func (pre *preload) preloadMatches(ctx context.Context, opts PackageOpts, matches []*search.Match) {
  1008  	for _, m := range matches {
  1009  		for _, pkg := range m.Pkgs {
  1010  			select {
  1011  			case <-pre.cancel:
  1012  				return
  1013  			case pre.sema <- struct{}{}:
  1014  				go func(pkg string) {
  1015  					mode := 0 // don't use vendoring or module import resolution
  1016  					bp, loaded, err := loadPackageData(ctx, pkg, "", base.Cwd(), "", false, mode)
  1017  					<-pre.sema
  1018  					if bp != nil && loaded && err == nil && !opts.IgnoreImports {
  1019  						pre.preloadImports(ctx, opts, bp.Imports, bp)
  1020  					}
  1021  				}(pkg)
  1022  			}
  1023  		}
  1024  	}
  1025  }
  1026  
  1027  // preloadImports queues a list of imports for preloading.
  1028  // When preloadImports returns, some packages may not be loaded yet,
  1029  // but loadPackageData and loadImport are always safe to call.
  1030  func (pre *preload) preloadImports(ctx context.Context, opts PackageOpts, imports []string, parent *build.Package) {
  1031  	parentIsStd := parent.Goroot && parent.ImportPath != "" && search.IsStandardImportPath(parent.ImportPath)
  1032  	for _, path := range imports {
  1033  		if path == "C" || path == "unsafe" {
  1034  			continue
  1035  		}
  1036  		select {
  1037  		case <-pre.cancel:
  1038  			return
  1039  		case pre.sema <- struct{}{}:
  1040  			go func(path string) {
  1041  				bp, loaded, err := loadPackageData(ctx, path, parent.ImportPath, parent.Dir, parent.Root, parentIsStd, ResolveImport)
  1042  				<-pre.sema
  1043  				if bp != nil && loaded && err == nil && !opts.IgnoreImports {
  1044  					pre.preloadImports(ctx, opts, bp.Imports, bp)
  1045  				}
  1046  			}(path)
  1047  		}
  1048  	}
  1049  }
  1050  
  1051  // flush stops pending preload operations. flush blocks until preload calls to
  1052  // loadPackageData have completed. The preloader will not make any new calls
  1053  // to loadPackageData.
  1054  func (pre *preload) flush() {
  1055  	// flush is usually deferred.
  1056  	// Don't hang program waiting for workers on panic.
  1057  	if v := recover(); v != nil {
  1058  		panic(v)
  1059  	}
  1060  
  1061  	close(pre.cancel)
  1062  	for i := 0; i < preloadWorkerCount; i++ {
  1063  		pre.sema <- struct{}{}
  1064  	}
  1065  }
  1066  
  1067  func cleanImport(path string) string {
  1068  	orig := path
  1069  	path = pathpkg.Clean(path)
  1070  	if strings.HasPrefix(orig, "./") && path != ".." && !strings.HasPrefix(path, "../") {
  1071  		path = "./" + path
  1072  	}
  1073  	return path
  1074  }
  1075  
  1076  var isDirCache par.Cache
  1077  
  1078  func isDir(path string) bool {
  1079  	return isDirCache.Do(path, func() any {
  1080  		fi, err := fsys.Stat(path)
  1081  		return err == nil && fi.IsDir()
  1082  	}).(bool)
  1083  }
  1084  
  1085  // ResolveImportPath returns the true meaning of path when it appears in parent.
  1086  // There are two different resolutions applied.
  1087  // First, there is Go 1.5 vendoring (golang.org/s/go15vendor).
  1088  // If vendor expansion doesn't trigger, then the path is also subject to
  1089  // Go 1.11 module legacy conversion (golang.org/issue/25069).
  1090  func ResolveImportPath(parent *Package, path string) (found string) {
  1091  	var parentPath, parentDir, parentRoot string
  1092  	parentIsStd := false
  1093  	if parent != nil {
  1094  		parentPath = parent.ImportPath
  1095  		parentDir = parent.Dir
  1096  		parentRoot = parent.Root
  1097  		parentIsStd = parent.Standard
  1098  	}
  1099  	return resolveImportPath(path, parentPath, parentDir, parentRoot, parentIsStd)
  1100  }
  1101  
  1102  func resolveImportPath(path, parentPath, parentDir, parentRoot string, parentIsStd bool) (found string) {
  1103  	if cfg.ModulesEnabled {
  1104  		if _, p, e := modload.Lookup(parentPath, parentIsStd, path); e == nil {
  1105  			return p
  1106  		}
  1107  		return path
  1108  	}
  1109  	found = vendoredImportPath(path, parentPath, parentDir, parentRoot)
  1110  	if found != path {
  1111  		return found
  1112  	}
  1113  	return moduleImportPath(path, parentPath, parentDir, parentRoot)
  1114  }
  1115  
  1116  // dirAndRoot returns the source directory and workspace root
  1117  // for the package p, guaranteeing that root is a path prefix of dir.
  1118  func dirAndRoot(path string, dir, root string) (string, string) {
  1119  	origDir, origRoot := dir, root
  1120  	dir = filepath.Clean(dir)
  1121  	root = filepath.Join(root, "src")
  1122  	if !str.HasFilePathPrefix(dir, root) || path != "command-line-arguments" && filepath.Join(root, path) != dir {
  1123  		// Look for symlinks before reporting error.
  1124  		dir = expandPath(dir)
  1125  		root = expandPath(root)
  1126  	}
  1127  
  1128  	if !str.HasFilePathPrefix(dir, root) || len(dir) <= len(root) || dir[len(root)] != filepath.Separator || path != "command-line-arguments" && !build.IsLocalImport(path) && filepath.Join(root, path) != dir {
  1129  		debug.PrintStack()
  1130  		base.Fatalf("unexpected directory layout:\n"+
  1131  			"	import path: %s\n"+
  1132  			"	root: %s\n"+
  1133  			"	dir: %s\n"+
  1134  			"	expand root: %s\n"+
  1135  			"	expand dir: %s\n"+
  1136  			"	separator: %s",
  1137  			path,
  1138  			filepath.Join(origRoot, "src"),
  1139  			filepath.Clean(origDir),
  1140  			origRoot,
  1141  			origDir,
  1142  			string(filepath.Separator))
  1143  	}
  1144  
  1145  	return dir, root
  1146  }
  1147  
  1148  // vendoredImportPath returns the vendor-expansion of path when it appears in parent.
  1149  // If parent is x/y/z, then path might expand to x/y/z/vendor/path, x/y/vendor/path,
  1150  // x/vendor/path, vendor/path, or else stay path if none of those exist.
  1151  // vendoredImportPath returns the expanded path or, if no expansion is found, the original.
  1152  func vendoredImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
  1153  	if parentRoot == "" {
  1154  		return path
  1155  	}
  1156  
  1157  	dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
  1158  
  1159  	vpath := "vendor/" + path
  1160  	for i := len(dir); i >= len(root); i-- {
  1161  		if i < len(dir) && dir[i] != filepath.Separator {
  1162  			continue
  1163  		}
  1164  		// Note: checking for the vendor directory before checking
  1165  		// for the vendor/path directory helps us hit the
  1166  		// isDir cache more often. It also helps us prepare a more useful
  1167  		// list of places we looked, to report when an import is not found.
  1168  		if !isDir(filepath.Join(dir[:i], "vendor")) {
  1169  			continue
  1170  		}
  1171  		targ := filepath.Join(dir[:i], vpath)
  1172  		if isDir(targ) && hasGoFiles(targ) {
  1173  			importPath := parentPath
  1174  			if importPath == "command-line-arguments" {
  1175  				// If parent.ImportPath is 'command-line-arguments'.
  1176  				// set to relative directory to root (also chopped root directory)
  1177  				importPath = dir[len(root)+1:]
  1178  			}
  1179  			// We started with parent's dir c:\gopath\src\foo\bar\baz\quux\xyzzy.
  1180  			// We know the import path for parent's dir.
  1181  			// We chopped off some number of path elements and
  1182  			// added vendor\path to produce c:\gopath\src\foo\bar\baz\vendor\path.
  1183  			// Now we want to know the import path for that directory.
  1184  			// Construct it by chopping the same number of path elements
  1185  			// (actually the same number of bytes) from parent's import path
  1186  			// and then append /vendor/path.
  1187  			chopped := len(dir) - i
  1188  			if chopped == len(importPath)+1 {
  1189  				// We walked up from c:\gopath\src\foo\bar
  1190  				// and found c:\gopath\src\vendor\path.
  1191  				// We chopped \foo\bar (length 8) but the import path is "foo/bar" (length 7).
  1192  				// Use "vendor/path" without any prefix.
  1193  				return vpath
  1194  			}
  1195  			return importPath[:len(importPath)-chopped] + "/" + vpath
  1196  		}
  1197  	}
  1198  	return path
  1199  }
  1200  
  1201  var (
  1202  	modulePrefix   = []byte("\nmodule ")
  1203  	goModPathCache par.Cache
  1204  )
  1205  
  1206  // goModPath returns the module path in the go.mod in dir, if any.
  1207  func goModPath(dir string) (path string) {
  1208  	return goModPathCache.Do(dir, func() any {
  1209  		data, err := os.ReadFile(filepath.Join(dir, "go.mod"))
  1210  		if err != nil {
  1211  			return ""
  1212  		}
  1213  		var i int
  1214  		if bytes.HasPrefix(data, modulePrefix[1:]) {
  1215  			i = 0
  1216  		} else {
  1217  			i = bytes.Index(data, modulePrefix)
  1218  			if i < 0 {
  1219  				return ""
  1220  			}
  1221  			i++
  1222  		}
  1223  		line := data[i:]
  1224  
  1225  		// Cut line at \n, drop trailing \r if present.
  1226  		if j := bytes.IndexByte(line, '\n'); j >= 0 {
  1227  			line = line[:j]
  1228  		}
  1229  		if line[len(line)-1] == '\r' {
  1230  			line = line[:len(line)-1]
  1231  		}
  1232  		line = line[len("module "):]
  1233  
  1234  		// If quoted, unquote.
  1235  		path = strings.TrimSpace(string(line))
  1236  		if path != "" && path[0] == '"' {
  1237  			s, err := strconv.Unquote(path)
  1238  			if err != nil {
  1239  				return ""
  1240  			}
  1241  			path = s
  1242  		}
  1243  		return path
  1244  	}).(string)
  1245  }
  1246  
  1247  // findVersionElement returns the slice indices of the final version element /vN in path.
  1248  // If there is no such element, it returns -1, -1.
  1249  func findVersionElement(path string) (i, j int) {
  1250  	j = len(path)
  1251  	for i = len(path) - 1; i >= 0; i-- {
  1252  		if path[i] == '/' {
  1253  			if isVersionElement(path[i+1 : j]) {
  1254  				return i, j
  1255  			}
  1256  			j = i
  1257  		}
  1258  	}
  1259  	return -1, -1
  1260  }
  1261  
  1262  // isVersionElement reports whether s is a well-formed path version element:
  1263  // v2, v3, v10, etc, but not v0, v05, v1.
  1264  func isVersionElement(s string) bool {
  1265  	if len(s) < 2 || s[0] != 'v' || s[1] == '0' || s[1] == '1' && len(s) == 2 {
  1266  		return false
  1267  	}
  1268  	for i := 1; i < len(s); i++ {
  1269  		if s[i] < '0' || '9' < s[i] {
  1270  			return false
  1271  		}
  1272  	}
  1273  	return true
  1274  }
  1275  
  1276  // moduleImportPath translates import paths found in go modules
  1277  // back down to paths that can be resolved in ordinary builds.
  1278  //
  1279  // Define “new” code as code with a go.mod file in the same directory
  1280  // or a parent directory. If an import in new code says x/y/v2/z but
  1281  // x/y/v2/z does not exist and x/y/go.mod says “module x/y/v2”,
  1282  // then go build will read the import as x/y/z instead.
  1283  // See golang.org/issue/25069.
  1284  func moduleImportPath(path, parentPath, parentDir, parentRoot string) (found string) {
  1285  	if parentRoot == "" {
  1286  		return path
  1287  	}
  1288  
  1289  	// If there are no vN elements in path, leave it alone.
  1290  	// (The code below would do the same, but only after
  1291  	// some other file system accesses that we can avoid
  1292  	// here by returning early.)
  1293  	if i, _ := findVersionElement(path); i < 0 {
  1294  		return path
  1295  	}
  1296  
  1297  	dir, root := dirAndRoot(parentPath, parentDir, parentRoot)
  1298  
  1299  	// Consider dir and parents, up to and including root.
  1300  	for i := len(dir); i >= len(root); i-- {
  1301  		if i < len(dir) && dir[i] != filepath.Separator {
  1302  			continue
  1303  		}
  1304  		if goModPath(dir[:i]) != "" {
  1305  			goto HaveGoMod
  1306  		}
  1307  	}
  1308  	// This code is not in a tree with a go.mod,
  1309  	// so apply no changes to the path.
  1310  	return path
  1311  
  1312  HaveGoMod:
  1313  	// This import is in a tree with a go.mod.
  1314  	// Allow it to refer to code in GOPATH/src/x/y/z as x/y/v2/z
  1315  	// if GOPATH/src/x/y/go.mod says module "x/y/v2",
  1316  
  1317  	// If x/y/v2/z exists, use it unmodified.
  1318  	if bp, _ := cfg.BuildContext.Import(path, "", build.IgnoreVendor); bp.Dir != "" {
  1319  		return path
  1320  	}
  1321  
  1322  	// Otherwise look for a go.mod supplying a version element.
  1323  	// Some version-like elements may appear in paths but not
  1324  	// be module versions; we skip over those to look for module
  1325  	// versions. For example the module m/v2 might have a
  1326  	// package m/v2/api/v1/foo.
  1327  	limit := len(path)
  1328  	for limit > 0 {
  1329  		i, j := findVersionElement(path[:limit])
  1330  		if i < 0 {
  1331  			return path
  1332  		}
  1333  		if bp, _ := cfg.BuildContext.Import(path[:i], "", build.IgnoreVendor); bp.Dir != "" {
  1334  			if mpath := goModPath(bp.Dir); mpath != "" {
  1335  				// Found a valid go.mod file, so we're stopping the search.
  1336  				// If the path is m/v2/p and we found m/go.mod that says
  1337  				// "module m/v2", then we return "m/p".
  1338  				if mpath == path[:j] {
  1339  					return path[:i] + path[j:]
  1340  				}
  1341  				// Otherwise just return the original path.
  1342  				// We didn't find anything worth rewriting,
  1343  				// and the go.mod indicates that we should
  1344  				// not consider parent directories.
  1345  				return path
  1346  			}
  1347  		}
  1348  		limit = i
  1349  	}
  1350  	return path
  1351  }
  1352  
  1353  // hasGoFiles reports whether dir contains any files with names ending in .go.
  1354  // For a vendor check we must exclude directories that contain no .go files.
  1355  // Otherwise it is not possible to vendor just a/b/c and still import the
  1356  // non-vendored a/b. See golang.org/issue/13832.
  1357  func hasGoFiles(dir string) bool {
  1358  	files, _ := os.ReadDir(dir)
  1359  	for _, f := range files {
  1360  		if !f.IsDir() && strings.HasSuffix(f.Name(), ".go") {
  1361  			return true
  1362  		}
  1363  	}
  1364  	return false
  1365  }
  1366  
  1367  // reusePackage reuses package p to satisfy the import at the top
  1368  // of the import stack stk. If this use causes an import loop,
  1369  // reusePackage updates p's error information to record the loop.
  1370  func reusePackage(p *Package, stk *ImportStack) *Package {
  1371  	// We use p.Internal.Imports==nil to detect a package that
  1372  	// is in the midst of its own loadPackage call
  1373  	// (all the recursion below happens before p.Internal.Imports gets set).
  1374  	if p.Internal.Imports == nil {
  1375  		if p.Error == nil {
  1376  			p.Error = &PackageError{
  1377  				ImportStack:   stk.Copy(),
  1378  				Err:           errors.New("import cycle not allowed"),
  1379  				IsImportCycle: true,
  1380  			}
  1381  		} else if !p.Error.IsImportCycle {
  1382  			// If the error is already set, but it does not indicate that
  1383  			// we are in an import cycle, set IsImportCycle so that we don't
  1384  			// end up stuck in a loop down the road.
  1385  			p.Error.IsImportCycle = true
  1386  		}
  1387  		p.Incomplete = true
  1388  	}
  1389  	// Don't rewrite the import stack in the error if we have an import cycle.
  1390  	// If we do, we'll lose the path that describes the cycle.
  1391  	if p.Error != nil && !p.Error.IsImportCycle && stk.shorterThan(p.Error.ImportStack) {
  1392  		p.Error.ImportStack = stk.Copy()
  1393  	}
  1394  	return p
  1395  }
  1396  
  1397  // disallowInternal checks that srcDir (containing package importerPath, if non-empty)
  1398  // is allowed to import p.
  1399  // If the import is allowed, disallowInternal returns the original package p.
  1400  // If not, it returns a new package containing just an appropriate error.
  1401  func disallowInternal(ctx context.Context, srcDir string, importer *Package, importerPath string, p *Package, stk *ImportStack) *Package {
  1402  	// golang.org/s/go14internal:
  1403  	// An import of a path containing the element “internal”
  1404  	// is disallowed if the importing code is outside the tree
  1405  	// rooted at the parent of the “internal” directory.
  1406  
  1407  	// There was an error loading the package; stop here.
  1408  	if p.Error != nil {
  1409  		return p
  1410  	}
  1411  
  1412  	// The generated 'testmain' package is allowed to access testing/internal/...,
  1413  	// as if it were generated into the testing directory tree
  1414  	// (it's actually in a temporary directory outside any Go tree).
  1415  	// This cleans up a former kludge in passing functionality to the testing package.
  1416  	if str.HasPathPrefix(p.ImportPath, "testing/internal") && importerPath == "testmain" {
  1417  		return p
  1418  	}
  1419  
  1420  	// We can't check standard packages with gccgo.
  1421  	if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
  1422  		return p
  1423  	}
  1424  
  1425  	// The sort package depends on internal/reflectlite, but during bootstrap
  1426  	// the path rewriting causes the normal internal checks to fail.
  1427  	// Instead, just ignore the internal rules during bootstrap.
  1428  	if p.Standard && strings.HasPrefix(importerPath, "bootstrap/") {
  1429  		return p
  1430  	}
  1431  
  1432  	// importerPath is empty: we started
  1433  	// with a name given on the command line, not an
  1434  	// import. Anything listed on the command line is fine.
  1435  	if importerPath == "" {
  1436  		return p
  1437  	}
  1438  
  1439  	// Check for "internal" element: three cases depending on begin of string and/or end of string.
  1440  	i, ok := findInternal(p.ImportPath)
  1441  	if !ok {
  1442  		return p
  1443  	}
  1444  
  1445  	// Internal is present.
  1446  	// Map import path back to directory corresponding to parent of internal.
  1447  	if i > 0 {
  1448  		i-- // rewind over slash in ".../internal"
  1449  	}
  1450  
  1451  	if p.Module == nil {
  1452  		parent := p.Dir[:i+len(p.Dir)-len(p.ImportPath)]
  1453  
  1454  		if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
  1455  			return p
  1456  		}
  1457  
  1458  		// Look for symlinks before reporting error.
  1459  		srcDir = expandPath(srcDir)
  1460  		parent = expandPath(parent)
  1461  		if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
  1462  			return p
  1463  		}
  1464  	} else {
  1465  		// p is in a module, so make it available based on the importer's import path instead
  1466  		// of the file path (https://golang.org/issue/23970).
  1467  		if importer.Internal.CmdlineFiles {
  1468  			// The importer is a list of command-line files.
  1469  			// Pretend that the import path is the import path of the
  1470  			// directory containing them.
  1471  			// If the directory is outside the main modules, this will resolve to ".",
  1472  			// which is not a prefix of any valid module.
  1473  			importerPath, _ = modload.MainModules.DirImportPath(ctx, importer.Dir)
  1474  		}
  1475  		parentOfInternal := p.ImportPath[:i]
  1476  		if str.HasPathPrefix(importerPath, parentOfInternal) {
  1477  			return p
  1478  		}
  1479  	}
  1480  
  1481  	// Internal is present, and srcDir is outside parent's tree. Not allowed.
  1482  	perr := *p
  1483  	perr.Error = &PackageError{
  1484  		alwaysPrintStack: true,
  1485  		ImportStack:      stk.Copy(),
  1486  		Err:              ImportErrorf(p.ImportPath, "use of internal package "+p.ImportPath+" not allowed"),
  1487  	}
  1488  	perr.Incomplete = true
  1489  	return &perr
  1490  }
  1491  
  1492  // findInternal looks for the final "internal" path element in the given import path.
  1493  // If there isn't one, findInternal returns ok=false.
  1494  // Otherwise, findInternal returns ok=true and the index of the "internal".
  1495  func findInternal(path string) (index int, ok bool) {
  1496  	// Three cases, depending on internal at start/end of string or not.
  1497  	// The order matters: we must return the index of the final element,
  1498  	// because the final one produces the most restrictive requirement
  1499  	// on the importer.
  1500  	switch {
  1501  	case strings.HasSuffix(path, "/internal"):
  1502  		return len(path) - len("internal"), true
  1503  	case strings.Contains(path, "/internal/"):
  1504  		return strings.LastIndex(path, "/internal/") + 1, true
  1505  	case path == "internal", strings.HasPrefix(path, "internal/"):
  1506  		return 0, true
  1507  	}
  1508  	return 0, false
  1509  }
  1510  
  1511  // disallowVendor checks that srcDir is allowed to import p as path.
  1512  // If the import is allowed, disallowVendor returns the original package p.
  1513  // If not, it returns a new package containing just an appropriate error.
  1514  func disallowVendor(srcDir string, path string, importerPath string, p *Package, stk *ImportStack) *Package {
  1515  	// If the importerPath is empty, we started
  1516  	// with a name given on the command line, not an
  1517  	// import. Anything listed on the command line is fine.
  1518  	if importerPath == "" {
  1519  		return p
  1520  	}
  1521  
  1522  	if perr := disallowVendorVisibility(srcDir, p, importerPath, stk); perr != p {
  1523  		return perr
  1524  	}
  1525  
  1526  	// Paths like x/vendor/y must be imported as y, never as x/vendor/y.
  1527  	if i, ok := FindVendor(path); ok {
  1528  		perr := *p
  1529  		perr.Error = &PackageError{
  1530  			ImportStack: stk.Copy(),
  1531  			Err:         ImportErrorf(path, "%s must be imported as %s", path, path[i+len("vendor/"):]),
  1532  		}
  1533  		perr.Incomplete = true
  1534  		return &perr
  1535  	}
  1536  
  1537  	return p
  1538  }
  1539  
  1540  // disallowVendorVisibility checks that srcDir is allowed to import p.
  1541  // The rules are the same as for /internal/ except that a path ending in /vendor
  1542  // is not subject to the rules, only subdirectories of vendor.
  1543  // This allows people to have packages and commands named vendor,
  1544  // for maximal compatibility with existing source trees.
  1545  func disallowVendorVisibility(srcDir string, p *Package, importerPath string, stk *ImportStack) *Package {
  1546  	// The stack does not include p.ImportPath.
  1547  	// If there's nothing on the stack, we started
  1548  	// with a name given on the command line, not an
  1549  	// import. Anything listed on the command line is fine.
  1550  	if importerPath == "" {
  1551  		return p
  1552  	}
  1553  
  1554  	// Check for "vendor" element.
  1555  	i, ok := FindVendor(p.ImportPath)
  1556  	if !ok {
  1557  		return p
  1558  	}
  1559  
  1560  	// Vendor is present.
  1561  	// Map import path back to directory corresponding to parent of vendor.
  1562  	if i > 0 {
  1563  		i-- // rewind over slash in ".../vendor"
  1564  	}
  1565  	truncateTo := i + len(p.Dir) - len(p.ImportPath)
  1566  	if truncateTo < 0 || len(p.Dir) < truncateTo {
  1567  		return p
  1568  	}
  1569  	parent := p.Dir[:truncateTo]
  1570  	if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
  1571  		return p
  1572  	}
  1573  
  1574  	// Look for symlinks before reporting error.
  1575  	srcDir = expandPath(srcDir)
  1576  	parent = expandPath(parent)
  1577  	if str.HasFilePathPrefix(filepath.Clean(srcDir), filepath.Clean(parent)) {
  1578  		return p
  1579  	}
  1580  
  1581  	// Vendor is present, and srcDir is outside parent's tree. Not allowed.
  1582  	perr := *p
  1583  	perr.Error = &PackageError{
  1584  		ImportStack: stk.Copy(),
  1585  		Err:         errors.New("use of vendored package not allowed"),
  1586  	}
  1587  	perr.Incomplete = true
  1588  	return &perr
  1589  }
  1590  
  1591  // FindVendor looks for the last non-terminating "vendor" path element in the given import path.
  1592  // If there isn't one, FindVendor returns ok=false.
  1593  // Otherwise, FindVendor returns ok=true and the index of the "vendor".
  1594  //
  1595  // Note that terminating "vendor" elements don't count: "x/vendor" is its own package,
  1596  // not the vendored copy of an import "" (the empty import path).
  1597  // This will allow people to have packages or commands named vendor.
  1598  // This may help reduce breakage, or it may just be confusing. We'll see.
  1599  func FindVendor(path string) (index int, ok bool) {
  1600  	// Two cases, depending on internal at start of string or not.
  1601  	// The order matters: we must return the index of the final element,
  1602  	// because the final one is where the effective import path starts.
  1603  	switch {
  1604  	case strings.Contains(path, "/vendor/"):
  1605  		return strings.LastIndex(path, "/vendor/") + 1, true
  1606  	case strings.HasPrefix(path, "vendor/"):
  1607  		return 0, true
  1608  	}
  1609  	return 0, false
  1610  }
  1611  
  1612  type TargetDir int
  1613  
  1614  const (
  1615  	ToTool    TargetDir = iota // to GOROOT/pkg/tool (default for cmd/*)
  1616  	ToBin                      // to bin dir inside package root (default for non-cmd/*)
  1617  	StalePath                  // an old import path; fail to build
  1618  )
  1619  
  1620  // InstallTargetDir reports the target directory for installing the command p.
  1621  func InstallTargetDir(p *Package) TargetDir {
  1622  	if strings.HasPrefix(p.ImportPath, "code.google.com/p/go.tools/cmd/") {
  1623  		return StalePath
  1624  	}
  1625  	if p.Goroot && strings.HasPrefix(p.ImportPath, "cmd/") && p.Name == "main" {
  1626  		switch p.ImportPath {
  1627  		case "cmd/go", "cmd/gofmt":
  1628  			return ToBin
  1629  		}
  1630  		return ToTool
  1631  	}
  1632  	return ToBin
  1633  }
  1634  
  1635  var cgoExclude = map[string]bool{
  1636  	"runtime/cgo": true,
  1637  }
  1638  
  1639  var cgoSyscallExclude = map[string]bool{
  1640  	"runtime/cgo":  true,
  1641  	"runtime/race": true,
  1642  	"runtime/msan": true,
  1643  	"runtime/asan": true,
  1644  }
  1645  
  1646  var foldPath = make(map[string]string)
  1647  
  1648  // exeFromImportPath returns an executable name
  1649  // for a package using the import path.
  1650  //
  1651  // The executable name is the last element of the import path.
  1652  // In module-aware mode, an additional rule is used on import paths
  1653  // consisting of two or more path elements. If the last element is
  1654  // a vN path element specifying the major version, then the
  1655  // second last element of the import path is used instead.
  1656  func (p *Package) exeFromImportPath() string {
  1657  	_, elem := pathpkg.Split(p.ImportPath)
  1658  	if cfg.ModulesEnabled {
  1659  		// If this is example.com/mycmd/v2, it's more useful to
  1660  		// install it as mycmd than as v2. See golang.org/issue/24667.
  1661  		if elem != p.ImportPath && isVersionElement(elem) {
  1662  			_, elem = pathpkg.Split(pathpkg.Dir(p.ImportPath))
  1663  		}
  1664  	}
  1665  	return elem
  1666  }
  1667  
  1668  // exeFromFiles returns an executable name for a package
  1669  // using the first element in GoFiles or CgoFiles collections without the prefix.
  1670  //
  1671  // Returns empty string in case of empty collection.
  1672  func (p *Package) exeFromFiles() string {
  1673  	var src string
  1674  	if len(p.GoFiles) > 0 {
  1675  		src = p.GoFiles[0]
  1676  	} else if len(p.CgoFiles) > 0 {
  1677  		src = p.CgoFiles[0]
  1678  	} else {
  1679  		return ""
  1680  	}
  1681  	_, elem := filepath.Split(src)
  1682  	return elem[:len(elem)-len(".go")]
  1683  }
  1684  
  1685  // DefaultExecName returns the default executable name for a package
  1686  func (p *Package) DefaultExecName() string {
  1687  	if p.Internal.CmdlineFiles {
  1688  		return p.exeFromFiles()
  1689  	}
  1690  	return p.exeFromImportPath()
  1691  }
  1692  
  1693  // load populates p using information from bp, err, which should
  1694  // be the result of calling build.Context.Import.
  1695  // stk contains the import stack, not including path itself.
  1696  func (p *Package) load(ctx context.Context, opts PackageOpts, path string, stk *ImportStack, importPos []token.Position, bp *build.Package, err error) {
  1697  	p.copyBuild(opts, bp)
  1698  
  1699  	// The localPrefix is the path we interpret ./ imports relative to,
  1700  	// if we support them at all (not in module mode!).
  1701  	// Synthesized main packages sometimes override this.
  1702  	if p.Internal.Local && !cfg.ModulesEnabled {
  1703  		p.Internal.LocalPrefix = dirToImportPath(p.Dir)
  1704  	}
  1705  
  1706  	// setError sets p.Error if it hasn't already been set. We may proceed
  1707  	// after encountering some errors so that 'go list -e' has more complete
  1708  	// output. If there's more than one error, we should report the first.
  1709  	setError := func(err error) {
  1710  		if p.Error == nil {
  1711  			p.Error = &PackageError{
  1712  				ImportStack: stk.Copy(),
  1713  				Err:         err,
  1714  			}
  1715  
  1716  			// Add the importer's position information if the import position exists, and
  1717  			// the current package being examined is the importer.
  1718  			// If we have not yet accepted package p onto the import stack,
  1719  			// then the cause of the error is not within p itself: the error
  1720  			// must be either in an explicit command-line argument,
  1721  			// or on the importer side (indicated by a non-empty importPos).
  1722  			if path != stk.Top() && len(importPos) > 0 {
  1723  				p.Error.setPos(importPos)
  1724  			}
  1725  		}
  1726  	}
  1727  
  1728  	if err != nil {
  1729  		p.Incomplete = true
  1730  		p.setLoadPackageDataError(err, path, stk, importPos)
  1731  	}
  1732  
  1733  	useBindir := p.Name == "main"
  1734  	if !p.Standard {
  1735  		switch cfg.BuildBuildmode {
  1736  		case "c-archive", "c-shared", "plugin":
  1737  			useBindir = false
  1738  		}
  1739  	}
  1740  
  1741  	if useBindir {
  1742  		// Report an error when the old code.google.com/p/go.tools paths are used.
  1743  		if InstallTargetDir(p) == StalePath {
  1744  			// TODO(matloob): remove this branch, and StalePath itself. code.google.com/p/go is so
  1745  			// old, even this code checking for it is stale now!
  1746  			newPath := strings.Replace(p.ImportPath, "code.google.com/p/go.", "golang.org/x/", 1)
  1747  			e := ImportErrorf(p.ImportPath, "the %v command has moved; use %v instead.", p.ImportPath, newPath)
  1748  			setError(e)
  1749  			return
  1750  		}
  1751  		elem := p.DefaultExecName()
  1752  		full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
  1753  		if cfg.BuildContext.GOOS != base.ToolGOOS || cfg.BuildContext.GOARCH != base.ToolGOARCH {
  1754  			// Install cross-compiled binaries to subdirectories of bin.
  1755  			elem = full
  1756  		}
  1757  		if p.Internal.Build.BinDir == "" && cfg.ModulesEnabled {
  1758  			p.Internal.Build.BinDir = modload.BinDir()
  1759  		}
  1760  		if p.Internal.Build.BinDir != "" {
  1761  			// Install to GOBIN or bin of GOPATH entry.
  1762  			p.Target = filepath.Join(p.Internal.Build.BinDir, elem)
  1763  			if !p.Goroot && strings.Contains(elem, "/") && cfg.GOBIN != "" {
  1764  				// Do not create $GOBIN/goos_goarch/elem.
  1765  				p.Target = ""
  1766  				p.Internal.GobinSubdir = true
  1767  			}
  1768  		}
  1769  		if InstallTargetDir(p) == ToTool {
  1770  			// This is for 'go tool'.
  1771  			// Override all the usual logic and force it into the tool directory.
  1772  			if cfg.BuildToolchainName == "gccgo" {
  1773  				p.Target = filepath.Join(base.ToolDir, elem)
  1774  			} else {
  1775  				p.Target = filepath.Join(cfg.GOROOTpkg, "tool", full)
  1776  			}
  1777  		}
  1778  		if p.Target != "" && cfg.BuildContext.GOOS == "windows" {
  1779  			p.Target += ".exe"
  1780  		}
  1781  	} else if p.Internal.Local {
  1782  		// Local import turned into absolute path.
  1783  		// No permanent install target.
  1784  		p.Target = ""
  1785  	} else {
  1786  		p.Target = p.Internal.Build.PkgObj
  1787  		if cfg.BuildLinkshared && p.Target != "" {
  1788  			// TODO(bcmills): The reliance on p.Target implies that -linkshared does
  1789  			// not work for any package that lacks a Target — such as a non-main
  1790  			// package in module mode. We should probably fix that.
  1791  			shlibnamefile := p.Target[:len(p.Target)-2] + ".shlibname"
  1792  			shlib, err := os.ReadFile(shlibnamefile)
  1793  			if err != nil && !os.IsNotExist(err) {
  1794  				base.Fatalf("reading shlibname: %v", err)
  1795  			}
  1796  			if err == nil {
  1797  				libname := strings.TrimSpace(string(shlib))
  1798  				if cfg.BuildContext.Compiler == "gccgo" {
  1799  					p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, "shlibs", libname)
  1800  				} else {
  1801  					p.Shlib = filepath.Join(p.Internal.Build.PkgTargetRoot, libname)
  1802  				}
  1803  			}
  1804  		}
  1805  	}
  1806  
  1807  	// Build augmented import list to add implicit dependencies.
  1808  	// Be careful not to add imports twice, just to avoid confusion.
  1809  	importPaths := p.Imports
  1810  	addImport := func(path string, forCompiler bool) {
  1811  		for _, p := range importPaths {
  1812  			if path == p {
  1813  				return
  1814  			}
  1815  		}
  1816  		importPaths = append(importPaths, path)
  1817  		if forCompiler {
  1818  			p.Internal.CompiledImports = append(p.Internal.CompiledImports, path)
  1819  		}
  1820  	}
  1821  
  1822  	if !opts.IgnoreImports {
  1823  		// Cgo translation adds imports of "unsafe", "runtime/cgo" and "syscall",
  1824  		// except for certain packages, to avoid circular dependencies.
  1825  		if p.UsesCgo() {
  1826  			addImport("unsafe", true)
  1827  		}
  1828  		if p.UsesCgo() && (!p.Standard || !cgoExclude[p.ImportPath]) && cfg.BuildContext.Compiler != "gccgo" {
  1829  			addImport("runtime/cgo", true)
  1830  		}
  1831  		if p.UsesCgo() && (!p.Standard || !cgoSyscallExclude[p.ImportPath]) {
  1832  			addImport("syscall", true)
  1833  		}
  1834  
  1835  		// SWIG adds imports of some standard packages.
  1836  		if p.UsesSwig() {
  1837  			addImport("unsafe", true)
  1838  			if cfg.BuildContext.Compiler != "gccgo" {
  1839  				addImport("runtime/cgo", true)
  1840  			}
  1841  			addImport("syscall", true)
  1842  			addImport("sync", true)
  1843  
  1844  			// TODO: The .swig and .swigcxx files can use
  1845  			// %go_import directives to import other packages.
  1846  		}
  1847  
  1848  		// The linker loads implicit dependencies.
  1849  		if p.Name == "main" && !p.Internal.ForceLibrary {
  1850  			for _, dep := range LinkerDeps(p) {
  1851  				addImport(dep, false)
  1852  			}
  1853  		}
  1854  	}
  1855  
  1856  	// Check for case-insensitive collisions of import paths.
  1857  	fold := str.ToFold(p.ImportPath)
  1858  	if other := foldPath[fold]; other == "" {
  1859  		foldPath[fold] = p.ImportPath
  1860  	} else if other != p.ImportPath {
  1861  		setError(ImportErrorf(p.ImportPath, "case-insensitive import collision: %q and %q", p.ImportPath, other))
  1862  		return
  1863  	}
  1864  
  1865  	if !SafeArg(p.ImportPath) {
  1866  		setError(ImportErrorf(p.ImportPath, "invalid import path %q", p.ImportPath))
  1867  		return
  1868  	}
  1869  
  1870  	// Errors after this point are caused by this package, not the importing
  1871  	// package. Pushing the path here prevents us from reporting the error
  1872  	// with the position of the import declaration.
  1873  	stk.Push(path)
  1874  	defer stk.Pop()
  1875  
  1876  	pkgPath := p.ImportPath
  1877  	if p.Internal.CmdlineFiles {
  1878  		pkgPath = "command-line-arguments"
  1879  	}
  1880  	if cfg.ModulesEnabled {
  1881  		p.Module = modload.PackageModuleInfo(ctx, pkgPath)
  1882  	}
  1883  
  1884  	p.EmbedFiles, p.Internal.Embed, err = resolveEmbed(p.Dir, p.EmbedPatterns)
  1885  	if err != nil {
  1886  		p.Incomplete = true
  1887  		setError(err)
  1888  		embedErr := err.(*EmbedError)
  1889  		p.Error.setPos(p.Internal.Build.EmbedPatternPos[embedErr.Pattern])
  1890  	}
  1891  
  1892  	// Check for case-insensitive collision of input files.
  1893  	// To avoid problems on case-insensitive files, we reject any package
  1894  	// where two different input files have equal names under a case-insensitive
  1895  	// comparison.
  1896  	inputs := p.AllFiles()
  1897  	f1, f2 := str.FoldDup(inputs)
  1898  	if f1 != "" {
  1899  		setError(fmt.Errorf("case-insensitive file name collision: %q and %q", f1, f2))
  1900  		return
  1901  	}
  1902  
  1903  	// If first letter of input file is ASCII, it must be alphanumeric.
  1904  	// This avoids files turning into flags when invoking commands,
  1905  	// and other problems we haven't thought of yet.
  1906  	// Also, _cgo_ files must be generated by us, not supplied.
  1907  	// They are allowed to have //go:cgo_ldflag directives.
  1908  	// The directory scan ignores files beginning with _,
  1909  	// so we shouldn't see any _cgo_ files anyway, but just be safe.
  1910  	for _, file := range inputs {
  1911  		if !SafeArg(file) || strings.HasPrefix(file, "_cgo_") {
  1912  			setError(fmt.Errorf("invalid input file name %q", file))
  1913  			return
  1914  		}
  1915  	}
  1916  	if name := pathpkg.Base(p.ImportPath); !SafeArg(name) {
  1917  		setError(fmt.Errorf("invalid input directory name %q", name))
  1918  		return
  1919  	}
  1920  
  1921  	// Build list of imported packages and full dependency list.
  1922  	imports := make([]*Package, 0, len(p.Imports))
  1923  	for i, path := range importPaths {
  1924  		if path == "C" {
  1925  			continue
  1926  		}
  1927  		p1 := LoadImport(ctx, opts, path, p.Dir, p, stk, p.Internal.Build.ImportPos[path], ResolveImport)
  1928  
  1929  		path = p1.ImportPath
  1930  		importPaths[i] = path
  1931  		if i < len(p.Imports) {
  1932  			p.Imports[i] = path
  1933  		}
  1934  
  1935  		imports = append(imports, p1)
  1936  		if p1.Incomplete {
  1937  			p.Incomplete = true
  1938  		}
  1939  	}
  1940  	p.Internal.Imports = imports
  1941  	p.collectDeps()
  1942  	if p.Error == nil && p.Name == "main" && !p.Internal.ForceLibrary && len(p.DepsErrors) == 0 {
  1943  		// TODO(bcmills): loading VCS metadata can be fairly slow.
  1944  		// Consider starting this as a background goroutine and retrieving the result
  1945  		// asynchronously when we're actually ready to build the package, or when we
  1946  		// actually need to evaluate whether the package's metadata is stale.
  1947  		p.setBuildInfo(opts.LoadVCS)
  1948  	}
  1949  
  1950  	// unsafe is a fake package.
  1951  	if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
  1952  		p.Target = ""
  1953  	}
  1954  
  1955  	// If cgo is not enabled, ignore cgo supporting sources
  1956  	// just as we ignore go files containing import "C".
  1957  	if !cfg.BuildContext.CgoEnabled {
  1958  		p.CFiles = nil
  1959  		p.CXXFiles = nil
  1960  		p.MFiles = nil
  1961  		p.SwigFiles = nil
  1962  		p.SwigCXXFiles = nil
  1963  		// Note that SFiles are okay (they go to the Go assembler)
  1964  		// and HFiles are okay (they might be used by the SFiles).
  1965  		// Also Sysofiles are okay (they might not contain object
  1966  		// code; see issue #16050).
  1967  	}
  1968  
  1969  	// The gc toolchain only permits C source files with cgo or SWIG.
  1970  	if len(p.CFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() && cfg.BuildContext.Compiler == "gc" {
  1971  		setError(fmt.Errorf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")))
  1972  		return
  1973  	}
  1974  
  1975  	// C++, Objective-C, and Fortran source files are permitted only with cgo or SWIG,
  1976  	// regardless of toolchain.
  1977  	if len(p.CXXFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
  1978  		setError(fmt.Errorf("C++ source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CXXFiles, " ")))
  1979  		return
  1980  	}
  1981  	if len(p.MFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
  1982  		setError(fmt.Errorf("Objective-C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.MFiles, " ")))
  1983  		return
  1984  	}
  1985  	if len(p.FFiles) > 0 && !p.UsesCgo() && !p.UsesSwig() {
  1986  		setError(fmt.Errorf("Fortran source files not allowed when not using cgo or SWIG: %s", strings.Join(p.FFiles, " ")))
  1987  		return
  1988  	}
  1989  }
  1990  
  1991  // An EmbedError indicates a problem with a go:embed directive.
  1992  type EmbedError struct {
  1993  	Pattern string
  1994  	Err     error
  1995  }
  1996  
  1997  func (e *EmbedError) Error() string {
  1998  	return fmt.Sprintf("pattern %s: %v", e.Pattern, e.Err)
  1999  }
  2000  
  2001  func (e *EmbedError) Unwrap() error {
  2002  	return e.Err
  2003  }
  2004  
  2005  // ResolveEmbed resolves //go:embed patterns and returns only the file list.
  2006  // For use by go mod vendor to find embedded files it should copy into the
  2007  // vendor directory.
  2008  // TODO(#42504): Once go mod vendor uses load.PackagesAndErrors, just
  2009  // call (*Package).ResolveEmbed
  2010  func ResolveEmbed(dir string, patterns []string) ([]string, error) {
  2011  	files, _, err := resolveEmbed(dir, patterns)
  2012  	return files, err
  2013  }
  2014  
  2015  // resolveEmbed resolves //go:embed patterns to precise file lists.
  2016  // It sets files to the list of unique files matched (for go list),
  2017  // and it sets pmap to the more precise mapping from
  2018  // patterns to files.
  2019  func resolveEmbed(pkgdir string, patterns []string) (files []string, pmap map[string][]string, err error) {
  2020  	var pattern string
  2021  	defer func() {
  2022  		if err != nil {
  2023  			err = &EmbedError{
  2024  				Pattern: pattern,
  2025  				Err:     err,
  2026  			}
  2027  		}
  2028  	}()
  2029  
  2030  	// TODO(rsc): All these messages need position information for better error reports.
  2031  	pmap = make(map[string][]string)
  2032  	have := make(map[string]int)
  2033  	dirOK := make(map[string]bool)
  2034  	pid := 0 // pattern ID, to allow reuse of have map
  2035  	for _, pattern = range patterns {
  2036  		pid++
  2037  
  2038  		glob := pattern
  2039  		all := strings.HasPrefix(pattern, "all:")
  2040  		if all {
  2041  			glob = pattern[len("all:"):]
  2042  		}
  2043  		// Check pattern is valid for //go:embed.
  2044  		if _, err := path.Match(glob, ""); err != nil || !validEmbedPattern(glob) {
  2045  			return nil, nil, fmt.Errorf("invalid pattern syntax")
  2046  		}
  2047  
  2048  		// Glob to find matches.
  2049  		match, err := fsys.Glob(pkgdir + string(filepath.Separator) + filepath.FromSlash(glob))
  2050  		if err != nil {
  2051  			return nil, nil, err
  2052  		}
  2053  
  2054  		// Filter list of matches down to the ones that will still exist when
  2055  		// the directory is packaged up as a module. (If p.Dir is in the module cache,
  2056  		// only those files exist already, but if p.Dir is in the current module,
  2057  		// then there may be other things lying around, like symbolic links or .git directories.)
  2058  		var list []string
  2059  		for _, file := range match {
  2060  			rel := filepath.ToSlash(file[len(pkgdir)+1:]) // file, relative to p.Dir
  2061  
  2062  			what := "file"
  2063  			info, err := fsys.Lstat(file)
  2064  			if err != nil {
  2065  				return nil, nil, err
  2066  			}
  2067  			if info.IsDir() {
  2068  				what = "directory"
  2069  			}
  2070  
  2071  			// Check that directories along path do not begin a new module
  2072  			// (do not contain a go.mod).
  2073  			for dir := file; len(dir) > len(pkgdir)+1 && !dirOK[dir]; dir = filepath.Dir(dir) {
  2074  				if _, err := fsys.Stat(filepath.Join(dir, "go.mod")); err == nil {
  2075  					return nil, nil, fmt.Errorf("cannot embed %s %s: in different module", what, rel)
  2076  				}
  2077  				if dir != file {
  2078  					if info, err := fsys.Lstat(dir); err == nil && !info.IsDir() {
  2079  						return nil, nil, fmt.Errorf("cannot embed %s %s: in non-directory %s", what, rel, dir[len(pkgdir)+1:])
  2080  					}
  2081  				}
  2082  				dirOK[dir] = true
  2083  				if elem := filepath.Base(dir); isBadEmbedName(elem) {
  2084  					if dir == file {
  2085  						return nil, nil, fmt.Errorf("cannot embed %s %s: invalid name %s", what, rel, elem)
  2086  					} else {
  2087  						return nil, nil, fmt.Errorf("cannot embed %s %s: in invalid directory %s", what, rel, elem)
  2088  					}
  2089  				}
  2090  			}
  2091  
  2092  			switch {
  2093  			default:
  2094  				return nil, nil, fmt.Errorf("cannot embed irregular file %s", rel)
  2095  
  2096  			case info.Mode().IsRegular():
  2097  				if have[rel] != pid {
  2098  					have[rel] = pid
  2099  					list = append(list, rel)
  2100  				}
  2101  
  2102  			case info.IsDir():
  2103  				// Gather all files in the named directory, stopping at module boundaries
  2104  				// and ignoring files that wouldn't be packaged into a module.
  2105  				count := 0
  2106  				err := fsys.Walk(file, func(path string, info os.FileInfo, err error) error {
  2107  					if err != nil {
  2108  						return err
  2109  					}
  2110  					rel := filepath.ToSlash(path[len(pkgdir)+1:])
  2111  					name := info.Name()
  2112  					if path != file && (isBadEmbedName(name) || ((name[0] == '.' || name[0] == '_') && !all)) {
  2113  						// Ignore bad names, assuming they won't go into modules.
  2114  						// Also avoid hidden files that user may not know about.
  2115  						// See golang.org/issue/42328.
  2116  						if info.IsDir() {
  2117  							return fs.SkipDir
  2118  						}
  2119  						return nil
  2120  					}
  2121  					if info.IsDir() {
  2122  						if _, err := fsys.Stat(filepath.Join(path, "go.mod")); err == nil {
  2123  							return filepath.SkipDir
  2124  						}
  2125  						return nil
  2126  					}
  2127  					if !info.Mode().IsRegular() {
  2128  						return nil
  2129  					}
  2130  					count++
  2131  					if have[rel] != pid {
  2132  						have[rel] = pid
  2133  						list = append(list, rel)
  2134  					}
  2135  					return nil
  2136  				})
  2137  				if err != nil {
  2138  					return nil, nil, err
  2139  				}
  2140  				if count == 0 {
  2141  					return nil, nil, fmt.Errorf("cannot embed directory %s: contains no embeddable files", rel)
  2142  				}
  2143  			}
  2144  		}
  2145  
  2146  		if len(list) == 0 {
  2147  			return nil, nil, fmt.Errorf("no matching files found")
  2148  		}
  2149  		sort.Strings(list)
  2150  		pmap[pattern] = list
  2151  	}
  2152  
  2153  	for file := range have {
  2154  		files = append(files, file)
  2155  	}
  2156  	sort.Strings(files)
  2157  	return files, pmap, nil
  2158  }
  2159  
  2160  func validEmbedPattern(pattern string) bool {
  2161  	return pattern != "." && fs.ValidPath(pattern)
  2162  }
  2163  
  2164  // isBadEmbedName reports whether name is the base name of a file that
  2165  // can't or won't be included in modules and therefore shouldn't be treated
  2166  // as existing for embedding.
  2167  func isBadEmbedName(name string) bool {
  2168  	if err := module.CheckFilePath(name); err != nil {
  2169  		return true
  2170  	}
  2171  	switch name {
  2172  	// Empty string should be impossible but make it bad.
  2173  	case "":
  2174  		return true
  2175  	// Version control directories won't be present in module.
  2176  	case ".bzr", ".hg", ".git", ".svn":
  2177  		return true
  2178  	}
  2179  	return false
  2180  }
  2181  
  2182  // collectDeps populates p.Deps and p.DepsErrors by iterating over
  2183  // p.Internal.Imports.
  2184  //
  2185  // TODO(jayconrod): collectDeps iterates over transitive imports for every
  2186  // package. We should only need to visit direct imports.
  2187  func (p *Package) collectDeps() {
  2188  	deps := make(map[string]*Package)
  2189  	var q []*Package
  2190  	q = append(q, p.Internal.Imports...)
  2191  	for i := 0; i < len(q); i++ {
  2192  		p1 := q[i]
  2193  		path := p1.ImportPath
  2194  		// The same import path could produce an error or not,
  2195  		// depending on what tries to import it.
  2196  		// Prefer to record entries with errors, so we can report them.
  2197  		p0 := deps[path]
  2198  		if p0 == nil || p1.Error != nil && (p0.Error == nil || len(p0.Error.ImportStack) > len(p1.Error.ImportStack)) {
  2199  			deps[path] = p1
  2200  			for _, p2 := range p1.Internal.Imports {
  2201  				if deps[p2.ImportPath] != p2 {
  2202  					q = append(q, p2)
  2203  				}
  2204  			}
  2205  		}
  2206  	}
  2207  
  2208  	p.Deps = make([]string, 0, len(deps))
  2209  	for dep := range deps {
  2210  		p.Deps = append(p.Deps, dep)
  2211  	}
  2212  	sort.Strings(p.Deps)
  2213  	for _, dep := range p.Deps {
  2214  		p1 := deps[dep]
  2215  		if p1 == nil {
  2216  			panic("impossible: missing entry in package cache for " + dep + " imported by " + p.ImportPath)
  2217  		}
  2218  		if p1.Error != nil {
  2219  			p.DepsErrors = append(p.DepsErrors, p1.Error)
  2220  		}
  2221  	}
  2222  }
  2223  
  2224  // vcsStatusCache maps repository directories (string)
  2225  // to their VCS information (vcsStatusError).
  2226  var vcsStatusCache par.Cache
  2227  
  2228  // setBuildInfo gathers build information, formats it as a string to be
  2229  // embedded in the binary, then sets p.Internal.BuildInfo to that string.
  2230  // setBuildInfo should only be called on a main package with no errors.
  2231  //
  2232  // This information can be retrieved using debug.ReadBuildInfo.
  2233  //
  2234  // Note that the GoVersion field is not set here to avoid encoding it twice.
  2235  // It is stored separately in the binary, mostly for historical reasons.
  2236  func (p *Package) setBuildInfo(includeVCS bool) {
  2237  	// TODO: build and vcs information is not embedded for executables in GOROOT.
  2238  	// cmd/dist uses -gcflags=all= -ldflags=all= by default, which means these
  2239  	// executables always appear stale unless the user sets the same flags.
  2240  	// Perhaps it's safe to omit those flags when GO_GCFLAGS and GO_LDFLAGS
  2241  	// are not set?
  2242  	setPkgErrorf := func(format string, args ...any) {
  2243  		if p.Error == nil {
  2244  			p.Error = &PackageError{Err: fmt.Errorf(format, args...)}
  2245  		}
  2246  	}
  2247  
  2248  	var debugModFromModinfo func(*modinfo.ModulePublic) *debug.Module
  2249  	debugModFromModinfo = func(mi *modinfo.ModulePublic) *debug.Module {
  2250  		version := mi.Version
  2251  		if version == "" {
  2252  			version = "(devel)"
  2253  		}
  2254  		dm := &debug.Module{
  2255  			Path:    mi.Path,
  2256  			Version: version,
  2257  		}
  2258  		if mi.Replace != nil {
  2259  			dm.Replace = debugModFromModinfo(mi.Replace)
  2260  		} else if mi.Version != "" {
  2261  			dm.Sum = modfetch.Sum(module.Version{Path: mi.Path, Version: mi.Version})
  2262  		}
  2263  		return dm
  2264  	}
  2265  
  2266  	var main debug.Module
  2267  	if p.Module != nil {
  2268  		main = *debugModFromModinfo(p.Module)
  2269  	}
  2270  
  2271  	visited := make(map[*Package]bool)
  2272  	mdeps := make(map[module.Version]*debug.Module)
  2273  	var q []*Package
  2274  	q = append(q, p.Internal.Imports...)
  2275  	for len(q) > 0 {
  2276  		p1 := q[0]
  2277  		q = q[1:]
  2278  		if visited[p1] {
  2279  			continue
  2280  		}
  2281  		visited[p1] = true
  2282  		if p1.Module != nil {
  2283  			m := module.Version{Path: p1.Module.Path, Version: p1.Module.Version}
  2284  			if p1.Module.Path != main.Path && mdeps[m] == nil {
  2285  				mdeps[m] = debugModFromModinfo(p1.Module)
  2286  			}
  2287  		}
  2288  		q = append(q, p1.Internal.Imports...)
  2289  	}
  2290  	sortedMods := make([]module.Version, 0, len(mdeps))
  2291  	for mod := range mdeps {
  2292  		sortedMods = append(sortedMods, mod)
  2293  	}
  2294  	module.Sort(sortedMods)
  2295  	deps := make([]*debug.Module, len(sortedMods))
  2296  	for i, mod := range sortedMods {
  2297  		deps[i] = mdeps[mod]
  2298  	}
  2299  
  2300  	pkgPath := p.ImportPath
  2301  	if p.Internal.CmdlineFiles {
  2302  		pkgPath = "command-line-arguments"
  2303  	}
  2304  	info := &debug.BuildInfo{
  2305  		Path: pkgPath,
  2306  		Main: main,
  2307  		Deps: deps,
  2308  	}
  2309  	appendSetting := func(key, value string) {
  2310  		value = strings.ReplaceAll(value, "\n", " ") // make value safe
  2311  		info.Settings = append(info.Settings, debug.BuildSetting{Key: key, Value: value})
  2312  	}
  2313  
  2314  	// Add command-line flags relevant to the build.
  2315  	// This is informational, not an exhaustive list.
  2316  	// Please keep the list sorted.
  2317  	if !p.Standard {
  2318  		if cfg.BuildASan {
  2319  			appendSetting("-asan", "true")
  2320  		}
  2321  		if BuildAsmflags.present {
  2322  			appendSetting("-asmflags", BuildAsmflags.String())
  2323  		}
  2324  		appendSetting("-compiler", cfg.BuildContext.Compiler)
  2325  		if BuildGccgoflags.present && cfg.BuildContext.Compiler == "gccgo" {
  2326  			appendSetting("-gccgoflags", BuildGccgoflags.String())
  2327  		}
  2328  		if BuildGcflags.present && cfg.BuildContext.Compiler == "gc" {
  2329  			appendSetting("-gcflags", BuildGcflags.String())
  2330  		}
  2331  		if BuildLdflags.present {
  2332  			appendSetting("-ldflags", BuildLdflags.String())
  2333  		}
  2334  		if cfg.BuildMSan {
  2335  			appendSetting("-msan", "true")
  2336  		}
  2337  		if cfg.BuildRace {
  2338  			appendSetting("-race", "true")
  2339  		}
  2340  		if tags := cfg.BuildContext.BuildTags; len(tags) > 0 {
  2341  			appendSetting("-tags", strings.Join(tags, ","))
  2342  		}
  2343  		cgo := "0"
  2344  		if cfg.BuildContext.CgoEnabled {
  2345  			cgo = "1"
  2346  		}
  2347  		appendSetting("CGO_ENABLED", cgo)
  2348  		if cfg.BuildContext.CgoEnabled {
  2349  			for _, name := range []string{"CGO_CFLAGS", "CGO_CPPFLAGS", "CGO_CXXFLAGS", "CGO_LDFLAGS"} {
  2350  				appendSetting(name, cfg.Getenv(name))
  2351  			}
  2352  		}
  2353  		appendSetting("GOARCH", cfg.BuildContext.GOARCH)
  2354  		if cfg.GOEXPERIMENT != "" {
  2355  			appendSetting("GOEXPERIMENT", cfg.GOEXPERIMENT)
  2356  		}
  2357  		appendSetting("GOOS", cfg.BuildContext.GOOS)
  2358  		if key, val := cfg.GetArchEnv(); key != "" && val != "" {
  2359  			appendSetting(key, val)
  2360  		}
  2361  	}
  2362  
  2363  	// Add VCS status if all conditions are true:
  2364  	//
  2365  	// - -buildvcs is enabled.
  2366  	// - p is a non-test contained within a main module (there may be multiple
  2367  	//   main modules in a workspace, but local replacements don't count).
  2368  	// - Both the current directory and p's module's root directory are contained
  2369  	//   in the same local repository.
  2370  	// - We know the VCS commands needed to get the status.
  2371  	setVCSError := func(err error) {
  2372  		setPkgErrorf("error obtaining VCS status: %v\n\tUse -buildvcs=false to disable VCS stamping.", err)
  2373  	}
  2374  
  2375  	var repoDir string
  2376  	var vcsCmd *vcs.Cmd
  2377  	var err error
  2378  	const allowNesting = true
  2379  	if includeVCS && cfg.BuildBuildvcs != "false" && p.Module != nil && p.Module.Version == "" && !p.Standard && !p.IsTestOnly() {
  2380  		repoDir, vcsCmd, err = vcs.FromDir(base.Cwd(), "", allowNesting)
  2381  		if err != nil && !errors.Is(err, os.ErrNotExist) {
  2382  			setVCSError(err)
  2383  			return
  2384  		}
  2385  		if !str.HasFilePathPrefix(p.Module.Dir, repoDir) &&
  2386  			!str.HasFilePathPrefix(repoDir, p.Module.Dir) {
  2387  			// The module containing the main package does not overlap with the
  2388  			// repository containing the working directory. Don't include VCS info.
  2389  			// If the repo contains the module or vice versa, but they are not
  2390  			// the same directory, it's likely an error (see below).
  2391  			goto omitVCS
  2392  		}
  2393  		if cfg.BuildBuildvcs == "auto" && vcsCmd != nil && vcsCmd.Cmd != "" {
  2394  			if _, err := exec.LookPath(vcsCmd.Cmd); err != nil {
  2395  				// We fould a repository, but the required VCS tool is not present.
  2396  				// "-buildvcs=auto" means that we should silently drop the VCS metadata.
  2397  				goto omitVCS
  2398  			}
  2399  		}
  2400  	}
  2401  	if repoDir != "" && vcsCmd.Status != nil {
  2402  		// Check that the current directory, package, and module are in the same
  2403  		// repository. vcs.FromDir allows nested Git repositories, but nesting
  2404  		// is not allowed for other VCS tools. The current directory may be outside
  2405  		// p.Module.Dir when a workspace is used.
  2406  		pkgRepoDir, _, err := vcs.FromDir(p.Dir, "", allowNesting)
  2407  		if err != nil {
  2408  			setVCSError(err)
  2409  			return
  2410  		}
  2411  		if pkgRepoDir != repoDir {
  2412  			if cfg.BuildBuildvcs != "auto" {
  2413  				setVCSError(fmt.Errorf("main package is in repository %q but current directory is in repository %q", pkgRepoDir, repoDir))
  2414  				return
  2415  			}
  2416  			goto omitVCS
  2417  		}
  2418  		modRepoDir, _, err := vcs.FromDir(p.Module.Dir, "", allowNesting)
  2419  		if err != nil {
  2420  			setVCSError(err)
  2421  			return
  2422  		}
  2423  		if modRepoDir != repoDir {
  2424  			if cfg.BuildBuildvcs != "auto" {
  2425  				setVCSError(fmt.Errorf("main module is in repository %q but current directory is in repository %q", modRepoDir, repoDir))
  2426  				return
  2427  			}
  2428  			goto omitVCS
  2429  		}
  2430  
  2431  		type vcsStatusError struct {
  2432  			Status vcs.Status
  2433  			Err    error
  2434  		}
  2435  		cached := vcsStatusCache.Do(repoDir, func() any {
  2436  			st, err := vcsCmd.Status(vcsCmd, repoDir)
  2437  			return vcsStatusError{st, err}
  2438  		}).(vcsStatusError)
  2439  		if err := cached.Err; err != nil {
  2440  			setVCSError(err)
  2441  			return
  2442  		}
  2443  		st := cached.Status
  2444  
  2445  		appendSetting("vcs", vcsCmd.Cmd)
  2446  		if st.Revision != "" {
  2447  			appendSetting("vcs.revision", st.Revision)
  2448  		}
  2449  		if !st.CommitTime.IsZero() {
  2450  			stamp := st.CommitTime.UTC().Format(time.RFC3339Nano)
  2451  			appendSetting("vcs.time", stamp)
  2452  		}
  2453  		appendSetting("vcs.modified", strconv.FormatBool(st.Uncommitted))
  2454  	}
  2455  omitVCS:
  2456  
  2457  	p.Internal.BuildInfo = info.String()
  2458  }
  2459  
  2460  // SafeArg reports whether arg is a "safe" command-line argument,
  2461  // meaning that when it appears in a command-line, it probably
  2462  // doesn't have some special meaning other than its own name.
  2463  // Obviously args beginning with - are not safe (they look like flags).
  2464  // Less obviously, args beginning with @ are not safe (they look like
  2465  // GNU binutils flagfile specifiers, sometimes called "response files").
  2466  // To be conservative, we reject almost any arg beginning with non-alphanumeric ASCII.
  2467  // We accept leading . _ and / as likely in file system paths.
  2468  // There is a copy of this function in cmd/compile/internal/gc/noder.go.
  2469  func SafeArg(name string) bool {
  2470  	if name == "" {
  2471  		return false
  2472  	}
  2473  	c := name[0]
  2474  	return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
  2475  }
  2476  
  2477  // LinkerDeps returns the list of linker-induced dependencies for main package p.
  2478  func LinkerDeps(p *Package) []string {
  2479  	// Everything links runtime.
  2480  	deps := []string{"runtime"}
  2481  
  2482  	// External linking mode forces an import of runtime/cgo.
  2483  	if externalLinkingForced(p) && cfg.BuildContext.Compiler != "gccgo" {
  2484  		deps = append(deps, "runtime/cgo")
  2485  	}
  2486  	// On ARM with GOARM=5, it forces an import of math, for soft floating point.
  2487  	if cfg.Goarch == "arm" {
  2488  		deps = append(deps, "math")
  2489  	}
  2490  	// Using the race detector forces an import of runtime/race.
  2491  	if cfg.BuildRace {
  2492  		deps = append(deps, "runtime/race")
  2493  	}
  2494  	// Using memory sanitizer forces an import of runtime/msan.
  2495  	if cfg.BuildMSan {
  2496  		deps = append(deps, "runtime/msan")
  2497  	}
  2498  	// Using address sanitizer forces an import of runtime/asan.
  2499  	if cfg.BuildASan {
  2500  		deps = append(deps, "runtime/asan")
  2501  	}
  2502  
  2503  	return deps
  2504  }
  2505  
  2506  // externalLinkingForced reports whether external linking is being
  2507  // forced even for programs that do not use cgo.
  2508  func externalLinkingForced(p *Package) bool {
  2509  	if !cfg.BuildContext.CgoEnabled {
  2510  		return false
  2511  	}
  2512  
  2513  	// Some targets must use external linking even inside GOROOT.
  2514  	switch cfg.BuildContext.GOOS {
  2515  	case "android":
  2516  		if cfg.BuildContext.GOARCH != "arm64" {
  2517  			return true
  2518  		}
  2519  	case "ios":
  2520  		return true
  2521  	}
  2522  
  2523  	// Currently build modes c-shared, pie (on systems that do not
  2524  	// support PIE with internal linking mode (currently all
  2525  	// systems: issue #18968)), plugin, and -linkshared force
  2526  	// external linking mode, as of course does
  2527  	// -ldflags=-linkmode=external. External linking mode forces
  2528  	// an import of runtime/cgo.
  2529  	// If there are multiple -linkmode options, the last one wins.
  2530  	pieCgo := cfg.BuildBuildmode == "pie" && !sys.InternalLinkPIESupported(cfg.BuildContext.GOOS, cfg.BuildContext.GOARCH)
  2531  	linkmodeExternal := false
  2532  	if p != nil {
  2533  		ldflags := BuildLdflags.For(p)
  2534  		for i := len(ldflags) - 1; i >= 0; i-- {
  2535  			a := ldflags[i]
  2536  			if a == "-linkmode=external" ||
  2537  				a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "external" {
  2538  				linkmodeExternal = true
  2539  				break
  2540  			} else if a == "-linkmode=internal" ||
  2541  				a == "-linkmode" && i+1 < len(ldflags) && ldflags[i+1] == "internal" {
  2542  				break
  2543  			}
  2544  		}
  2545  	}
  2546  
  2547  	return cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal
  2548  }
  2549  
  2550  // mkAbs rewrites list, which must be paths relative to p.Dir,
  2551  // into a sorted list of absolute paths. It edits list in place but for
  2552  // convenience also returns list back to its caller.
  2553  func (p *Package) mkAbs(list []string) []string {
  2554  	for i, f := range list {
  2555  		list[i] = filepath.Join(p.Dir, f)
  2556  	}
  2557  	sort.Strings(list)
  2558  	return list
  2559  }
  2560  
  2561  // InternalGoFiles returns the list of Go files being built for the package,
  2562  // using absolute paths.
  2563  func (p *Package) InternalGoFiles() []string {
  2564  	return p.mkAbs(str.StringList(p.GoFiles, p.CgoFiles, p.TestGoFiles))
  2565  }
  2566  
  2567  // InternalXGoFiles returns the list of Go files being built for the XTest package,
  2568  // using absolute paths.
  2569  func (p *Package) InternalXGoFiles() []string {
  2570  	return p.mkAbs(p.XTestGoFiles)
  2571  }
  2572  
  2573  // InternalGoFiles returns the list of all Go files possibly relevant for the package,
  2574  // using absolute paths. "Possibly relevant" means that files are not excluded
  2575  // due to build tags, but files with names beginning with . or _ are still excluded.
  2576  func (p *Package) InternalAllGoFiles() []string {
  2577  	return p.mkAbs(str.StringList(p.IgnoredGoFiles, p.GoFiles, p.CgoFiles, p.TestGoFiles, p.XTestGoFiles))
  2578  }
  2579  
  2580  // usesSwig reports whether the package needs to run SWIG.
  2581  func (p *Package) UsesSwig() bool {
  2582  	return len(p.SwigFiles) > 0 || len(p.SwigCXXFiles) > 0
  2583  }
  2584  
  2585  // usesCgo reports whether the package needs to run cgo
  2586  func (p *Package) UsesCgo() bool {
  2587  	return len(p.CgoFiles) > 0
  2588  }
  2589  
  2590  // PackageList returns the list of packages in the dag rooted at roots
  2591  // as visited in a depth-first post-order traversal.
  2592  func PackageList(roots []*Package) []*Package {
  2593  	seen := map[*Package]bool{}
  2594  	all := []*Package{}
  2595  	var walk func(*Package)
  2596  	walk = func(p *Package) {
  2597  		if seen[p] {
  2598  			return
  2599  		}
  2600  		seen[p] = true
  2601  		for _, p1 := range p.Internal.Imports {
  2602  			walk(p1)
  2603  		}
  2604  		all = append(all, p)
  2605  	}
  2606  	for _, root := range roots {
  2607  		walk(root)
  2608  	}
  2609  	return all
  2610  }
  2611  
  2612  // TestPackageList returns the list of packages in the dag rooted at roots
  2613  // as visited in a depth-first post-order traversal, including the test
  2614  // imports of the roots. This ignores errors in test packages.
  2615  func TestPackageList(ctx context.Context, opts PackageOpts, roots []*Package) []*Package {
  2616  	seen := map[*Package]bool{}
  2617  	all := []*Package{}
  2618  	var walk func(*Package)
  2619  	walk = func(p *Package) {
  2620  		if seen[p] {
  2621  			return
  2622  		}
  2623  		seen[p] = true
  2624  		for _, p1 := range p.Internal.Imports {
  2625  			walk(p1)
  2626  		}
  2627  		all = append(all, p)
  2628  	}
  2629  	walkTest := func(root *Package, path string) {
  2630  		var stk ImportStack
  2631  		p1 := LoadImport(ctx, opts, path, root.Dir, root, &stk, root.Internal.Build.TestImportPos[path], ResolveImport)
  2632  		if p1.Error == nil {
  2633  			walk(p1)
  2634  		}
  2635  	}
  2636  	for _, root := range roots {
  2637  		walk(root)
  2638  		for _, path := range root.TestImports {
  2639  			walkTest(root, path)
  2640  		}
  2641  		for _, path := range root.XTestImports {
  2642  			walkTest(root, path)
  2643  		}
  2644  	}
  2645  	return all
  2646  }
  2647  
  2648  // LoadImportWithFlags loads the package with the given import path and
  2649  // sets tool flags on that package. This function is useful loading implicit
  2650  // dependencies (like sync/atomic for coverage).
  2651  // TODO(jayconrod): delete this function and set flags automatically
  2652  // in LoadImport instead.
  2653  func LoadImportWithFlags(path, srcDir string, parent *Package, stk *ImportStack, importPos []token.Position, mode int) *Package {
  2654  	p := LoadImport(context.TODO(), PackageOpts{}, path, srcDir, parent, stk, importPos, mode)
  2655  	setToolFlags(p)
  2656  	return p
  2657  }
  2658  
  2659  // PackageOpts control the behavior of PackagesAndErrors and other package
  2660  // loading functions.
  2661  type PackageOpts struct {
  2662  	// IgnoreImports controls whether we ignore explicit and implicit imports
  2663  	// when loading packages.  Implicit imports are added when supporting Cgo
  2664  	// or SWIG and when linking main packages.
  2665  	IgnoreImports bool
  2666  
  2667  	// ModResolveTests indicates whether calls to the module loader should also
  2668  	// resolve test dependencies of the requested packages.
  2669  	//
  2670  	// If ModResolveTests is true, then the module loader needs to resolve test
  2671  	// dependencies at the same time as packages; otherwise, the test dependencies
  2672  	// of those packages could be missing, and resolving those missing dependencies
  2673  	// could change the selected versions of modules that provide other packages.
  2674  	ModResolveTests bool
  2675  
  2676  	// MainOnly is true if the caller only wants to load main packages.
  2677  	// For a literal argument matching a non-main package, a stub may be returned
  2678  	// with an error. For a non-literal argument (with "..."), non-main packages
  2679  	// are not be matched, and their dependencies may not be loaded. A warning
  2680  	// may be printed for non-literal arguments that match no main packages.
  2681  	MainOnly bool
  2682  
  2683  	// LoadVCS controls whether we also load version-control metadata for main packages.
  2684  	LoadVCS bool
  2685  }
  2686  
  2687  // PackagesAndErrors returns the packages named by the command line arguments
  2688  // 'patterns'. If a named package cannot be loaded, PackagesAndErrors returns
  2689  // a *Package with the Error field describing the failure. If errors are found
  2690  // loading imported packages, the DepsErrors field is set. The Incomplete field
  2691  // may be set as well.
  2692  //
  2693  // To obtain a flat list of packages, use PackageList.
  2694  // To report errors loading packages, use ReportPackageErrors.
  2695  func PackagesAndErrors(ctx context.Context, opts PackageOpts, patterns []string) []*Package {
  2696  	ctx, span := trace.StartSpan(ctx, "load.PackagesAndErrors")
  2697  	defer span.Done()
  2698  
  2699  	for _, p := range patterns {
  2700  		// Listing is only supported with all patterns referring to either:
  2701  		// - Files that are part of the same directory.
  2702  		// - Explicit package paths or patterns.
  2703  		if strings.HasSuffix(p, ".go") {
  2704  			// We need to test whether the path is an actual Go file and not a
  2705  			// package path or pattern ending in '.go' (see golang.org/issue/34653).
  2706  			if fi, err := fsys.Stat(p); err == nil && !fi.IsDir() {
  2707  				return []*Package{GoFilesPackage(ctx, opts, patterns)}
  2708  			}
  2709  		}
  2710  	}
  2711  
  2712  	var matches []*search.Match
  2713  	if modload.Init(); cfg.ModulesEnabled {
  2714  		modOpts := modload.PackageOpts{
  2715  			ResolveMissingImports: true,
  2716  			LoadTests:             opts.ModResolveTests,
  2717  			SilencePackageErrors:  true,
  2718  		}
  2719  		matches, _ = modload.LoadPackages(ctx, modOpts, patterns...)
  2720  	} else {
  2721  		noModRoots := []string{}
  2722  		matches = search.ImportPaths(patterns, noModRoots)
  2723  	}
  2724  
  2725  	var (
  2726  		pkgs    []*Package
  2727  		stk     ImportStack
  2728  		seenPkg = make(map[*Package]bool)
  2729  	)
  2730  
  2731  	pre := newPreload()
  2732  	defer pre.flush()
  2733  	pre.preloadMatches(ctx, opts, matches)
  2734  
  2735  	for _, m := range matches {
  2736  		for _, pkg := range m.Pkgs {
  2737  			if pkg == "" {
  2738  				panic(fmt.Sprintf("ImportPaths returned empty package for pattern %s", m.Pattern()))
  2739  			}
  2740  			p := loadImport(ctx, opts, pre, pkg, base.Cwd(), nil, &stk, nil, 0)
  2741  			p.Match = append(p.Match, m.Pattern())
  2742  			p.Internal.CmdlinePkg = true
  2743  			if m.IsLiteral() {
  2744  				// Note: do not set = m.IsLiteral unconditionally
  2745  				// because maybe we'll see p matching both
  2746  				// a literal and also a non-literal pattern.
  2747  				p.Internal.CmdlinePkgLiteral = true
  2748  			}
  2749  			if seenPkg[p] {
  2750  				continue
  2751  			}
  2752  			seenPkg[p] = true
  2753  			pkgs = append(pkgs, p)
  2754  		}
  2755  
  2756  		if len(m.Errs) > 0 {
  2757  			// In addition to any packages that were actually resolved from the
  2758  			// pattern, there was some error in resolving the pattern itself.
  2759  			// Report it as a synthetic package.
  2760  			p := new(Package)
  2761  			p.ImportPath = m.Pattern()
  2762  			// Pass an empty ImportStack and nil importPos: the error arose from a pattern, not an import.
  2763  			var stk ImportStack
  2764  			var importPos []token.Position
  2765  			p.setLoadPackageDataError(m.Errs[0], m.Pattern(), &stk, importPos)
  2766  			p.Incomplete = true
  2767  			p.Match = append(p.Match, m.Pattern())
  2768  			p.Internal.CmdlinePkg = true
  2769  			if m.IsLiteral() {
  2770  				p.Internal.CmdlinePkgLiteral = true
  2771  			}
  2772  			pkgs = append(pkgs, p)
  2773  		}
  2774  	}
  2775  
  2776  	if opts.MainOnly {
  2777  		pkgs = mainPackagesOnly(pkgs, matches)
  2778  	}
  2779  
  2780  	// Now that CmdlinePkg is set correctly,
  2781  	// compute the effective flags for all loaded packages
  2782  	// (not just the ones matching the patterns but also
  2783  	// their dependencies).
  2784  	setToolFlags(pkgs...)
  2785  
  2786  	return pkgs
  2787  }
  2788  
  2789  // CheckPackageErrors prints errors encountered loading pkgs and their
  2790  // dependencies, then exits with a non-zero status if any errors were found.
  2791  func CheckPackageErrors(pkgs []*Package) {
  2792  	printed := map[*PackageError]bool{}
  2793  	for _, pkg := range pkgs {
  2794  		if pkg.Error != nil {
  2795  			base.Errorf("%v", pkg.Error)
  2796  			printed[pkg.Error] = true
  2797  		}
  2798  		for _, err := range pkg.DepsErrors {
  2799  			// Since these are errors in dependencies,
  2800  			// the same error might show up multiple times,
  2801  			// once in each package that depends on it.
  2802  			// Only print each once.
  2803  			if !printed[err] {
  2804  				printed[err] = true
  2805  				base.Errorf("%v", err)
  2806  			}
  2807  		}
  2808  	}
  2809  	base.ExitIfErrors()
  2810  
  2811  	// Check for duplicate loads of the same package.
  2812  	// That should be impossible, but if it does happen then
  2813  	// we end up trying to build the same package twice,
  2814  	// usually in parallel overwriting the same files,
  2815  	// which doesn't work very well.
  2816  	seen := map[string]bool{}
  2817  	reported := map[string]bool{}
  2818  	for _, pkg := range PackageList(pkgs) {
  2819  		if seen[pkg.ImportPath] && !reported[pkg.ImportPath] {
  2820  			reported[pkg.ImportPath] = true
  2821  			base.Errorf("internal error: duplicate loads of %s", pkg.ImportPath)
  2822  		}
  2823  		seen[pkg.ImportPath] = true
  2824  	}
  2825  	base.ExitIfErrors()
  2826  }
  2827  
  2828  // mainPackagesOnly filters out non-main packages matched only by arguments
  2829  // containing "..." and returns the remaining main packages.
  2830  //
  2831  // Packages with missing, invalid, or ambiguous names may be treated as
  2832  // possibly-main packages.
  2833  //
  2834  // mainPackagesOnly sets a non-main package's Error field and returns it if it
  2835  // is named by a literal argument.
  2836  //
  2837  // mainPackagesOnly prints warnings for non-literal arguments that only match
  2838  // non-main packages.
  2839  func mainPackagesOnly(pkgs []*Package, matches []*search.Match) []*Package {
  2840  	treatAsMain := map[string]bool{}
  2841  	for _, m := range matches {
  2842  		if m.IsLiteral() {
  2843  			for _, path := range m.Pkgs {
  2844  				treatAsMain[path] = true
  2845  			}
  2846  		}
  2847  	}
  2848  
  2849  	var mains []*Package
  2850  	for _, pkg := range pkgs {
  2851  		if pkg.Name == "main" {
  2852  			treatAsMain[pkg.ImportPath] = true
  2853  			mains = append(mains, pkg)
  2854  			continue
  2855  		}
  2856  
  2857  		if len(pkg.InvalidGoFiles) > 0 { // TODO(#45999): && pkg.Name == "", but currently go/build sets pkg.Name arbitrarily if it is ambiguous.
  2858  			// The package has (or may have) conflicting names, and we can't easily
  2859  			// tell whether one of them is "main". So assume that it could be, and
  2860  			// report an error for the package.
  2861  			treatAsMain[pkg.ImportPath] = true
  2862  		}
  2863  		if treatAsMain[pkg.ImportPath] {
  2864  			if pkg.Error == nil {
  2865  				pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
  2866  			}
  2867  			mains = append(mains, pkg)
  2868  		}
  2869  	}
  2870  
  2871  	for _, m := range matches {
  2872  		if m.IsLiteral() || len(m.Pkgs) == 0 {
  2873  			continue
  2874  		}
  2875  		foundMain := false
  2876  		for _, path := range m.Pkgs {
  2877  			if treatAsMain[path] {
  2878  				foundMain = true
  2879  				break
  2880  			}
  2881  		}
  2882  		if !foundMain {
  2883  			fmt.Fprintf(os.Stderr, "go: warning: %q matched only non-main packages\n", m.Pattern())
  2884  		}
  2885  	}
  2886  
  2887  	return mains
  2888  }
  2889  
  2890  type mainPackageError struct {
  2891  	importPath string
  2892  }
  2893  
  2894  func (e *mainPackageError) Error() string {
  2895  	return fmt.Sprintf("package %s is not a main package", e.importPath)
  2896  }
  2897  
  2898  func (e *mainPackageError) ImportPath() string {
  2899  	return e.importPath
  2900  }
  2901  
  2902  func setToolFlags(pkgs ...*Package) {
  2903  	for _, p := range PackageList(pkgs) {
  2904  		p.Internal.Asmflags = BuildAsmflags.For(p)
  2905  		p.Internal.Gcflags = BuildGcflags.For(p)
  2906  		p.Internal.Ldflags = BuildLdflags.For(p)
  2907  		p.Internal.Gccgoflags = BuildGccgoflags.For(p)
  2908  	}
  2909  }
  2910  
  2911  // GoFilesPackage creates a package for building a collection of Go files
  2912  // (typically named on the command line). The target is named p.a for
  2913  // package p or named after the first Go file for package main.
  2914  func GoFilesPackage(ctx context.Context, opts PackageOpts, gofiles []string) *Package {
  2915  	modload.Init()
  2916  
  2917  	for _, f := range gofiles {
  2918  		if !strings.HasSuffix(f, ".go") {
  2919  			pkg := new(Package)
  2920  			pkg.Internal.Local = true
  2921  			pkg.Internal.CmdlineFiles = true
  2922  			pkg.Name = f
  2923  			pkg.Error = &PackageError{
  2924  				Err: fmt.Errorf("named files must be .go files: %s", pkg.Name),
  2925  			}
  2926  			return pkg
  2927  		}
  2928  	}
  2929  
  2930  	var stk ImportStack
  2931  	ctxt := cfg.BuildContext
  2932  	ctxt.UseAllFiles = true
  2933  
  2934  	// Synthesize fake "directory" that only shows the named files,
  2935  	// to make it look like this is a standard package or
  2936  	// command directory. So that local imports resolve
  2937  	// consistently, the files must all be in the same directory.
  2938  	var dirent []fs.FileInfo
  2939  	var dir string
  2940  	for _, file := range gofiles {
  2941  		fi, err := fsys.Stat(file)
  2942  		if err != nil {
  2943  			base.Fatalf("%s", err)
  2944  		}
  2945  		if fi.IsDir() {
  2946  			base.Fatalf("%s is a directory, should be a Go file", file)
  2947  		}
  2948  		dir1 := filepath.Dir(file)
  2949  		if dir == "" {
  2950  			dir = dir1
  2951  		} else if dir != dir1 {
  2952  			base.Fatalf("named files must all be in one directory; have %s and %s", dir, dir1)
  2953  		}
  2954  		dirent = append(dirent, fi)
  2955  	}
  2956  	ctxt.ReadDir = func(string) ([]fs.FileInfo, error) { return dirent, nil }
  2957  
  2958  	if cfg.ModulesEnabled {
  2959  		modload.ImportFromFiles(ctx, gofiles)
  2960  	}
  2961  
  2962  	var err error
  2963  	if dir == "" {
  2964  		dir = base.Cwd()
  2965  	}
  2966  	dir, err = filepath.Abs(dir)
  2967  	if err != nil {
  2968  		base.Fatalf("%s", err)
  2969  	}
  2970  
  2971  	bp, err := ctxt.ImportDir(dir, 0)
  2972  	pkg := new(Package)
  2973  	pkg.Internal.Local = true
  2974  	pkg.Internal.CmdlineFiles = true
  2975  	pkg.load(ctx, opts, "command-line-arguments", &stk, nil, bp, err)
  2976  	if !cfg.ModulesEnabled {
  2977  		pkg.Internal.LocalPrefix = dirToImportPath(dir)
  2978  	}
  2979  	pkg.ImportPath = "command-line-arguments"
  2980  	pkg.Target = ""
  2981  	pkg.Match = gofiles
  2982  
  2983  	if pkg.Name == "main" {
  2984  		exe := pkg.DefaultExecName() + cfg.ExeSuffix
  2985  
  2986  		if cfg.GOBIN != "" {
  2987  			pkg.Target = filepath.Join(cfg.GOBIN, exe)
  2988  		} else if cfg.ModulesEnabled {
  2989  			pkg.Target = filepath.Join(modload.BinDir(), exe)
  2990  		}
  2991  	}
  2992  
  2993  	if opts.MainOnly && pkg.Name != "main" && pkg.Error == nil {
  2994  		pkg.Error = &PackageError{Err: &mainPackageError{importPath: pkg.ImportPath}}
  2995  	}
  2996  	setToolFlags(pkg)
  2997  
  2998  	return pkg
  2999  }
  3000  
  3001  // PackagesAndErrorsOutsideModule is like PackagesAndErrors but runs in
  3002  // module-aware mode and ignores the go.mod file in the current directory or any
  3003  // parent directory, if there is one. This is used in the implementation of 'go
  3004  // install pkg@version' and other commands that support similar forms.
  3005  //
  3006  // modload.ForceUseModules must be true, and modload.RootMode must be NoRoot
  3007  // before calling this function.
  3008  //
  3009  // PackagesAndErrorsOutsideModule imposes several constraints to avoid
  3010  // ambiguity. All arguments must have the same version suffix (not just a suffix
  3011  // that resolves to the same version). They must refer to packages in the same
  3012  // module, which must not be std or cmd. That module is not considered the main
  3013  // module, but its go.mod file (if it has one) must not contain directives that
  3014  // would cause it to be interpreted differently if it were the main module
  3015  // (replace, exclude).
  3016  func PackagesAndErrorsOutsideModule(ctx context.Context, opts PackageOpts, args []string) ([]*Package, error) {
  3017  	if !modload.ForceUseModules {
  3018  		panic("modload.ForceUseModules must be true")
  3019  	}
  3020  	if modload.RootMode != modload.NoRoot {
  3021  		panic("modload.RootMode must be NoRoot")
  3022  	}
  3023  
  3024  	// Check that the arguments satisfy syntactic constraints.
  3025  	var version string
  3026  	for _, arg := range args {
  3027  		if i := strings.Index(arg, "@"); i >= 0 {
  3028  			version = arg[i+1:]
  3029  			if version == "" {
  3030  				return nil, fmt.Errorf("%s: version must not be empty", arg)
  3031  			}
  3032  			break
  3033  		}
  3034  	}
  3035  	patterns := make([]string, len(args))
  3036  	for i, arg := range args {
  3037  		if !strings.HasSuffix(arg, "@"+version) {
  3038  			return nil, fmt.Errorf("%s: all arguments must have the same version (@%s)", arg, version)
  3039  		}
  3040  		p := arg[:len(arg)-len(version)-1]
  3041  		switch {
  3042  		case build.IsLocalImport(p):
  3043  			return nil, fmt.Errorf("%s: argument must be a package path, not a relative path", arg)
  3044  		case filepath.IsAbs(p):
  3045  			return nil, fmt.Errorf("%s: argument must be a package path, not an absolute path", arg)
  3046  		case search.IsMetaPackage(p):
  3047  			return nil, fmt.Errorf("%s: argument must be a package path, not a meta-package", arg)
  3048  		case path.Clean(p) != p:
  3049  			return nil, fmt.Errorf("%s: argument must be a clean package path", arg)
  3050  		case !strings.Contains(p, "...") && search.IsStandardImportPath(p) && goroot.IsStandardPackage(cfg.GOROOT, cfg.BuildContext.Compiler, p):
  3051  			return nil, fmt.Errorf("%s: argument must not be a package in the standard library", arg)
  3052  		default:
  3053  			patterns[i] = p
  3054  		}
  3055  	}
  3056  
  3057  	// Query the module providing the first argument, load its go.mod file, and
  3058  	// check that it doesn't contain directives that would cause it to be
  3059  	// interpreted differently if it were the main module.
  3060  	//
  3061  	// If multiple modules match the first argument, accept the longest match
  3062  	// (first result). It's possible this module won't provide packages named by
  3063  	// later arguments, and other modules would. Let's not try to be too
  3064  	// magical though.
  3065  	allowed := modload.CheckAllowed
  3066  	if modload.IsRevisionQuery(version) {
  3067  		// Don't check for retractions if a specific revision is requested.
  3068  		allowed = nil
  3069  	}
  3070  	noneSelected := func(path string) (version string) { return "none" }
  3071  	qrs, err := modload.QueryPackages(ctx, patterns[0], version, noneSelected, allowed)
  3072  	if err != nil {
  3073  		return nil, fmt.Errorf("%s: %w", args[0], err)
  3074  	}
  3075  	rootMod := qrs[0].Mod
  3076  	data, err := modfetch.GoMod(rootMod.Path, rootMod.Version)
  3077  	if err != nil {
  3078  		return nil, fmt.Errorf("%s: %w", args[0], err)
  3079  	}
  3080  	f, err := modfile.Parse("go.mod", data, nil)
  3081  	if err != nil {
  3082  		return nil, fmt.Errorf("%s (in %s): %w", args[0], rootMod, err)
  3083  	}
  3084  	directiveFmt := "%s (in %s):\n" +
  3085  		"\tThe go.mod file for the module providing named packages contains one or\n" +
  3086  		"\tmore %s directives. It must not contain directives that would cause\n" +
  3087  		"\tit to be interpreted differently than if it were the main module."
  3088  	if len(f.Replace) > 0 {
  3089  		return nil, fmt.Errorf(directiveFmt, args[0], rootMod, "replace")
  3090  	}
  3091  	if len(f.Exclude) > 0 {
  3092  		return nil, fmt.Errorf(directiveFmt, args[0], rootMod, "exclude")
  3093  	}
  3094  
  3095  	// Since we are in NoRoot mode, the build list initially contains only
  3096  	// the dummy command-line-arguments module. Add a requirement on the
  3097  	// module that provides the packages named on the command line.
  3098  	if _, err := modload.EditBuildList(ctx, nil, []module.Version{rootMod}); err != nil {
  3099  		return nil, fmt.Errorf("%s: %w", args[0], err)
  3100  	}
  3101  
  3102  	// Load packages for all arguments.
  3103  	pkgs := PackagesAndErrors(ctx, opts, patterns)
  3104  
  3105  	// Check that named packages are all provided by the same module.
  3106  	for _, pkg := range pkgs {
  3107  		var pkgErr error
  3108  		if pkg.Module == nil {
  3109  			// Packages in std, cmd, and their vendored dependencies
  3110  			// don't have this field set.
  3111  			pkgErr = fmt.Errorf("package %s not provided by module %s", pkg.ImportPath, rootMod)
  3112  		} else if pkg.Module.Path != rootMod.Path || pkg.Module.Version != rootMod.Version {
  3113  			pkgErr = fmt.Errorf("package %s provided by module %s@%s\n\tAll packages must be provided by the same module (%s).", pkg.ImportPath, pkg.Module.Path, pkg.Module.Version, rootMod)
  3114  		}
  3115  		if pkgErr != nil && pkg.Error == nil {
  3116  			pkg.Error = &PackageError{Err: pkgErr}
  3117  		}
  3118  	}
  3119  
  3120  	matchers := make([]func(string) bool, len(patterns))
  3121  	for i, p := range patterns {
  3122  		if strings.Contains(p, "...") {
  3123  			matchers[i] = search.MatchPattern(p)
  3124  		}
  3125  	}
  3126  	return pkgs, nil
  3127  }
  3128  

View as plain text