godarwinrosettauname

fetching processor architecture in mac using uname giving incorrect results when go binary is built for amd64


I have a golang service which needs to fetch processor's architecture type

archCmd := exec.Command("uname", "-m")
arch, _ := archCmd.CombinedOutput()

I am running the same binary on both intel and arm machines. The binary is built with

GOOS=darwin GOARCH=amd64

On arm machines, this fetches x86_64. It seems this is happening since I'm building with GOARCH=amd64. I am not however sure why this would happen. What's my alternative if i want to run the same built binary on both intel and arm machines.


Solution

  • Quoting a comment from @hrdy that describes this problem:

    Running any kind of EDR which might run on the client under rosetta makes [sysctl] the only valid answer since this checks the underlaying machine itself and not the current prompt which might be wrong due to rosetta.

    Quoting a separate superuser answer: https://superuser.com/a/1735265/443147

    You can use sysctl to get information about your CPU:

    sysctl machdep.cpu.brand_string
    machdep.cpu.brand_string: Apple M1 Pro
    
    

    ... this will require some conditional logic to detect OS as well as parsing to detect an Apple CPU type. This may break in the future if this string value changes.

    archCmd := exec.Command("sysctl", "machdep.cpu.brand_string")
    arch, _ := archCmd.CombinedOutput()
    

    Again, credit goes to @selalerercapitolis's answer linked.