【Linux自制操作系统系列】(二)实验环境安装:源码编译安装 Qemu 9.1.1 和 Bochs 2.8

源码编译安装 Qemu 9.1.1 和 Bochs 2.8


三、实验虚拟环境安装

操作系统:

Debian 12.7.0

虚拟机版本:

Qemu-9.1.1 ; Bochs 2.8。

说明:重点介绍Qemu 9.1.1,Bochs具体安装过程只作简要介绍。


3.1 下载源码软件包

3.1.1 Qemu 虚拟机

官网链接: 官网全系列版本下载地址
教程链接: Qemu-9.1.1 版本下载地址

Git方式自取(命令行):

git clone https://github.com/qemu/qemu.git

个人网盘分享:百度网盘下载地址 Qemu-9.1.1

3.1.2 Bochs 虚拟机:

个人网盘分享:百度网盘下载地址 Bochs 2.8

3.2 源码Qemu9.1.1安装过程

3.2.1 安装依赖库

试验安装过程中需要的库文件(本机测试缺少的库):

# 针对 Debian12.7.0, 必需的包

sudo apt-get install pkg-config
sudo apt-get install libsdl2-dev
sudo apt-get install libpixman-1-dev
sudo apt-get install flex
sudo apt-get install bison
sudo apt-get install ninja-build
sudo apt-get install zlib1g-dev
sudo apt-get install python3-venv
sudo apt-get install libfdt-dev
# 建议安装的额外的包, qemu: 为了额外的功能

sudo apt-get install git-email
sudo apt-get install libaio-dev libbluetooth-dev libcapstone-dev libbrlapi-dev libbz2-dev
sudo apt-get install libcap-ng-dev libcurl4-gnutls-dev libgtk-3-dev
sudo apt-get install libibverbs-dev libjpeg8-dev libncurses5-dev libnuma-dev
sudo apt-get install librbd-dev librdmacm-dev
sudo apt-get install libsasl2-dev libsdl2-dev libseccomp-dev libsnappy-dev libssh-dev
sudo apt-get install libvde-dev libvdeplug-dev libvte-2.91-dev libxen-dev liblzo2-dev
sudo apt-get install valgrind xfslibs-dev

3.2.2 安装前配置文件

本机配置(根据需要修改):

./configure --prefix=/usr/local/share/qemu --target-list=x86_64-softmmu,i386-softmmu,x86_64-linux-user,i386-linux-user,mips64el-linux-user,mips64el-softmmu --enable-debug --enable-kvm --enable-sdl --enable-tools --enable-vnc --enable-werror --disable-curl --enable-fdt=auto

具体查阅帮助文件:

./configure --help

配置文件简要说明:
--target-list 选择目标机器的架构。默认是将所有的架构都编译,但为了更快的完成编译,指定需要的架构即可。
可用模拟平台(查阅帮助文件): aarch64-linux-user
aarch64_be-linux-user alpha-linux-user
arm-linux-user armeb-linux-user cris-linux-user
hexagon-linux-user hppa-linux-user i386-linux-user
loongarch64-linux-user m68k-linux-user
microblaze-linux-user microblazeel-linux-user
mips-linux-user mips64-linux-user
mips64el-linux-user mipsel-linux-user
mipsn32-linux-user mipsn32el-linux-user
nios2-linux-user or1k-linux-user ppc-linux-user
ppc64-linux-user ppc64le-linux-user
riscv32-linux-user riscv64-linux-user
s390x-linux-user sh4-linux-user sh4eb-linux-user
sparc-linux-user sparc32plus-linux-user
sparc64-linux-user x86_64-linux-user
xtensa-linux-user xtensaeb-linux-user
aarch64-softmmu alpha-softmmu arm-softmmu
avr-softmmu cris-softmmu hppa-softmmu i386-softmmu
loongarch64-softmmu m68k-softmmu microblaze-softmmu
microblazeel-softmmu mips-softmmu mips64-softmmu
mips64el-softmmu mipsel-softmmu nios2-softmmu
or1k-softmmu ppc-softmmu ppc64-softmmu
riscv32-softmmu riscv64-softmmu rx-softmmu
s390x-softmmu sh4-softmmu sh4eb-softmmu
sparc-softmmu sparc64-softmmu tricore-softmmu
x86_64-softmmu xtensa-softmmu xtensaeb-softmmu

其中:
xxx-softmmu 表示的是模拟整个物理机,使用 qemu-system-xxx 命令
xxx-linux-user 仅模拟用户应用程序,使用 qemu-xxx 命令
aarch64-softmmu:ARM64指令集
arm-softmmu:ARMv7指令集
riscv32-softmmu:RISC-V的32bit指令集
riscv64-softmmu:RISC-V的64bit指令集

--prefix 指定安装路径
--enable-debug 使用GDB调试
--enable-kvm 编译KVM模块,使QEMU可以利用KVM来访问硬件提供的虚拟化服务。
--enable-vnc 启用VNC。
--enalbe-werror 编译时,将所有的警告当作错误处理。

注意:
如果不使用 --target-list ,会编译安装各种平台的Qemu模拟器(aarch64,riscv64,arm等)
不指定 --prefix,一般会安装到 /usr/local ,建议自定义一个路径
如果要添加新的目标平台,则直接在qemu的源码目录执行 make clean,然后重新配置、编译、安装


