在Linux系统中,通过qemu-user可以运行其他指令集架构的程序。本文记录了在amd64构架的Debian 11系统中运行armhf架构程序的过程。

根据wikipedia的描述(https://zh.wikipedia.org/zh-sg/Binfmt_misc),binfmt_misc是Linux内核的一项功能,其使得内核可识别任意类型的可执行文件格式并传递至特定的用户空间应用程序,如模拟器和虚拟机[1]。它是内核中准备用户空间程序运行的诸多二进制格式文件处理程序之一 [2].。

在Debian系统中,安装qemu-user和qemu-user-binfmt,即可支持系统模拟运行其他架构的二进制程序,直接通过apt-get安装即可:

apt-get install qemu-user qemu-user-binfmt qemu-user-static

此时,已可以运行其他架构的静态链接程序(如golang编译的程序、gcc编译的静态链接程序)。

使用dpkg添加armhf架构,并安装c库,以支持基本的动态链接的程序(Debian 11软件仓库提供的构架有:amd64, arm64, armel, armhf, i386, mips64el, mipsel, ppc64el, s390x):

dpkg --add-architecture armhf
apt-get install libc6:armhf

其他库可以按需要进行安装。

安装一个armhf架构的交叉编译器,用于编译测试程序:

apt-get install gcc-arm-linux-gnueabihf binutils-arm-linux-gnueabihf

编译一个armhf的测试程序:

arm-linux-gnueabihf-gcc main.c -o main

测试的运行过程和结果如下:

root@vmdeb:~/test_armhf# cat main.c
#include <stdio.h>

int main()
{
    printf("Hello\n");
    return(0);
}
root@vmdeb:~/test_armhf# file main
main: ELF 32-bit LSB pie executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-armhf.so.3, BuildID[sha1]=2d4a1852aa73bb0ba0ea4d6c8ffbe4acbaec1615, for GNU/Linux 3.2.0, not stripped
root@vmdeb:~/test_armhf# uname -an
Linux vmdeb 5.10.0-20-cloud-amd64 #1 SMP Debian 5.10.158-2 (2022-12-13) x86_64 GNU/Linux
root@vmdeb:~/test_armhf# ./main
Hello
root@vmdeb:~/test_armhf#

可以看到,amd64架构的Debian直接正常运行了armhf架构的程序。

https://linux-sunxi.org/Debootstrap里的一个步骤中,利用chroot和qemu-user-static,可以直接进入其他架构的rootfs(例如,在amd64架构的PC上直接使用树莓派的sd卡中的根分区):

# 假设armhf构架的根分区挂载在了/mnt中
cp /usr/bin/qemu-arm-static /mnt/usr/bin/
chroot /mnt /usr/bin/qemu-arm-static /bin/sh -i

类似的,在给OpenWRT设备编译程序时,对于小型工程,可以直接将OpenWRT的rootfs解压并用上述方法进入,通过opkg安装gcc或其他编译工具,直接进行编译。这样可以以编译速度为代价,省去搭建交叉编译环境的工作。

标签: Linux, Debian

添加新评论