1. 安装qemu工具
1.1 Ubuntu系统
sudo apt install qemu-user-static
2. 常见使用
2.1 下载对应架构的根文件并解压
2.2 将对应架构的qemu-aarch64-static拷贝
2.3 运行下列终端即可进入
chroot "${PWD}/rootfs" /bin/bash
3. 常用脚本
3.1 脚本模板
function create_qemu_env(){
if [ ! -f "/usr/bin/qemu-aarch64-static" ]; then
echo "please install qemu-aarch64-static"
exit 1
fi
LDK_ROOTFS_DIR="${LDK_DIR}/rootfs"
cp /usr/bin/qemu-aarch64-static ${LDK_ROOTFS_DIR}/usr/bin/
chmod 755 ${LDK_ROOTFS_DIR}/usr/bin/qemu-aarch64-static
mv "${LDK_ROOTFS_DIR}/etc/resolv.conf" "${LDK_ROOTFS_DIR}/etc/resolv.conf.saved"
cp /etc/resolv.conf "${LDK_ROOTFS_DIR}/etc/"
mount /sys ${LDK_ROOTFS_DIR}/sys -o bind
mount /proc ${LDK_ROOTFS_DIR}/proc -o bind
mount /dev ${LDK_ROOTFS_DIR}/dev -o bind
mount /dev/pts ${LDK_ROOTFS_DIR}/dev/pts -o bind
mount $(pwd) ${LDK_ROOTFS_DIR}/mnt -o bind;
}
function clean_qemu_env(){
echo "Cleaning up virtual env"
LDK_ROOTFS_DIR="${LDK_DIR}/rootfs"
mountpoint -q "${LDK_ROOTFS_DIR}/sys" && umount "${LDK_ROOTFS_DIR}/sys"
mountpoint -q "${LDK_ROOTFS_DIR}/proc" && umount "${LDK_ROOTFS_DIR}/proc"
mountpoint -q "${LDK_ROOTFS_DIR}/dev/shm" && umount "${LDK_ROOTFS_DIR}/dev/shm"
mountpoint -q "${LDK_ROOTFS_DIR}/dev/pts" && umount "${LDK_ROOTFS_DIR}/dev/pts"
mountpoint -q "${LDK_ROOTFS_DIR}/dev" && umount "${LDK_ROOTFS_DIR}/dev"
mountpoint -q "${LDK_ROOTFS_DIR}/mnt" && umount "${LDK_ROOTFS_DIR}/mnt"
if [ -f "${LDK_ROOTFS_DIR}/etc/resolv.conf.saved" ]; then
mv "${LDK_ROOTFS_DIR}/etc/resolv.conf.saved" "${LDK_ROOTFS_DIR}/etc/resolv.conf"
fi
rm -f "${LDK_ROOTFS_DIR}/usr/bin/qemu-aarch64-static"
}
3.2 脚本使用方法
function do_run_cmd(){
trap clean_qemu_env EXIT
local cmd="$*"
echo "do_run_cmd, cmd: $cmd"
create_qemu_env
# 显示将要执行的完整命令
local full_command="LC_ALL=C chroot \"${LDK_DIR}/rootfs\" /bin/bash -c \"$cmd\""
echo "Executing command: $full_command"
if ! eval $full_command; then
echo "ERROR: do_run_cmd failed!"
exit 1
else
echo "do_run_cmd successful!"
clean_qemu_env
trap - EXIT
fi
}