@@ -169,6 +169,38 @@ rec {
169169 } ;
170170 } ;
171171
172+ # Register binfmt handlers for cross-architecture builds (e.g., aarch64-linux on x86_64).
173+ #
174+ # The kernel binfmt P flag (preserveArgvZero) inserts the original argv[0] as an
175+ # extra argument: interpreter <original-argv0> <binary-path> [args...]. A raw
176+ # qemu-aarch64 binary doesn't understand this calling convention and will crash.
177+ # wrapQemuBinfmtP builds a statically-linked C wrapper (TARGET_QEMU baked in at
178+ # compile time) that translates the P-flag calling convention into proper qemu -0
179+ # invocation and strips LD_* vars so they can't affect qemu inside Nix sandboxes.
180+ #
181+ # The kernel registration always points to /run/binfmt/<name> (not the store path
182+ # directly) to stay under the kernel's interpreter path length limit and to allow
183+ # the symlink to be updated without re-registering.
184+ register-binfmt =
185+ let
186+ qemuBin = lib . getExe' pkgs . qemu-user "qemu-aarch64" ;
187+ wrapper = pkgs . wrapQemuBinfmtP "qemu-aarch64-binfmt-P" qemuBin ;
188+ wrapperBin = "${ wrapper } /bin/qemu-aarch64-binfmt-P" ;
189+ in
190+ pkgs . writeShellScriptBin "register-binfmt" ''
191+ set -euo pipefail
192+ echo "Setting up /run/binfmt/aarch64-linux -> ${ wrapperBin } "
193+ sudo mkdir -p /run/binfmt
194+ sudo ln -sf ${ wrapperBin } /run/binfmt/aarch64-linux
195+
196+ echo "Registering binfmt handler for aarch64-linux..."
197+ # Remove any existing registration first (ignore errors if not registered)
198+ echo -1 | sudo tee /proc/sys/fs/binfmt_misc/aarch64-linux > /dev/null 2>&1 || true
199+ printf ':aarch64-linux: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\x00\xff\xfe\xff\xff:/run/binfmt/aarch64-linux:P\n' | \
200+ sudo tee /proc/sys/fs/binfmt_misc/register > /dev/null
201+ echo "Done!"
202+ '' ;
203+
172204 lixImage = pkgs . callPackage ./liximage.nix { } ;
173205 scratchImage = pkgs . callPackage ./scratchimage.nix { } ;
174206}
0 commit comments