Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an executable can I determine values of GOOS and GOARCH used to build it?

Tags:

go

The title pretty much sums it up. How can I determine what the values of GOOS and GOARCH was given just the go executable?

like image 966
mozey Avatar asked Jan 06 '23 13:01

mozey


1 Answers

EDIT: The behavior of runtime.GOROOT() changed in Go 1.10, for details, see Go 1.10 release notes # Runtime. Basically now runtime.GOROOT() checks if the GOROOT environment variable is set, and if so, its value is returned. If not, it returns the GOROOT value recorded at compile time.


Check out the runtime package:

The GOARCH, GOOS, GOPATH, and GOROOT environment variables complete the set of Go environment variables. They influence the building of Go programs (see https://golang.org/cmd/go and https://golang.org/pkg/go/build). GOARCH, GOOS, and GOROOT are recorded at compile time and made available by constants or functions in this package, but they do not influence the execution of the run-time system.

A list of possible combinations for GOARCH and GOOS can be found here: https://golang.org/doc/install/source#environment

So what you are looking for are constants in the runtime package:

runtime.GOOS
runtime.GOARCH

And they will exactly contain the values that were present when your app was built.

For example see this simple app:

func main() {
    fmt.Println(runtime.GOOS)
    fmt.Println(runtime.GOARCH)
}

Let's say GOOS=windows and GOARCH=amd64. Running it with go run xx.go will print:

windows
amd64

Build an exe from it (e.g. go build). Running the exe has the same output.

Now change GOARCH to 386. If you run it with go run (or build an exe and run that), it will print:

windows
386

If you run the previously built exe, it will still print:

windows
amd64
like image 173
icza Avatar answered Apr 19 '23 23:04

icza