3.2.3 配置过程可能出现的问题及解决办法

3.2.3.1 ERROR: cannot find Ninja

sudo apt-get install ninja-build

3.2.3.2 ERROR: Pkg-config binary ‘pkg-config’ not found

sudo apt-get install pkg-config

3.2.3.3 ERROR: Program ‘flex’ not found or not executable

sudo apt-get install flex

3.2.3.4 ERROR: Program ‘flex’ not found or not executable

sudo apt-get install flex

3.2.3.5 configure配置出错 FileNotFoundError: [Errno 2] No such file or directory: “‘/home/*/下载/qemu-9.0.0/build/pyvenv/bin/meson’”
scripts/symlink-install-tree.py
具体报错信息:Found ninja-1.10.0 at /usr/bin/ninja
Running postconf script ‘/home/xixi/下载/qemu-9.0.0/build/pyvenv/bin/python3 /home/xixi/下载/qemu-9.0.0/scripts/symlink-install-tree.py’
Traceback (most recent call last):
File “/home/xixi/下载/qemu-9.0.0/scripts/symlink-install-tree.py”, line 17, in
out = subprocess.run([*introspect.split(’ ‘), ‘–installed’],
File “/usr/lib/python3.8/subprocess.py”, line 493, in run
with Popen(popenargs, **kwargs) as process:
File “/usr/lib/python3.8/subprocess.py”, line 858, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File “/usr/lib/python3.8/subprocess.py”, line 1704, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: "'/home/
/下载/qemu-9.0.0/build/pyvenv/bin/meson’"

将  scripts/symlink-install-tree.py修改为如下代码即可解决问题

#!/usr/bin/env python3

from pathlib import PurePath
import errno
import json
import os
import shlex
import subprocess
import sys

def destdir_join(d1: str, d2: str) -> str:
    if not d1:
        return d2
    # c:\destdir + c:\prefix must produce c:\destdir\prefix
    return str(PurePath(d1, *PurePath(d2).parts[1:]))

introspect = os.environ.get('MESONINTROSPECT')
# out = subprocess.run([*introspect.split(' '), '--installed'],
out = subprocess.run([*shlex.split(introspect), '--installed'],
                     stdout=subprocess.PIPE, check=True).stdout
for source, dest in json.loads(out).items():
    bundle_dest = destdir_join('qemu-bundle', dest)
    path = os.path.dirname(bundle_dest)
    try:
        os.makedirs(path, exist_ok=True)
    except BaseException as e:
        print(f'error making directory {path}', file=sys.stderr)
        raise e
    try:
        os.symlink(source, bundle_dest)
    except BaseException as e:
        if not isinstance(e, OSError) or e.errno != errno.EEXIST:
            if os.name == 'nt':
                print('Please enable Developer Mode to support soft link '
                      'without Administrator permission')
            print(f'error making symbolic link {dest}', file=sys.stderr)
            raise e

具体修改内容(scripts/symlink-install-tree.py):
增加 import shlex
修改 # out = subprocess.run([*introspect.split(’ '), ‘–installed’], 为 out = subprocess.run([*shlex.split(introspect), ‘–installed’],

安装过程中出现问题时不要慌:
除了问题3.2.3.5之外,其他问题主打一个缺啥安装啥就行。

安装完成提示:

User defined options
Native files : config-meson.cross
optimization : 0
prefix : /usr/local/share/qemu
curl : disabled
debug_graph_lock : true
debug_mutex : true
debug_tcg : true
docs : disabled
kvm : enabled
plugins : true
sdl : enabled
tools : enabled
Found ninja-1.10.0 at /usr/bin/ninja
Running postconf script ‘/home/xixi/下载/qemu-9.1.1/build/pyvenv/bin/python3 /home/xixi/下载/qemu-9.0.0/scripts/symlink-install-tree.py’

3.2.4 安装编译

make -j12

说明:因为我是12核处理器,所以指定了多线程编译,加快编译的速度,根据实际情况指定,默认为1。

sudo make install | tee make-install.log

说明:tee make-install.log 用来保存安装记录,便于以后卸载使用。安装到刚才 --prefix 指定的路径下。

3.2.5 添加到环境变量中

vim ~/.bashrc

# 添加如下一行, 需要会一点 vim, 或者使用其他方式修改
export PATH=$PATH:/usr/local/share/qemu/bin

# 刷新配置文件,立即生效,之后就可以在任意目录下使用 “qemu-*”命令
source ~/.bashrc

qemu-x86_64 --version

#命令显示结果
qemu-x86_64 version 9.1.1
Copyright (c) 2003-2024 Fabrice Bellard and the QEMU Project developers

3.2.6 Qemu 9 简单使用介绍

3.2.6.1 qemu命令语法(qemu Command Syntax)

Qemu语法与大多数Linux命令相同。

qemu-system-x86_64 OPTIONS IMAGE

OPTIONS提供了VM选项,如RAM大小,功能,CPU,显卡等。
IMAGE is the file name of the disk for the VM.
IMAGE是VM磁盘的文件名。

3.2.6.1.1 设置Qemu VM的CPU和核心计数(Set CPU and Core Count for Qemu VM)

CPU是系统最重要的部分之一。 我们可以在Qemu中设置VM的CPU核心数。 我们将提供-smp选项,该选项将启用具有core=2值的多个CPU内核,这将在给定VM中设置内核计数2。

qemu-system-x86_64 -smp cores=2

从网络启动 (Boot From Network)
有多种启动VM系统的方法。 通常,映像用于引导,但是我们也可以使用-boot -boot order=nc选项从网络引导。

qemu-system-x86_64 -boot order=nc
3.2.6.1.2 设置Qemu VM的RAM或内存大小 (Set RAM or Memory Size For Qemu VM)

RAM是VM的另一个重要组件。 默认情况下,为启动的VM设置128 MB RAM。 但是我们也可以使用-m选项显式设置RAM的大小,这是内存的简称。 我们还将以MB为单位提供大小,在此示例中,我们将设置256 MB Ram。

qemu-system-x86_64 -m 256
3.2.6.1.3 设置Qemu的VM名称(Set VM Name For Qemu)

我们还可以选择为虚拟机设置名称。 我们可以使用-name选项并提供VM名称。 VM名称将显示在Qemu的Window标头中。 在此示例中,我们将虚拟机名称设置为bogson。

qemu-system-x86_64 -name bogson
3.2.6.1.4 为Qemu VM指定磁盘文件或映像 (Specify Disk File or Image For Qemu VM)

我们可以使用-drive选项指定磁盘/映像文件。 这将使我们能够指定额外的驱动程序相关选项。 file用于指定文件大小。 另外if用于提供磁盘的驱动程序或接口类型。

qemu-system-x86_64 -drive file=fedoraraw.qcow2,if=virtio
3.2.6.1.5 禁用Qemu VM的GUI (Disable GUI for Qemu VM)

默认情况下,VM控制台将作为GUI窗口提供。 但是我们也可以禁用控制台,仅向系统终端提供-nographic选项。

qemu-system-x86_64 -nographic
3.2.6.1.6 像virbr0一样连接到虚拟交换机 (Connect To Virtual Switch Like virbr0)

默认情况下,启动的来宾系统将不连接网络,并且仅连接单个接口。 在大多数情况下,这不是实用且有用的功能。 我们可以添加网络接口,并将此接口连接到在主机操作系统中运行的桥接设备。 在此示例中,我们将通过virtio类型的网络接口将客户机连接到名为virbr0的虚拟交换机/桥中。

qemu-system-x86_64 -drive file=fedoraraw.qcow2,if=virtio -display none -net bridge,br=virbr0 -net nic,model=virtio
3.2.6.1.7 对Qemu VM使用远程磁盘映像 (Use Remote Disk Images For Qemu VM)

通常,使用VM磁盘映像的最佳方法是在本地使用,但是qemu还通过与诸如SSH等不同协议的网络共享来支持远程磁盘映像。在本示例中,我们将通过以下disk.img在远程系统上使用名为disk.img的磁盘映像:通过使用file选项的SSh。

qemu-system-x86_64 -drive file=ssh://[email protected]/disk.img

3.2.6.2 qemu 常用参数

-M: 指定设备类型
-m: 指定内存大小; 如:-m 512M
-kernel: 指定内核文件; 如:-kernel linux-5.10.181/arch/riscv/boot/Image
-bios: 指定bios文件
-smp: 指定虚拟机核心数
-S: 冻结 CPU 直到远程 GDB 输入相应命令
-s: 启动 GDB 服务,在 1234 端口接受gdb调试; 如:-s -S 或 -gdb tcp::1234 -S 选项用于启动 gdb 服务,启动后 qemu 不立即运行 guest,而是等待主机 gdb 发起连接,此时使用 gdb 输入 target remote:1234 可以进行相关调试,与真机调试无异。
-initrd:指定启动文件
-dtb: 指定dtb文件
-nographic: 指定不需要图形界面
-append:指定扩展显示界面,串口或者LCD,"console=ttyS0"和-nographic配合后,使得启动后的串口重定向到宿主机终端,能在宿主机的终端看到调试信息。如: -append “root=/dev/vda rw console=ttyS0”
-device:常用于指定guest上总线挂载的外部设备,例如virtio-mmio、usb、pci等总线
-netdev:配置网络设备
#!/bin/sh

3.2.6.2.1 启动配置示例1
qemu-system-riscv64 \
-M virt \
-bios opensbi/build/platform/generic/firmware/fw_jump.elf \
-kernel linux-5.10.181/arch/riscv/boot/Image \
-append "rootwait root=/dev/vda ro" \
-drive file=buildroot-2023.02.1/output/images/rootfs.ext2,format=raw,id=hd0 \
-device virtio-blk-device,drive=hd0 \
-netdev user,id=net0 -device virtio-net-device,netdev=net0 \
-nographic
3.2.6.2.2 启动配置示例2
qemu-system-arm -kernel kernel-qemu \
                  -cpu arm1176 \
                  -m 256 \
                  -M versatilepb \
                  -no-reboot \
                  -serial stdio \
                  -append "root=/dev/sda2 panic=1 rootfstype=ext4 rw init=/bin/bash" \
                  -hda image-file-name.img
3.2.6.2.3 启动配置示例3
qemu-system-riscv64 \
-M virt \
-bios opensbi/build/platform/generic/firmware/fw_jump.elf \
-kernel linux-5.10.181/arch/riscv/boot/Image \
-append "rootwait root=/dev/vda ro" \
-drive file=buildroot-2023.02.1/output/images/rootfs.ext2,format=raw,id=hd0 \
-device virtio-blk-device,drive=hd0 \
-netdev user,id=net0 -device virtio-net-device,netdev=net0 \
-nographic

3.2.6.3 启动过程

3.2.6.3.1 运行(Run)
qemu-system-arm -kernel kernel-qemu \
                  -cpu arm1176 \
                  -m 256 \
                  -M versatilepb \
                  -no-reboot \
                  -serial stdio \
                  -append "root=/dev/sda2 panic=1 rootfstype=ext4 rw init=/bin/bash" \
                  -hda image-file-name.img
                  
#You should get # prompt (bash) at the end of processing.
3.2.6.3.2 编辑(Edit) /etc/ld.so.preload by commenting (with # symbol) the 1st line, e.g.:
# /usr/lib/arm-linux-gnueabihf/libcofi_rpi.so
#
# ... rest of the file
3.2.6.3.3 编辑(Edit) /etc/udev/rules.d/90-qemu.rules by adding the following lines:
KERNEL=="sda", SYMLINK+="mmcblk0"
KERNEL=="sda?", SYMLINK+="mmcblk0p%n"
KERNEL=="sda2", SYMLINK+="root"
3.2.6.3.4 运行(Run)
sudo poweroff
3.2.6.3.5 Re-emulate by running
qemu-system-arm -kernel kernel-qemu \
                  -cpu arm1176 \
                  -m 256 \
                  -M versatilepb \
                  -serial stdio \
                  -append "root=/dev/sda2 panic=1 rootfstype=ext4 rw" \
                  -drive "file=image-file-name.img,index=0,media=disk,format=raw"

3.2.6.4 KVM虚拟化qemu-img命令详解

qemu-img是QEMU的磁盘管理工具,在qemu-kvm源码编译后就会默认编译好qemu-img这个二进制文件。qemu-img也是QEMU/KVM使用过程中一个比较重要的工具。

3.2.6.4.1 qemu-img check [-f fmt] filename

对磁盘镜像文件进行一致性检查,查找镜像文件中的错误,目前仅支持对“qcow2”、“qed”、“vdi”格式文件的检查。其中,qcow2是QEMU
0.8.3版本引入的镜像文件格式,也是目前使用最广泛的格式。
qed(QEMU enhanced disk)是从QEMU0.14版开始加入的增强磁盘文件格式,为了避免qcow2格式的一些缺点,也为了提高性能,不过目前还不够成熟。而vdi(Virtual Disk Image)是Oracle的VirtualBox虚拟机中的存储格式。
-f fmt 是指定文件的格式,如果不指定格式qemu-img会自动检测 filename是磁盘镜像文件的名称(包括路径)。

如下命令行演示了qemu-img的check命令的使用方法。

[root@linux xixi]# qemu-img check cps.qcow2

No errors were found on the image.
3.2.6.4.2 创建 qemu-img create

create [-f fmt] [-o options] filename [size]
根据文件格式fmt的不同,还可以添加一个或多个选项(options)来附加对该文件的各种功能设置,可以使用“-o ?”来查询某种格式文件支持那些选项,在“-o”选项中各个选项用逗号来分隔。
如果“-o”选项中使用了backing_file这个选项来指定其后端镜像文件,那么这个创建的镜像文件仅记录与后端镜像文件的差异部分。后端镜像文件不会被修改,除非在QEMU monitor中使用“commit”命令或者使用“qemu-img commit”命令去手动提交这些改动。这种情况下,size参数不是必须需的,其值默认为后端镜像文件的大小。另外,直接使用“-b backfile”参数也与“-o backing_file=backfile”效果相同。
size选项用于指定镜像文件的大小,其默认单位是字节(bytes),也可以支持k(或K)、M、G、T来分别表示KB、MB、GB、TB大小。另外,镜像文件的大小(size)也并非必须写在命令的最后,它也可以被写在“-o”选项中作为其中一个选项。
对create命令的演示如下所示,其中包括查询qcow2格式支持的选项、创建有backing_file的qcow2格式的镜像文件、创建没有backing_file的10GB大小的qcow2格式的镜像文件。

查询qcow2格式支持的选项:

[root@linux xixi]# qemu-img create -f qcow2 -o ? temp.qcow
Supported options:
size             Virtual disk size
compat           Compatibility level (0.10 or 1.1)
backing_file     File name of a base image
backing_fmt      Image format of the base image
encryption       Encrypt the image
cluster_size     qcow2 cluster size
preallocation    Preallocation mode (allowed values: off, metadata, falloc, full)
lazy_refcounts   Postpone refcount updates

创建有backing_file的qcow2格式的镜像文件

[root@linux xixi]# qemu-img create -f qcow2 -b rhel6u3.img  rhel6u3.qcow2
Formatting ‘rhel6u3.qcow2′, fmt=qcow2 size=8589934592 backing_file=’rhel6u3.img’ encryption=off cluster_size=65536

创建没有backing_file的10GB大小的qcow2格式的镜像文件

[root@linux xixi]# qemu-img create -f qcow2 -o backing_file=rhel6u3.img  rhel6u3-1.qcow2
Formatting ‘rhel6u3-1.qcow2′, fmt=qcow2 size=8589934592 backing_file=’rhel6u3.img’ encryption=off cluster_size=65536

[root@linux xixi]# qemu-img create -f qcow2 -o backing_file=rhel6u3.img,size=20G  rhel6u3-2.qcow2
Formatting ‘rhel6u3-2.qcow2′, fmt=qcow2 size=21474836480 backing_file=’rhel6u3.img’ encryption=off cluster_size=65536

[root@linux xixi]# qemu-img create -f qcow2 ubuntu.qcow2 10G
Formatting ‘ubuntu.qcow2′, fmt=qcow2 size=10737418240 encryption=off cluster_size=65536
3.2.6.4.3 提交 qemu-img commit

提交filename文件中的更改到后端支持镜像文件(创建时通过backing_file指定的)中去。

如下命令行演示了qemu-img的check命令的使用方法。

commit [-f fmt] filename
3.2.6.4.4 转换 qemu-img convert

convert [-c] [-f fmt] [-O output_fmt] [-o options] filename [filename2 [...]] output_filename
将fmt格式的filename镜像文件根据options选项转换为格式为output_fmt的名为output_filename的镜像文件。它支持不同格式的镜像文件之间的转换,比如可以用VMware用的vmdk格式文件转换为qcow2文件,这对从其他虚拟化方案转移到KVM上的用户非常有用。一般来说,输入文件格式fmt由qemu-img工具自动检测到,而输出文件格式output_fmt根据自己需要来指定,默认会被转换为与raw文件格式(且默认使用稀疏文件的方式存储以节省存储空间)。
其中,“-c”参数是对输出的镜像文件进行压缩,不过只有qcow2和qcow格式的镜像文件才支持压缩,而且这种压缩是只读的,如果压缩的扇区被重写,则会被重写为未压缩的数据。同样可以使用“-o options”来指定各种选项,如:后端镜像、文件大小、是否加密等等。使用backing_file选项来指定后端镜像,让生成的文件是copy-on-write的增量文件,这时必须让转换命令中指定的后端镜像与输入文件的后端镜像的内容是相同的,尽管它们各自后端镜像的目录、格式可能不同。
如果使用qcow2、qcow、cow等作为输出文件格式来转换raw格式的镜像文件(非稀疏文件格式),镜像转换还可以起到将镜像文件转化为更小的镜像,因为它可以将空的扇区删除使之在生成的输出文件中并不存在。

如下命令行演示了qemu-img的convert命令的使用方法。

3.2.6.4.4.1 将VMware的vmdk格式镜像转换为KVM可以使用的qcow2镜像
[root@linux xixi]# qemu-img convert my-vmware.vmdk my-kvm.img
#此处并无实际存在vmdk文件,仅演示其命令行操作
3.2.6.4.4.1.2 raw镜像文件转化为qcow2格式
[root@linux xixi]# qemu-img convert -O qcow2 rhel6u3.img rhel6u3-a.img
3.2.6.4.5 查询 qemu-img info

info [-f fmt] filename
复制
展示filename镜像文件的信息。如果文件是使用稀疏文件的存储方式,也会显示出它的本来分配的大小以及实际已占用的磁盘空间大小。如果文件中存放有客户机快照,快照的信息也会被显示出来。下面的命令行演示了前面进行文件转换的输入、输出文件的信息。

如下命令行演示了qemu-img的info命令的使用方法。

[root@linux xixi]# qemu-img info rhel6u3.img
image: rhel6u3.img
file format: raw
virtual size: 8.0G (8589934592 bytes)
disk size: 8.0G

[root@linux xixi]# qemu-img info rhel6u3-a.img
image: rhel6u3-a.img
file format: qcow2
virtual size: 8.0G (8589934592 bytes)
disk size: 6.8G
cluster_size: 65536
3.2.6.4.6 快照 qemu-img snapshot

snapshot [-l | -a snapshot | -c snapshot | -d snapshot] filename
“-l” 选项是查询并列出镜像文件中的所有快照,“-a snapshot”是让镜像文件使用某个快照,“-c snapshot”是创建一个快照,“-d”是删除一个快照。

3.2.6.4.7 改变镜像文件的后端镜像文件qemu-img rebase

rebase [-f fmt] [-t cache] [-p] [-u] -b backing_file [-F backing_fmt] filename
改变镜像文件的后端镜像文件,只有qcow2和qed格式支持rebase命令。使用“-b backing_file”中指定的文件作为后端镜像,后端镜像也被转化为“-F backing_fmt”中指定的后端镜像格式。
它可以工作于两种模式之下,一种是安全模式(Safe Mode)也是默认的模式,qemu-img会去比较原来的后端镜像与现在的后端镜像的不同进行合理的处理;另一种是非安全模式(Unsafe Mode),是通过“-u”参数来指定的,这种模式主要用于将后端镜像进行了重命名或者移动了位置之后对前端镜像文件的修复处理,由用户去保证后端镜像的一致性。

3.2.6.4.8 改变大小 qemu-img resize

1resize filename [+ | -]size1
改变镜像文件的大小,使其不同于创建之时的大小。“+”和“-”分别表示增加和减少镜像文件的大小,而size也是支持K、M、G、T等单位的使用。缩小镜像的大小之前,需要在客户机中保证里面的文件系统有空余空间,否则会数据丢失,另外,qcow2格式文件不支持缩小镜像的操作。在增加了镜像文件大小后,也需启动客户机到里面去应用“fdisk”、“parted”等分区工具进行相应的操作才能真正让客户机使用到增加后的镜像空间。不过使用resize命令时需要小心(最好做好备份),如果失败的话,可能会导致镜像文件无法正常使用而造成数据丢失。

如下命令行演示了qemu-img的resize命令的使用方法。

3.2.6.4.8.1 将一个8GB的qcow2镜像增加2GB的空间
[root@linux xixi]# qemu-img resize rhel6u3-a.img +2G
Image resized.

[root@linux xixi]# qemu-img info rhel6u3-a.img
image: rhel6u3-a.img
file format: qcow2
virtual size: 10G (10737418240 bytes)
disk size: 6.8G
cluster_size: 65536
3.2.6.4.8.2 将一个8GB大小的raw镜像减少1GB空间
[root@linux xixi]# qemu-img resize rhel6u3-b.img -1G
Image resized.

[root@linux xixi]# qemu-img info rhel6u3-b.img
image: rhel6u3-b.img
file format: raw
virtual size: 7.0G (7516192768 bytes)
disk size: 6.5G

3.2.7 使用gdb分析QEMU代码

使用gdb不仅可以很好地调试代码,也可以利用它来动态地分析代码。使用gdb调试QEMU需要做一些准备工作:

1. 编译QEMU时需要在执行configure脚本时的参数中加入–enable-debug。

2. 启动gdb调试QEMU

gdb --args qemu-system-x86_64 -enable-kvm -m 4096 -smp 4 linux-0.2.img

#  -smp指定处理器个数。

3.3 源码 Bochs2.8 安装过程

3.3.1 安装前配置文件

本机配置(根据需要修改):

./configure --prefix=/usr/local/share/bochs  --enable-ltdl-install --disable-largefile --enable-a20-pin --enable-x86-64 --enable-trace-linking --enable-configurable-msrs  --enable-gdb-stub  --enable-readline --enable-usb --enable-sb16  --enable-busmouse  --enable-e1000 --with-sdl2  

注意:
–with-sdl2 #安装sdl2框架, 也可以安装其他框架。安装命令 :sudo apt install libsdl2-dev
–enable-gdb-stub #打开GDB调试。安装命令:sudo apt install gdb

Configuration:
  -h, --help              display this help and exit
      --help=short        display options specific to this package
      --help=recursive    display the short help of all the included packages
  -V, --version           display version information and exit
  -q, --quiet, --silent   do not print `checking ...' messages
      --cache-file=FILE   cache test results in FILE [disabled]
  -C, --config-cache      alias for `--cache-file=config.cache'
  -n, --no-create         do not create output files
      --srcdir=DIR        find the sources in DIR [configure dir or `..']

Installation directories:
  --prefix=PREFIX         install architecture-independent files in PREFIX
                          [/usr/local]
  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
                          [PREFIX]

By default, `make install' will install all the files in
`/usr/local/bin', `/usr/local/lib' etc.  You can specify
an installation prefix other than `/usr/local' using `--prefix',
for instance `--prefix=$HOME'.

For better control, use the options below.

Fine tuning of the installation directories:
  --bindir=DIR            user executables [EPREFIX/bin]
  --sbindir=DIR           system admin executables [EPREFIX/sbin]
  --libexecdir=DIR        program executables [EPREFIX/libexec]
  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
  --runstatedir=DIR       modifiable per-process data [LOCALSTATEDIR/run]
  --libdir=DIR            object code libraries [EPREFIX/lib]
  --includedir=DIR        C header files [PREFIX/include]
  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
  --infodir=DIR           info documentation [DATAROOTDIR/info]
  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
  --mandir=DIR            man documentation [DATAROOTDIR/man]
  --docdir=DIR            documentation root [DATAROOTDIR/doc/PACKAGE]
  --htmldir=DIR           html documentation [DOCDIR]
  --dvidir=DIR            dvi documentation [DOCDIR]
  --pdfdir=DIR            pdf documentation [DOCDIR]
  --psdir=DIR             ps documentation [DOCDIR]

X features:
  --x-includes=DIR    X include files are in DIR
  --x-libraries=DIR   X library files are in DIR

System types:
  --build=BUILD     configure for building on BUILD [guessed]
  --host=HOST       cross-compile to build programs to run on HOST [BUILD]
  --target=TARGET   configure for building compilers for TARGET [HOST]

Optional Features:
  --disable-option-checking  ignore unrecognized --enable/--with options
  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
  --enable-static-link    link libraries statically [default=disabled]
  --enable-static[=PKGS]  build static libraries [default=no]
  --enable-shared[=PKGS]  build shared libraries [default=yes]
  --enable-fast-install[=PKGS]
                          optimize for fast installation [default=yes]
  --disable-libtool-lock  avoid locking (might break parallel builds)
  --enable-ltdl-install   install libltdl
  --disable-largefile     omit support for large files
  --enable-idle-hack      use Roland Mainz's idle hack (no)
  --enable-plugins        enable plugin support (no)
  --enable-a20-pin        compile in support for A20 pin (yes)
  --enable-x86-64         compile in support for x86-64 instructions (no)
  --enable-smp            compile in support for SMP configurations (no)
  --enable-cpu-level      select cpu level (3,4,5,6 - default is 6)
  --enable-long-phy-address
                          compile in support for physical address larger than
                          32 bit (yes, if cpu level >= 5)
  --enable-large-ramfile  enable large ramfile support (yes)
  --enable-repeat-speedups
                          support repeated IO and mem copy speedups (no)
  --enable-fast-function-calls
                          support for fast function calls (no - gcc on x86 and
                          MSVC nmake only)
  --enable-handlers-chaining
                          support handlers-chaining emulation speedups (no)
  --enable-trace-linking  enable trace linking speedups support (no)
  --enable-configurable-msrs
                          support for configurable MSR registers (yes if cpu
                          level >= 5)
  --enable-show-ips       show IPS in Bochs status bar / log file (yes)
  --enable-cpp            use .cpp as C++ suffix (no)
  --enable-debugger       compile in support for Bochs internal debugger (no)
  --enable-debugger-gui   compile in support for Bochs internal debugger GUI
                          (yes, if debugger is on)
  --enable-gdb-stub       enable gdb stub support (no)
  --enable-iodebug        enable I/O interface to debugger (yes, if debugger
                          is on)
  --enable-all-optimizations
                          compile in all possible optimizations (no)
  --enable-readline       use readline library, if available (no)
  --enable-instrumentation=instrument-dir
                          compile in support for instrumentation (no)
  --enable-logging        enable logging (yes)
  --enable-stats          enable statistics collection (yes)
  --enable-assert-checks  enable BX_ASSERT checks (yes, if debugger is on)
  --enable-fpu            compile in FPU emulation (yes)
  --enable-vmx            VMX (virtualization extensions) emulation
                          (--enable-vmx=[no|1|2])
  --enable-svm            SVM (AMD: secure virtual machine) emulation (no)
  --enable-protection-keys
                          User-Mode Protection Keys support (no)
  --enable-cet            Control Flow Enforcement Technology support (no)
  --enable-uintr          for User Level Interrupt support (no)
  --enable-3dnow          3DNow! support (no - incomplete)
  --enable-alignment-check
                          alignment check (#AC) support (yes, if cpu level >
                          3)
  --enable-monitor-mwait  support for MONITOR/MWAIT instructions (yes, if cpu
                          level > 5 - experimental)
  --enable-perfmon        support for limited hardware performance monitoring
                          emulation (yes, if cpu level > 5 - experimental)
  --enable-memtype        support for memory type
  --enable-avx            support for AVX instructions (no)
  --enable-evex           support for EVEX prefix and AVX-512 extensions (no)
  --enable-amx            support for AMX extensions (no)
  --enable-x86-debugger   x86 debugger support (no)
  --enable-pci            enable i440FX PCI support (yes)
  --enable-pcidev         enable PCI host device mapping support (no - linux
                          host only)
  --enable-usb            enable USB UHCI support (no)
  --enable-usb-ohci       enable USB OHCI support (no)
  --enable-usb-ehci       enable USB EHCI support (no)
  --enable-usb-xhci       enable USB xHCI support (no)
  --enable-ne2000         enable NE2000 support (no)
  --enable-pnic           enable PCI pseudo NIC support (no)
  --enable-e1000          enable Intel(R) Gigabit Ethernet support (no)
  --enable-raw-serial     use raw serial port access (no - incomplete)
  --enable-clgd54xx       enable CLGD54XX emulation (no)
  --enable-voodoo         enable 3dfx Voodoo Graphics emulation (no)
  --enable-cdrom          lowlevel CDROM support (yes)
  --enable-sb16           Sound Blaster 16 Support (no)
  --enable-es1370         enable ES1370 soundcard support (no)
  --enable-gameport       enable standard PC gameport support (yes, if
                          soundcard present)
  --enable-busmouse       enable Busmouse support (InPort & Standard)
  --enable-docbook        build the Docbook documentation (yes, if docbook
                          present)
  --enable-xpm            enable the check for XPM support (yes)

Optional Packages:
  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
  --with-gnu-ld           assume the C compiler uses GNU ld [default=no]
  --with-pic              try to use only PIC/non-PIC objects [default=use
                          both]
  --with-tags[=TAGS]      include additional configurations [automatic]
  --with-x                use the X Window System
  --with-x11                        use X11 GUI
  --with-win32                      use Win32 GUI
  --with-macos                      use Macintosh/CodeWarrior environment
  --with-carbon                     compile for MacOS X with Carbon GUI
  --with-nogui                      no native GUI, just use blank stubs
  --with-term                       textmode terminal environment
  --with-rfb                        use RFB protocol, works with VNC viewer
  --with-vncsrv                     use LibVNCServer, works with VNC viewer
  --with-amigaos                    use AmigaOS (or MorphOS) GUI
  --with-sdl                        use SDL libraries
  --with-sdl2                       use SDL2 libraries
  --with-wx                         use wxWidgets libraries
  --with-all-libs                   compile all guis that Bochs supports

Some influential environment variables:
  CC          C compiler command
  CFLAGS      C compiler flags
  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
              nonstandard directory <lib dir>
  LIBS        libraries to pass to the linker, e.g. -l<library>
  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
              you have headers in a nonstandard directory <include dir>
  CXX         C++ compiler command
  CXXFLAGS    C++ compiler flags
  CXXCPP      C++ preprocessor
  F77         Fortran 77 compiler command
  FFLAGS      Fortran 77 compiler flags
  XMKMF       Path to xmkmf, Makefile generator for X Window System
  CPP         C preprocessor

3.3.2 启动配置文件

可用配置文件(bochsrc文件):

# 设置内存为32MB
megs: 32

# 设置对应机器的BIOS
romimage: file=$BXSHARE/BIOS-bochs-latest 
# 设置对应机器的VGA BIOS
vgaromimage: file=$BXSHARE/VGABIOS-lgpl-latest

# 选择启动盘符,默认为从软盘启动,但是这里设置为硬盘,软盘太古老了
boot: disk 

# 设置日志文件的输出
log: bochs_out.log

# 关闭鼠标功能,打开键盘功能,并且设置键盘的映射
mouse: enabled=0 
keyboard: keymap=$BXSHARE/keymaps/sdl2-pc-us.map 

# 硬盘设置
ata0: enabled=1, ioaddr1=0x1f0, ioaddr2=0x3f0, irq=14 
ata0-master: type=disk, path="hd60M.img", mode=flat, cylinders=121, heads=16, spt=63
#ata0-master: type=disk, path="hdc-0.11.img", mode=flat, cylinders=306, heads=4, spt=17
#ata0-slave: type=disk, path="hd60M.img", mode=flat
#debug_symbols: file="kernel.sym"
display_library: sdl2
gdbstub:enabled=1,port=1234,text_base=0,data_base=0,bss_base=0
#debugger_enabled: yes

注意:

#关闭鼠标功能,打开键盘功能,并且设置键盘的映射 mouse: enabled=0 keyboard:
keymap=$BXSHARE/keymaps/sdl2-pc-us.map

我们实验时选择的是sdl2框架,所以这里键盘影射文件也要选择sdl2-pc-us.map,否则会出错。其他的框架也是要选择相对应的键盘影射文件。

参考详细配置文件(bochsrc-sample.txt):

# You may now use double quotes around pathnames, in case
# your pathname includes spaces.

#=======================================================================
# PLUGIN_CTRL:
# Controls the presence of optional device plugins. These plugins are loaded
# directly with this option and some of them install a config option that is
# only available when the plugin device is loaded. The value "1" means to load
# the plugin and "0" will unload it (if loaded before).
#
# These plugins will be loaded by default (if present): 'biosdev', 'extfpuirq',
# 'gameport', 'iodebug','parallel', 'serial', 'speaker' and 'unmapped'.
#
# These plugins are also supported, but they are usually loaded directly with
# their bochsrc option: 'e1000', 'es1370', 'ne2k', 'pcidev', 'pcipnic', 'sb16',
# 'usb_ehci', 'usb_ohci', 'usb_uhci', 'usb_xhci' and 'voodoo'.
#=======================================================================
#plugin_ctrl: unmapped=0, e1000=1 # unload 'unmapped' and load 'e1000'

#=======================================================================
# CONFIG_INTERFACE
#
# The configuration interface is a series of menus or dialog boxes that
# allows you to change all the settings that control Bochs's behavior.
# Depending on the platform there are up to 3 choices of configuration
# interface: a text mode version called "textconfig" and two graphical versions
# called "win32config" and "wx".  The text mode version uses stdin/stdout or
# gui console (if available / runtime config) and is always compiled in, unless
# Bochs is compiled for wx only. The choice "win32config" is only available on
# win32/win64 and it is the default on these platforms. The choice "wx" is only
# available when Bochs is compiled with wxWidgets support.  If you do not write
# a config_interface line, Bochs will choose a default for you.
#
# NOTE: if you use the "wx" configuration interface, you must also use
# the "wx" display library.
#=======================================================================
#config_interface: textconfig
#config_interface: win32config
#config_interface: wx

#=======================================================================
# DISPLAY_LIBRARY
#
# The display library is the code that displays the Bochs VGA screen.  Bochs
# has a selection of about 10 different display library implementations for
# different platforms.  If you run configure with multiple --with-* options,
# the display_library command lets you choose which one you want to run with.
# If you do not write a display_library line, Bochs will choose a default for
# you.
#
# The choices are:
#   x              use X windows interface, cross platform
#   win32          use native win32 libraries
#   carbon         use Carbon library (for MacOS X)
#   macintosh      use MacOS pre-10
#   amigaos        use native AmigaOS libraries
#   sdl            use SDL 1.2.x library, cross platform
#   sdl2           use SDL 2.x library, cross platform
#   term           text only, uses curses/ncurses library, cross platform
#   rfb            provides an interface to AT&T's VNC viewer, cross platform
#   vncsrv         use LibVNCServer for extended RFB(VNC) support
#   wx             use wxWidgets library, cross platform
#   nogui          no display at all
#
# NOTE: if you use the "wx" configuration interface, you must also use
# the "wx" display library.
#
# Specific options:
# Some display libraries now support specific options to control their
# behaviour. These options are supported by more than one display library:
#
# "cmdmode"     - call a headerbar button handler after pressing F7 <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值