0

I am trying to call some terminal commands from Java using the Java ProcessBuilder with an M1 Mac that uses arm64. However, even though that I am using arm64 compatible JVM (Zulu 11, 17..) that identify arm64 chips, whenever I try to use the Java ProcessBuilder, it seems that the terminal is using Rosetta.

For example, the following command returns x86_64 instead of the expected arm64.

ProcessBuilder pb = new ProcessBuilder();
pb.command(new String[] {"bash", "-c", "uname -m"});
Process proc = pb.start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String text = "";
String line;
while ((line = input.readLine()) != null) {
     text += line + System.lineSeparator();
}
bufferedReader.close();
System.out.println(text);

Do you know if there is any other way to execute terminal commands from Java using acutally the arm64 chip instead of the emulated Intel one?

Regards,

Carlos

CARLOS
  • 56
  • 6
  • Can you try `pb.command(new String[] {"/usr/bin/uname", "-m"});` – Elliott Frisch Nov 13 '22 at 23:49
  • I couldn't reproduce this on my M1 Pro. It prints `arm64` as expected. I did have to change `input` to `bufferedReader` in the code provided. Was that just a transcription error or is it actually reading the wrong thing in your original code? – Tim Moore Nov 14 '22 at 03:40

1 Answers1

1

Any process you spawn will default to the same architecture as your process, if that architecture is available in the binary.

On the syscall layer, this can be overridden with Apple's proprietary posix_spawnattr_setbinpref_np() to select the preferred architecture slice in universal binaries when using posix_spawn().

On the command line, this is supported via the arch command:

arch -arm64 uname -m
arch -x86_64 uname -m

So in your code, this should look like this:

{"arch", "-arm64", "bash", "-c", "uname -m"}

You can also pass multiple architecture selectors to the arch command to be attempted in that order, so if you want your code to spawn native binaries whenever possible on either arm64 or x86_64 hosts, you can use:

{"arch", "-arm64", "-x86_64", "bash", "-c", "uname -m"}
Siguza
  • 21,155
  • 6
  • 52
  • 89