Detect if running under rosetta

Hi All,

I am trying to check if my program is running under emulation on an m1 machine. The code I am using is below

declare function sysctlbyname lib “/usr/lib/libSystem.dylib” (name as cString, out as ptr, byref size as Uinteger, newP as ptr, newPSize as Uinteger) as integer
Dim sizeInfo as Uinteger
Dim r as integer
r=sysctlbyname( “sysctl.proc_translated”, nil, sizeInfo, nil, 0 )

it returns 0 which is correct, but I have no way of knowing if it is running under rosetta since I am testing on a Mac mini m1 so it always returns 0.

I tried using Get info but I see no options for the app to use rosetta, so I don’t know if the code I am
using is correct. Under emulation it should return 1.

Any help would be appreciated

Thanks

See my code here:

If that result <> TargetARM, then it’s running in Rosetta.

1 Like
If SystemInformationMBS.isARM Then
// "Running ARM version on ARM CPU"
Elseif SystemInformationMBS.IsTranslated=1 Then
// "Running Intel version on ARM CPU"
Else
// "Running Intel version on Intel CPU"
End If
3 Likes

There’s a bug in the code in the first post: it’s checking the return value of the sysctlbyname call, and is not checking the byref (memory block) value. Also, there’s some bad code examples on StackOverflow that may be confusing things.

Here’s proper Xojo code to detect Rosetta Translation:

Public Function CPURosettaTranslation() as Boolean
  #if TargetWin32
    return false
  #elseif TargetMacOS and not TargetARM
    // Determine if we are on running Intel translated on Rosetta on a M1 ARM / Apple Silicon CPU
    // https://developer.apple.com/documentation/apple_silicon/about_the_rosetta_translation_environment
    
    Try
      declare function sysctlbyname lib "/usr/lib/libSystem.dylib" (name as cString, out as ptr, byref size as Uinteger, newP as ptr, newPSize as Uinteger) as integer
      
      const NATIVE_EXECUTION  = 0
      const EMULATED_EXECUTION = 1
      const UNKNOWN_EXECUTION = -1
      
      dim size as UInteger = 8 // int64
      dim mb as new MemoryBlock(size) 
      
      if sysctlbyname( "sysctl.proc_translated", mb, size, nil, 0 ) <> 0 then
        System.DebugLog currentMethodName +" sysctlbyname sysctl.proc_translated failed"
        return false
      end if

      dim r as Int64 = mb.Int64Value(0)
      
      select case r
      case NATIVE_EXECUTION
        return false
      case EMULATED_EXECUTION
        return true
      else
        System.DebugLog currentMethodName +" sysctlbyname sysctl.proctranslated UNKNOWN_EXECUTION"
        return false
      end select
      
      
    catch ee as RuntimeException
      LogWarning "Exception " + ee.ExceptionName() + " in " + CurrentMethodName
    End Try
    
  #endif
  
  
  return false
End Function
Forum for Xojo Programming Language and IDE. Copyright © 2021 Xojo, Inc.