Source file src/cmd/go/internal/cfg/cfg.go

     1  // Copyright 2017 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 cfg holds configuration shared by multiple parts
     6  // of the go command.
     7  package cfg
     8  
     9  import (
    10  	"bytes"
    11  	"context"
    12  	"fmt"
    13  	"go/build"
    14  	"internal/buildcfg"
    15  	"internal/cfg"
    16  	"io"
    17  	"io/fs"
    18  	"os"
    19  	"path/filepath"
    20  	"runtime"
    21  	"strings"
    22  	"sync"
    23  	"time"
    24  
    25  	"cmd/go/internal/fsys"
    26  	"cmd/internal/pathcache"
    27  )
    28  
    29  // Global build parameters (used during package load)
    30  var (
    31  	Goos   = envOr("GOOS", build.Default.GOOS)
    32  	Goarch = envOr("GOARCH", build.Default.GOARCH)
    33  
    34  	ExeSuffix = exeSuffix()
    35  
    36  	// ModulesEnabled specifies whether the go command is running
    37  	// in module-aware mode (as opposed to GOPATH mode).
    38  	// It is equal to modload.Enabled, but not all packages can import modload.
    39  	ModulesEnabled bool
    40  )
    41  
    42  func exeSuffix() string {
    43  	if Goos == "windows" {
    44  		return ".exe"
    45  	}
    46  	return ""
    47  }
    48  
    49  // Configuration for tools installed to GOROOT/bin.
    50  // Normally these match runtime.GOOS and runtime.GOARCH,
    51  // but when testing a cross-compiled cmd/go they will
    52  // indicate the GOOS and GOARCH of the installed cmd/go
    53  // rather than the test binary.
    54  var (
    55  	installedGOOS   string
    56  	installedGOARCH string
    57  )
    58  
    59  // ToolExeSuffix returns the suffix for executables installed
    60  // in build.ToolDir.
    61  func ToolExeSuffix() string {
    62  	if installedGOOS == "windows" {
    63  		return ".exe"
    64  	}
    65  	return ""
    66  }
    67  
    68  // These are general "build flags" used by build and other commands.
    69  var (
    70  	BuildA                 bool     // -a flag
    71  	BuildBuildmode         string   // -buildmode flag
    72  	BuildBuildvcs          = "auto" // -buildvcs flag: "true", "false", or "auto"
    73  	BuildContext           = defaultContext()
    74  	BuildMod               string                  // -mod flag
    75  	BuildModExplicit       bool                    // whether -mod was set explicitly
    76  	BuildModReason         string                  // reason -mod was set, if set by default
    77  	BuildLinkshared        bool                    // -linkshared flag
    78  	BuildMSan              bool                    // -msan flag
    79  	BuildASan              bool                    // -asan flag
    80  	BuildCover             bool                    // -cover flag
    81  	BuildCoverMode         string                  // -covermode flag
    82  	BuildCoverPkg          []string                // -coverpkg flag
    83  	BuildJSON              bool                    // -json flag
    84  	BuildN                 bool                    // -n flag
    85  	BuildO                 string                  // -o flag
    86  	BuildP                 = runtime.GOMAXPROCS(0) // -p flag
    87  	BuildPGO               string                  // -pgo flag
    88  	BuildPkgdir            string                  // -pkgdir flag
    89  	BuildRace              bool                    // -race flag
    90  	BuildToolexec          []string                // -toolexec flag
    91  	BuildToolchainName     string
    92  	BuildToolchainCompiler func() string
    93  	BuildToolchainLinker   func() string
    94  	BuildTrimpath          bool // -trimpath flag
    95  	BuildV                 bool // -v flag
    96  	BuildWork              bool // -work flag
    97  	BuildX                 bool // -x flag
    98  
    99  	ModCacheRW bool   // -modcacherw flag
   100  	ModFile    string // -modfile flag
   101  
   102  	CmdName string // "build", "install", "list", "mod tidy", etc.
   103  
   104  	DebugActiongraph  string // -debug-actiongraph flag (undocumented, unstable)
   105  	DebugTrace        string // -debug-trace flag
   106  	DebugRuntimeTrace string // -debug-runtime-trace flag (undocumented, unstable)
   107  
   108  	// GoPathError is set when GOPATH is not set. it contains an
   109  	// explanation why GOPATH is unset.
   110  	GoPathError   string
   111  	GOPATHChanged bool
   112  	CGOChanged    bool
   113  )
   114  
   115  func defaultContext() build.Context {
   116  	ctxt := build.Default
   117  
   118  	ctxt.JoinPath = filepath.Join // back door to say "do not use go command"
   119  
   120  	// Override defaults computed in go/build with defaults
   121  	// from go environment configuration file, if known.
   122  	ctxt.GOPATH, GOPATHChanged = EnvOrAndChanged("GOPATH", gopath(ctxt))
   123  	ctxt.GOOS = Goos
   124  	ctxt.GOARCH = Goarch
   125  
   126  	// Clear the GOEXPERIMENT-based tool tags, which we will recompute later.
   127  	var save []string
   128  	for _, tag := range ctxt.ToolTags {
   129  		if !strings.HasPrefix(tag, "goexperiment.") {
   130  			save = append(save, tag)
   131  		}
   132  	}
   133  	ctxt.ToolTags = save
   134  
   135  	// The go/build rule for whether cgo is enabled is:
   136  	//  1. If $CGO_ENABLED is set, respect it.
   137  	//  2. Otherwise, if this is a cross-compile, disable cgo.
   138  	//  3. Otherwise, use built-in default for GOOS/GOARCH.
   139  	//
   140  	// Recreate that logic here with the new GOOS/GOARCH setting.
   141  	// We need to run steps 2 and 3 to determine what the default value
   142  	// of CgoEnabled would be for computing CGOChanged.
   143  	defaultCgoEnabled := ctxt.CgoEnabled
   144  	if ctxt.GOOS != runtime.GOOS || ctxt.GOARCH != runtime.GOARCH {
   145  		defaultCgoEnabled = false
   146  	} else {
   147  		// Use built-in default cgo setting for GOOS/GOARCH.
   148  		// Note that ctxt.GOOS/GOARCH are derived from the preference list
   149  		// (1) environment, (2) go/env file, (3) runtime constants,
   150  		// while go/build.Default.GOOS/GOARCH are derived from the preference list
   151  		// (1) environment, (2) runtime constants.
   152  		//
   153  		// We know ctxt.GOOS/GOARCH == runtime.GOOS/GOARCH;
   154  		// no matter how that happened, go/build.Default will make the
   155  		// same decision (either the environment variables are set explicitly
   156  		// to match the runtime constants, or else they are unset, in which
   157  		// case go/build falls back to the runtime constants), so
   158  		// go/build.Default.GOOS/GOARCH == runtime.GOOS/GOARCH.
   159  		// So ctxt.CgoEnabled (== go/build.Default.CgoEnabled) is correct
   160  		// as is and can be left unmodified.
   161  		//
   162  		// All that said, starting in Go 1.20 we layer one more rule
   163  		// on top of the go/build decision: if CC is unset and
   164  		// the default C compiler we'd look for is not in the PATH,
   165  		// we automatically default cgo to off.
   166  		// This makes go builds work automatically on systems
   167  		// without a C compiler installed.
   168  		if ctxt.CgoEnabled {
   169  			if os.Getenv("CC") == "" {
   170  				cc := DefaultCC(ctxt.GOOS, ctxt.GOARCH)
   171  				if _, err := pathcache.LookPath(cc); err != nil {
   172  					defaultCgoEnabled = false
   173  				}
   174  			}
   175  		}
   176  	}
   177  	ctxt.CgoEnabled = defaultCgoEnabled
   178  	if v := Getenv("CGO_ENABLED"); v == "0" || v == "1" {
   179  		ctxt.CgoEnabled = v[0] == '1'
   180  	}
   181  	CGOChanged = ctxt.CgoEnabled != defaultCgoEnabled
   182  
   183  	ctxt.OpenFile = func(path string) (io.ReadCloser, error) {
   184  		return fsys.Open(path)
   185  	}
   186  	ctxt.ReadDir = func(path string) ([]fs.FileInfo, error) {
   187  		// Convert []fs.DirEntry to []fs.FileInfo using dirInfo.
   188  		dirs, err := fsys.ReadDir(path)
   189  		infos := make([]fs.FileInfo, len(dirs))
   190  		for i, dir := range dirs {
   191  			infos[i] = &dirInfo{dir}
   192  		}
   193  		return infos, err
   194  	}
   195  	ctxt.IsDir = func(path string) bool {
   196  		isDir, err := fsys.IsDir(path)
   197  		return err == nil && isDir
   198  	}
   199  
   200  	return ctxt
   201  }
   202  
   203  func init() {
   204  	SetGOROOT(Getenv("GOROOT"), false)
   205  }
   206  
   207  // SetGOROOT sets GOROOT and associated variables to the given values.
   208  //
   209  // If isTestGo is true, build.ToolDir is set based on the TESTGO_GOHOSTOS and
   210  // TESTGO_GOHOSTARCH environment variables instead of runtime.GOOS and
   211  // runtime.GOARCH.
   212  func SetGOROOT(goroot string, isTestGo bool) {
   213  	BuildContext.GOROOT = goroot
   214  
   215  	GOROOT = goroot
   216  	if goroot == "" {
   217  		GOROOTbin = ""
   218  		GOROOTpkg = ""
   219  		GOROOTsrc = ""
   220  	} else {
   221  		GOROOTbin = filepath.Join(goroot, "bin")
   222  		GOROOTpkg = filepath.Join(goroot, "pkg")
   223  		GOROOTsrc = filepath.Join(goroot, "src")
   224  	}
   225  
   226  	installedGOOS = runtime.GOOS
   227  	installedGOARCH = runtime.GOARCH
   228  	if isTestGo {
   229  		if testOS := os.Getenv("TESTGO_GOHOSTOS"); testOS != "" {
   230  			installedGOOS = testOS
   231  		}
   232  		if testArch := os.Getenv("TESTGO_GOHOSTARCH"); testArch != "" {
   233  			installedGOARCH = testArch
   234  		}
   235  	}
   236  
   237  	if runtime.Compiler != "gccgo" {
   238  		if goroot == "" {
   239  			build.ToolDir = ""
   240  		} else {
   241  			// Note that we must use the installed OS and arch here: the tool
   242  			// directory does not move based on environment variables, and even if we
   243  			// are testing a cross-compiled cmd/go all of the installed packages and
   244  			// tools would have been built using the native compiler and linker (and
   245  			// would spuriously appear stale if we used a cross-compiled compiler and
   246  			// linker).
   247  			//
   248  			// This matches the initialization of ToolDir in go/build, except for
   249  			// using ctxt.GOROOT and the installed GOOS and GOARCH rather than the
   250  			// GOROOT, GOOS, and GOARCH reported by the runtime package.
   251  			build.ToolDir = filepath.Join(GOROOTpkg, "tool", installedGOOS+"_"+installedGOARCH)
   252  		}
   253  	}
   254  }
   255  
   256  // Experiment configuration.
   257  var (
   258  	// RawGOEXPERIMENT is the GOEXPERIMENT value set by the user.
   259  	RawGOEXPERIMENT = envOr("GOEXPERIMENT", buildcfg.DefaultGOEXPERIMENT)
   260  	// CleanGOEXPERIMENT is the minimal GOEXPERIMENT value needed to reproduce the
   261  	// experiments enabled by RawGOEXPERIMENT.
   262  	CleanGOEXPERIMENT = RawGOEXPERIMENT
   263  
   264  	Experiment    *buildcfg.ExperimentFlags
   265  	ExperimentErr error
   266  )
   267  
   268  func init() {
   269  	Experiment, ExperimentErr = buildcfg.ParseGOEXPERIMENT(Goos, Goarch, RawGOEXPERIMENT)
   270  	if ExperimentErr != nil {
   271  		return
   272  	}
   273  
   274  	// GOEXPERIMENT is valid, so convert it to canonical form.
   275  	CleanGOEXPERIMENT = Experiment.String()
   276  
   277  	// Add build tags based on the experiments in effect.
   278  	exps := Experiment.Enabled()
   279  	expTags := make([]string, 0, len(exps)+len(BuildContext.ToolTags))
   280  	for _, exp := range exps {
   281  		expTags = append(expTags, "goexperiment."+exp)
   282  	}
   283  	BuildContext.ToolTags = append(expTags, BuildContext.ToolTags...)
   284  }
   285  
   286  // An EnvVar is an environment variable Name=Value.
   287  type EnvVar struct {
   288  	Name    string
   289  	Value   string
   290  	Changed bool // effective Value differs from default
   291  }
   292  
   293  // OrigEnv is the original environment of the program at startup.
   294  var OrigEnv []string
   295  
   296  // CmdEnv is the new environment for running go tool commands.
   297  // User binaries (during go test or go run) are run with OrigEnv,
   298  // not CmdEnv.
   299  var CmdEnv []EnvVar
   300  
   301  var envCache struct {
   302  	once   sync.Once
   303  	m      map[string]string
   304  	goroot map[string]string
   305  }
   306  
   307  // EnvFile returns the name of the Go environment configuration file,
   308  // and reports whether the effective value differs from the default.
   309  func EnvFile() (string, bool, error) {
   310  	if file := os.Getenv("GOENV"); file != "" {
   311  		if file == "off" {
   312  			return "", false, fmt.Errorf("GOENV=off")
   313  		}
   314  		return file, true, nil
   315  	}
   316  	dir, err := os.UserConfigDir()
   317  	if err != nil {
   318  		return "", false, err
   319  	}
   320  	if dir == "" {
   321  		return "", false, fmt.Errorf("missing user-config dir")
   322  	}
   323  	return filepath.Join(dir, "go/env"), false, nil
   324  }
   325  
   326  func initEnvCache() {
   327  	envCache.m = make(map[string]string)
   328  	envCache.goroot = make(map[string]string)
   329  	if file, _, _ := EnvFile(); file != "" {
   330  		readEnvFile(file, "user")
   331  	}
   332  	goroot := findGOROOT(envCache.m["GOROOT"])
   333  	if goroot != "" {
   334  		readEnvFile(filepath.Join(goroot, "go.env"), "GOROOT")
   335  	}
   336  
   337  	// Save the goroot for func init calling SetGOROOT,
   338  	// and also overwrite anything that might have been in go.env.
   339  	// It makes no sense for GOROOT/go.env to specify
   340  	// a different GOROOT.
   341  	envCache.m["GOROOT"] = goroot
   342  }
   343  
   344  func readEnvFile(file string, source string) {
   345  	if file == "" {
   346  		return
   347  	}
   348  	data, err := os.ReadFile(file)
   349  	if err != nil {
   350  		return
   351  	}
   352  
   353  	for len(data) > 0 {
   354  		// Get next line.
   355  		line := data
   356  		i := bytes.IndexByte(data, '\n')
   357  		if i >= 0 {
   358  			line, data = line[:i], data[i+1:]
   359  		} else {
   360  			data = nil
   361  		}
   362  
   363  		i = bytes.IndexByte(line, '=')
   364  		if i < 0 || line[0] < 'A' || 'Z' < line[0] {
   365  			// Line is missing = (or empty) or a comment or not a valid env name. Ignore.
   366  			// This should not happen in the user file, since the file should be maintained almost
   367  			// exclusively by "go env -w", but better to silently ignore than to make
   368  			// the go command unusable just because somehow the env file has
   369  			// gotten corrupted.
   370  			// In the GOROOT/go.env file, we expect comments.
   371  			continue
   372  		}
   373  		key, val := line[:i], line[i+1:]
   374  
   375  		if source == "GOROOT" {
   376  			envCache.goroot[string(key)] = string(val)
   377  			// In the GOROOT/go.env file, do not overwrite fields loaded from the user's go/env file.
   378  			if _, ok := envCache.m[string(key)]; ok {
   379  				continue
   380  			}
   381  		}
   382  		envCache.m[string(key)] = string(val)
   383  	}
   384  }
   385  
   386  // Getenv gets the value for the configuration key.
   387  // It consults the operating system environment
   388  // and then the go/env file.
   389  // If Getenv is called for a key that cannot be set
   390  // in the go/env file (for example GODEBUG), it panics.
   391  // This ensures that CanGetenv is accurate, so that
   392  // 'go env -w' stays in sync with what Getenv can retrieve.
   393  func Getenv(key string) string {
   394  	if !CanGetenv(key) {
   395  		switch key {
   396  		case "CGO_TEST_ALLOW", "CGO_TEST_DISALLOW", "CGO_test_ALLOW", "CGO_test_DISALLOW":
   397  			// used by internal/work/security_test.go; allow
   398  		default:
   399  			panic("internal error: invalid Getenv " + key)
   400  		}
   401  	}
   402  	val := os.Getenv(key)
   403  	if val != "" {
   404  		return val
   405  	}
   406  	envCache.once.Do(initEnvCache)
   407  	return envCache.m[key]
   408  }
   409  
   410  // CanGetenv reports whether key is a valid go/env configuration key.
   411  func CanGetenv(key string) bool {
   412  	envCache.once.Do(initEnvCache)
   413  	if _, ok := envCache.m[key]; ok {
   414  		// Assume anything in the user file or go.env file is valid.
   415  		return true
   416  	}
   417  	return strings.Contains(cfg.KnownEnv, "\t"+key+"\n")
   418  }
   419  
   420  var (
   421  	GOROOT string
   422  
   423  	// Either empty or produced by filepath.Join(GOROOT, …).
   424  	GOROOTbin string
   425  	GOROOTpkg string
   426  	GOROOTsrc string
   427  
   428  	GOBIN                           = Getenv("GOBIN")
   429  	GOCACHEPROG, GOCACHEPROGChanged = EnvOrAndChanged("GOCACHEPROG", "")
   430  	GOMODCACHE, GOMODCACHEChanged   = EnvOrAndChanged("GOMODCACHE", gopathDir("pkg/mod"))
   431  
   432  	// Used in envcmd.MkEnv and build ID computations.
   433  	GOARM64, goARM64Changed     = EnvOrAndChanged("GOARM64", buildcfg.DefaultGOARM64)
   434  	GOARM, goARMChanged         = EnvOrAndChanged("GOARM", buildcfg.DefaultGOARM)
   435  	GO386, go386Changed         = EnvOrAndChanged("GO386", buildcfg.DefaultGO386)
   436  	GOAMD64, goAMD64Changed     = EnvOrAndChanged("GOAMD64", buildcfg.DefaultGOAMD64)
   437  	GOMIPS, goMIPSChanged       = EnvOrAndChanged("GOMIPS", buildcfg.DefaultGOMIPS)
   438  	GOMIPS64, goMIPS64Changed   = EnvOrAndChanged("GOMIPS64", buildcfg.DefaultGOMIPS64)
   439  	GOPPC64, goPPC64Changed     = EnvOrAndChanged("GOPPC64", buildcfg.DefaultGOPPC64)
   440  	GORISCV64, goRISCV64Changed = EnvOrAndChanged("GORISCV64", buildcfg.DefaultGORISCV64)
   441  	GOWASM, goWASMChanged       = EnvOrAndChanged("GOWASM", fmt.Sprint(buildcfg.GOWASM))
   442  
   443  	GOFIPS140, GOFIPS140Changed = EnvOrAndChanged("GOFIPS140", buildcfg.DefaultGOFIPS140)
   444  	GOPROXY, GOPROXYChanged     = EnvOrAndChanged("GOPROXY", "")
   445  	GOSUMDB, GOSUMDBChanged     = EnvOrAndChanged("GOSUMDB", "")
   446  	GOPRIVATE                   = Getenv("GOPRIVATE")
   447  	GONOPROXY, GONOPROXYChanged = EnvOrAndChanged("GONOPROXY", GOPRIVATE)
   448  	GONOSUMDB, GONOSUMDBChanged = EnvOrAndChanged("GONOSUMDB", GOPRIVATE)
   449  	GOINSECURE                  = Getenv("GOINSECURE")
   450  	GOVCS                       = Getenv("GOVCS")
   451  	GOAUTH, GOAUTHChanged       = EnvOrAndChanged("GOAUTH", "netrc")
   452  )
   453  
   454  // EnvOrAndChanged returns the environment variable value
   455  // and reports whether it differs from the default value.
   456  func EnvOrAndChanged(name, def string) (v string, changed bool) {
   457  	val := Getenv(name)
   458  	if val != "" {
   459  		v = val
   460  		if g, ok := envCache.goroot[name]; ok {
   461  			changed = val != g
   462  		} else {
   463  			changed = val != def
   464  		}
   465  		return v, changed
   466  	}
   467  	return def, false
   468  }
   469  
   470  var SumdbDir = gopathDir("pkg/sumdb")
   471  
   472  // GetArchEnv returns the name and setting of the
   473  // GOARCH-specific architecture environment variable.
   474  // If the current architecture has no GOARCH-specific variable,
   475  // GetArchEnv returns empty key and value.
   476  func GetArchEnv() (key, val string, changed bool) {
   477  	switch Goarch {
   478  	case "arm":
   479  		return "GOARM", GOARM, goARMChanged
   480  	case "arm64":
   481  		return "GOARM64", GOARM64, goARM64Changed
   482  	case "386":
   483  		return "GO386", GO386, go386Changed
   484  	case "amd64":
   485  		return "GOAMD64", GOAMD64, goAMD64Changed
   486  	case "mips", "mipsle":
   487  		return "GOMIPS", GOMIPS, goMIPSChanged
   488  	case "mips64", "mips64le":
   489  		return "GOMIPS64", GOMIPS64, goMIPS64Changed
   490  	case "ppc64", "ppc64le":
   491  		return "GOPPC64", GOPPC64, goPPC64Changed
   492  	case "riscv64":
   493  		return "GORISCV64", GORISCV64, goRISCV64Changed
   494  	case "wasm":
   495  		return "GOWASM", GOWASM, goWASMChanged
   496  	}
   497  	return "", "", false
   498  }
   499  
   500  // envOr returns Getenv(key) if set, or else def.
   501  func envOr(key, def string) string {
   502  	val := Getenv(key)
   503  	if val == "" {
   504  		val = def
   505  	}
   506  	return val
   507  }
   508  
   509  // There is a copy of findGOROOT, isSameDir, and isGOROOT in
   510  // x/tools/cmd/godoc/goroot.go.
   511  // Try to keep them in sync for now.
   512  
   513  // findGOROOT returns the GOROOT value, using either an explicitly
   514  // provided environment variable, a GOROOT that contains the current
   515  // os.Executable value, or else the GOROOT that the binary was built
   516  // with from runtime.GOROOT().
   517  //
   518  // There is a copy of this code in x/tools/cmd/godoc/goroot.go.
   519  func findGOROOT(env string) string {
   520  	if env == "" {
   521  		// Not using Getenv because findGOROOT is called
   522  		// to find the GOROOT/go.env file. initEnvCache
   523  		// has passed in the setting from the user go/env file.
   524  		env = os.Getenv("GOROOT")
   525  	}
   526  	if env != "" {
   527  		return filepath.Clean(env)
   528  	}
   529  	def := ""
   530  	if r := runtime.GOROOT(); r != "" {
   531  		def = filepath.Clean(r)
   532  	}
   533  	if runtime.Compiler == "gccgo" {
   534  		// gccgo has no real GOROOT, and it certainly doesn't
   535  		// depend on the executable's location.
   536  		return def
   537  	}
   538  
   539  	// canonical returns a directory path that represents
   540  	// the same directory as dir,
   541  	// preferring the spelling in def if the two are the same.
   542  	canonical := func(dir string) string {
   543  		if isSameDir(def, dir) {
   544  			return def
   545  		}
   546  		return dir
   547  	}
   548  
   549  	exe, err := os.Executable()
   550  	if err == nil {
   551  		exe, err = filepath.Abs(exe)
   552  		if err == nil {
   553  			// cmd/go may be installed in GOROOT/bin or GOROOT/bin/GOOS_GOARCH,
   554  			// depending on whether it was cross-compiled with a different
   555  			// GOHOSTOS (see https://go.dev/issue/62119). Try both.
   556  			if dir := filepath.Join(exe, "../.."); isGOROOT(dir) {
   557  				return canonical(dir)
   558  			}
   559  			if dir := filepath.Join(exe, "../../.."); isGOROOT(dir) {
   560  				return canonical(dir)
   561  			}
   562  
   563  			// Depending on what was passed on the command line, it is possible
   564  			// that os.Executable is a symlink (like /usr/local/bin/go) referring
   565  			// to a binary installed in a real GOROOT elsewhere
   566  			// (like /usr/lib/go/bin/go).
   567  			// Try to find that GOROOT by resolving the symlinks.
   568  			exe, err = filepath.EvalSymlinks(exe)
   569  			if err == nil {
   570  				if dir := filepath.Join(exe, "../.."); isGOROOT(dir) {
   571  					return canonical(dir)
   572  				}
   573  				if dir := filepath.Join(exe, "../../.."); isGOROOT(dir) {
   574  					return canonical(dir)
   575  				}
   576  			}
   577  		}
   578  	}
   579  	return def
   580  }
   581  
   582  // isSameDir reports whether dir1 and dir2 are the same directory.
   583  func isSameDir(dir1, dir2 string) bool {
   584  	if dir1 == dir2 {
   585  		return true
   586  	}
   587  	info1, err1 := os.Stat(dir1)
   588  	info2, err2 := os.Stat(dir2)
   589  	return err1 == nil && err2 == nil && os.SameFile(info1, info2)
   590  }
   591  
   592  // isGOROOT reports whether path looks like a GOROOT.
   593  //
   594  // It does this by looking for the path/pkg/tool directory,
   595  // which is necessary for useful operation of the cmd/go tool,
   596  // and is not typically present in a GOPATH.
   597  //
   598  // There is a copy of this code in x/tools/cmd/godoc/goroot.go.
   599  func isGOROOT(path string) bool {
   600  	stat, err := os.Stat(filepath.Join(path, "pkg", "tool"))
   601  	if err != nil {
   602  		return false
   603  	}
   604  	return stat.IsDir()
   605  }
   606  
   607  func gopathDir(rel string) string {
   608  	list := filepath.SplitList(BuildContext.GOPATH)
   609  	if len(list) == 0 || list[0] == "" {
   610  		return ""
   611  	}
   612  	return filepath.Join(list[0], rel)
   613  }
   614  
   615  // Keep consistent with go/build.defaultGOPATH.
   616  func gopath(ctxt build.Context) string {
   617  	if len(ctxt.GOPATH) > 0 {
   618  		return ctxt.GOPATH
   619  	}
   620  	env := "HOME"
   621  	if runtime.GOOS == "windows" {
   622  		env = "USERPROFILE"
   623  	} else if runtime.GOOS == "plan9" {
   624  		env = "home"
   625  	}
   626  	if home := os.Getenv(env); home != "" {
   627  		def := filepath.Join(home, "go")
   628  		if filepath.Clean(def) == filepath.Clean(runtime.GOROOT()) {
   629  			GoPathError = "cannot set GOROOT as GOPATH"
   630  		}
   631  		return ""
   632  	}
   633  	GoPathError = fmt.Sprintf("%s is not set", env)
   634  	return ""
   635  }
   636  
   637  // WithBuildXWriter returns a Context in which BuildX output is written
   638  // to given io.Writer.
   639  func WithBuildXWriter(ctx context.Context, xLog io.Writer) context.Context {
   640  	return context.WithValue(ctx, buildXContextKey{}, xLog)
   641  }
   642  
   643  type buildXContextKey struct{}
   644  
   645  // BuildXWriter returns nil if BuildX is false, or
   646  // the writer to which BuildX output should be written otherwise.
   647  func BuildXWriter(ctx context.Context) (io.Writer, bool) {
   648  	if !BuildX {
   649  		return nil, false
   650  	}
   651  	if v := ctx.Value(buildXContextKey{}); v != nil {
   652  		return v.(io.Writer), true
   653  	}
   654  	return os.Stderr, true
   655  }
   656  
   657  // A dirInfo implements fs.FileInfo from fs.DirEntry.
   658  // We know that go/build doesn't use the non-DirEntry parts,
   659  // so we can panic instead of doing difficult work.
   660  type dirInfo struct {
   661  	dir fs.DirEntry
   662  }
   663  
   664  func (d *dirInfo) Name() string      { return d.dir.Name() }
   665  func (d *dirInfo) IsDir() bool       { return d.dir.IsDir() }
   666  func (d *dirInfo) Mode() fs.FileMode { return d.dir.Type() }
   667  
   668  func (d *dirInfo) Size() int64        { panic("dirInfo.Size") }
   669  func (d *dirInfo) ModTime() time.Time { panic("dirInfo.ModTime") }
   670  func (d *dirInfo) Sys() any           { panic("dirInfo.Sys") }
   671  

View as plain text