# register qemu-aarch64-static with binfmt_misc to use it as emulator for aarch64 binaries (based on their magic and mask)
# The format of the configuration string is ":name:type:offset:magic:mask:interpreter:flags"
# The most important flag is "F", which allows the qemu-aarch64-static binary to be loaded regardless of chroot and namespaces.
# * doesn't register with binfmt_misc with the persistent ("F") flag we need (see below)
#
# To overcome the above limitations, we use the https://github.com/multiarch/qemu-user-static
# docker image to provide a new enough version of qemu-user-static and register it with
# the desired binfmt_misc flags. The most important flag we need is "F" (set by "--persistent yes"),
# which allows the qemu-aarch64-static binary to be loaded eagerly at the time of registration with binfmt_misc.
# That way, we can emulate aarch64 binaries running inside docker containers transparently, without needing the emulator
# to be accessible from the docker image we're emulating.
echo -1 | sudo tee /proc/sys/fs/binfmt_misc/qemu-aarch64 # delete the existing registration
echo":qemu-aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/local/bin/qemu-aarch64-static:OCF"| sudo tee /proc/sys/fs/binfmt_misc/register
# binary to be accessible from the docker image we're emulating.
# Note that on newer distributions (such as glinux), simply "apt install qemu-user-static" is sufficient
# to install qemu-user-static with the right flags.
docker run --rm --privileged multiarch/qemu-user-static:5.2.0-2 --reset --credential yes --persistent yes
# Print current qemu reqistration to make sure everything is setup correctly.