7

I compiled a simple "Hello World" C program on Raspberry Pi 3, which was then transferred to an AMD64 laptop. Out of curiosity, I executed it, and it runs even though I did not expect it to:

$ uname -a
Linux 15ud490-gx76k 6.5.0-25-generic #25~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Tue Feb 20 16:09:15 UTC 2 x86_64 x86_64 x86_64 GNU/Linux
$ file hello64
hello64: ELF 64-bit LSB executable, ARM aarch64, version 1 (GNU/Linux), statically linked, BuildID[sha1]=486ee1cde035cd704b49c037a32fb77239b6a1c2, for GNU/Linux 3.7.0, not stripped
$ ./hello64
Hello World!

Like that, how can it execute?

QEMU User Emulation is installed, but I don't know whether it is playing a part in this or not.

Kusalananda
  • 333,661

1 Answers1

16

QEMU user emulation is exactly why your binary runs: on your system, one of the QEMU-related packages you’ve installed ensures that QEMU is registered as a handler for all the architectures it can emulate, and the kernel then passes binaries to it. As long as you have the required libraries, if any, the binary will run; since your binary is statically linked, it has no external dependencies.

See Why can my statically compiled ARM binary of BusyBox run on my x86_64 PC? and How is Mono magical? for details.

Stephen Kitt
  • 434,908
  • Strictly speaking, it’s not QEMU that does the registration, but usually init scripts or one-shot systemd units shipped by the distro itself that do (there are also other ways this can be handled, such as the multiarch/qemu-user-static Docker image). Ubuntu and Debian ship this in a package called qemu-user-binfmt, which IIRC gets pulled in by default if you install either the regular or statically linked user-mode emulation binaries, and the package enables this functionality by default when installed. – Austin Hemmelgarn Mar 10 '24 at 17:42
  • @Austin yes, or by qemu-user-static (see this previous answer, also linked in the answer, for details). qemu-user-static does its own registration; qemu-user-binfmt is only used with qemu-user. – Stephen Kitt Mar 10 '24 at 17:52
  • Note that dynamically-linked programs are not likely to work so easily. The OP's program is statically linked. – user253751 Mar 10 '24 at 19:46
  • 1
    @user253751 yes; “As long as you have the required libraries, if any, the binary will run; since your binary is statically linked, it has no external dependencies.” On Debian derivatives it’s not that hard to run many dynamically-linked foreign binaries, thanks to multi-arch, but it is of course much simpler to run static binaries. – Stephen Kitt Mar 10 '24 at 19:50