cmd/go: disallow go env -w GOROOT=...

The go command determines GOROOT from where the binary is.
It is an error to try to run a go command with a mismatched Go tree.
The only possible use for 'go env -w GOROOT=...' would be if you
copied the go executable to a new place (say, $HOME/bin) and needed
to set the default GOROOT so that it could find its way back home.
Don't do that. Use a symlink or a tiny shell script.

Fixes #77825.

Change-Id: I2b4430c46a9ef35fccb7406ffba3e44b3de191be
Reviewed-on: https://go-review.googlesource.com/c/go/+/749461
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: David Chase <drchase@google.com>
This commit is contained in:
Russ Cox
2026-02-26 12:39:48 -05:00
parent 383000da24
commit b7d1c58875
2 changed files with 13 additions and 1 deletions

View File

@@ -604,7 +604,17 @@ func getOrigEnv(key string) string {
func checkEnvWrite(key, val string) error {
switch key {
case "GOEXE", "GOGCCFLAGS", "GOHOSTARCH", "GOHOSTOS", "GOMOD", "GOWORK", "GOTOOLDIR", "GOVERSION", "GOTELEMETRY", "GOTELEMETRYDIR":
case "GOEXE",
"GOGCCFLAGS",
"GOHOSTARCH",
"GOHOSTOS",
"GOMOD",
"GOROOT",
"GOTELEMETRY",
"GOTELEMETRYDIR",
"GOTOOLDIR",
"GOVERSION",
"GOWORK":
return fmt.Errorf("%s cannot be modified", key)
case "GOENV", "GODEBUG":
return fmt.Errorf("%s can only be set using the OS environment", key)

View File

@@ -71,6 +71,8 @@ stderr 'unknown go command variable GOGC'
stderr 'GOEXE cannot be modified'
! go env -w GOVERSION=customversion
stderr 'GOVERSION cannot be modified'
! go env -w GOROOT=./go
stderr 'GOROOT cannot be modified'
! go env -w GOENV=/env
stderr 'GOENV can only be set using the OS environment'
! go env -w GODEBUG=gctrace=1