Skip to content

Commit

Permalink
Quote CC if it contains whitespace (#3491)
Browse files Browse the repository at this point in the history
The `cgo` tool splits `CC` on unquoted whitespace, which can cause
failures on Windows when `CC` points to an absolute path such as
`C:\Program Files\some\compiler.exe`.
  • Loading branch information
fmeum committed Mar 27, 2023
1 parent c898c1c commit a0fb771
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
17 changes: 17 additions & 0 deletions go/tools/builders/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,23 @@ func passLongArgsInResponseFiles(cmd *exec.Cmd) (cleanup func()) {
return cleanup
}

// quotePathIfNeeded quotes path if it contains whitespace and isn't already quoted.
// Use this for paths that will be passed through
// https://github.com/golang/go/blob/06264b740e3bfe619f5e90359d8f0d521bd47806/src/cmd/internal/quoted/quoted.go#L25
func quotePathIfNeeded(path string) string {
if strings.HasPrefix(path, "\"") || strings.HasPrefix(path, "'") {
// Assume already quoted
return path
}
// https://github.com/golang/go/blob/06264b740e3bfe619f5e90359d8f0d521bd47806/src/cmd/internal/quoted/quoted.go#L16
if strings.IndexAny(path, " \t\n\r") < 0 {
// Does not require quoting
return path
}
// Escaping quotes is not supported, so we can assume path doesn't contain any quotes.
return "'" + path + "'"
}

func useResponseFile(path string, argLen int) bool {
// Unless the program uses objabi.Flagparse, which understands
// response files, don't use response files.
Expand Down
2 changes: 1 addition & 1 deletion go/tools/builders/stdlib.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ You may need to use the flags --cpu=x64_windows --compiler=mingw-gcc.`)

// Make sure we have an absolute path to the C compiler.
// TODO(#1357): also take absolute paths of includes and other paths in flags.
os.Setenv("CC", abs(os.Getenv("CC")))
os.Setenv("CC", quotePathIfNeeded(abs(os.Getenv("CC"))))

// Ensure paths are absolute.
absPaths := []string{}
Expand Down
2 changes: 1 addition & 1 deletion go/tools/builders/stdliblist.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func stdliblist(args []string) error {
os.Setenv("GOROOT", newGoRoot)
// Make sure we have an absolute path to the C compiler.
// TODO(#1357): also take absolute paths of includes and other paths in flags.
os.Setenv("CC", abs(os.Getenv("CC")))
os.Setenv("CC", quotePathIfNeeded(abs(os.Getenv("CC"))))

cachePath := abs(*out + ".gocache")
defer os.RemoveAll(cachePath)
Expand Down

0 comments on commit a0fb771

Please sign in to comment.