Using qemu userspace emulation to build Debian packages for other architectures

Posted on 23.11.2018

In my attempt to avoid overloading my poor new Pinebook (some cheap arm64 laptop) with builds, I tried setting up a build environment on my more powerful x86-64 based machines.

For consistency I’m looking for a Debian package builder (since the machine is running Debian), and I know that pbuilder is a reasonable tool for that purpose. The only complication is making it aware of other architectures.

There’s some machinery already prepared to run binaries for other architectures using the qemu userspace emulators, and while this sometimes creates issues, it’s a much more comfortable and faster environment than a fully emulated system.

After some digging, I got it all worked out:

$ # To install pbuilder and the userspace emulators, run:
$ sudo apt install pbuilder qemu-user-static

Then, put the following configuration into ~root/.pbuilderrc:

# The host architecture is a reasonable default.
export ARCHITECTURE=$(dpkg --print-architecture)
# Subshell to clone the command line, so later interpretation of it still
# works.
eval $(
        while [ $# -gt 0 ]; do
                if [ "$1" = "--architecture" ]; then
                        shift
                        echo export ARCHITECTURE=$1
                fi
                shift
        done
)
BASETGZ=/var/cache/pbuilder/base-$ARCHITECTURE.tgz
if [ "$ARCHITECTURE" != "$(dpkg --print-architecture)" ]; then
        DEBOOTSTRAP=qemu-debootstrap
fi
# aptitude doesn't work within qemu-user for some reason, and for consistency
# just always go for apt.
PBUILDERSATISFYDEPENDSCMD=/usr/lib/pbuilder/pbuilder-satisfydepends-apt

That code is always executed when you run pbuilder and it will hook up qemu if necessary and work with a base image that is made for this architecture (otherwise all your builds would try to use /var/cache/pbuilder/base.tgz, mixing up architectures).