VirtualBox (简体中文) - ArchWiki

Jump to content
翻译状态：本文是 VirtualBox 的翻译。上次翻译日期：2022-10-23。如果英文版本有所更改，则您可以帮助同步翻译。

相关文章

- VirtualBox/Install Arch Linux as a guest
- Category:Hypervisors
- PhpVirtualBox
- RemoteBox
- Moving an existing install into (or out of) a virtual machine

VirtualBox 是运行于现有操作系统之上的虚拟机监视器，用途是在特制环境（即虚拟机）里运行操作系统。VirtualBox 处于活跃开发状态，时常会引入新功能。VirtualBox 支持 Qt，SDL 与无界面 模式运行虚拟机。也支持用 Qt 图形界面和命令行工具管理虚拟机。

为了实现某些主体-客体系统间的整合功能，例如共享目录与剪贴板、显卡加速渲染、无缝窗口整合，VirtualBox 需要在某些系统中安装客体机插件（Guest Addition）。

## 在 Arch 里安装 VirtualBox

以下步骤可以帮你在 Arch 主体系统里安装 VirtualBox

### 安装基本软件包

安装 软件包 virtualbox。内核模块的安装方式要从下面二选一：

- 如果使用的是 linux 内核，建议安装 virtualbox-host-modules-arch
- 其它的内核，包括 linux-lts，请安装 virtualbox-host-dkms

为了让 virtualbox-host-dkms 编译内核模块，需要安装对应的内核头文件（例如linux-lts 内核的头文件是 linux-lts-headers）。[1] 当 VirtualBox 或内核更新的时候，DKMS 的 Pacman 钩子会自动编译内核模块。

### 模块签名

如果你的 Linux 内核是自行编译的，并启用了 `CONFIG_MODULE_SIG_FORCE` 选项，那么你需要用编译内核时所使用的密钥为所有模块签名。

进入内核源码目录，执行下面的命令：

    # for module in `ls /lib/modules/$(uname -r)/kernel/misc/{vboxdrv.ko,vboxnetadp.ko,vboxnetflt.ko}` ; do ./scripts/sign-file sha1 certs/signing_key.pem certs/signing_key.x509 $module ; done

注意： 哈系算法不必与配置时选择的算法相匹配，但必须被编译进内核。

### 加载 VirtualBox 内核模块

virtualbox-host-modules-arch 和 virtualbox-host-dkms 使用 `systemd-modules-load.service` 在启动时自动加载 VirtualBox 的四个内核模块。若要在安装之后就加载模块，可以手动加载一次，或者干脆重启。可以从 `/usr/lib/modules-load.d/virtualbox-host-modules-arch.conf` 或 `/usr/lib/modules-load.d/virtualbox-host-dkms.conf` 中查看加载的模块列表。

注意： 如果希望启动时不自动加载 VirtualBox 模块，需要将默认的 `/usr/lib/modules-load.d/virtualbox-host-modules-arch.conf` (或 ``/usr/lib/modules-load.d/virtualbox-host-dkms.conf``) 配置文件屏蔽掉。具体做法是：在 `/etc/modules-load.d/` 目录里创建同名的空文件。

在 VirtualBox 所使用的 内核模块 中，只有 `vboxdrv` 是必须的。该模块必须在虚拟机运行之前加载。

手动加载模块的命令是：

    # modprobe vboxdrv

以下模块不是必需的，但如果你不想在使用高级功能（见下）时再操心，建议都加载上。

- `vboxnetadp` 和 `vboxnetflt`：这两个模块在使用桥接网络和host-only 网络功能时，都是需要的。具体来说，`vboxnetadp` 模块用于在 VirtualBox 全局配置里为主体机创建虚拟网卡；`vboxnetflt` 模块会在使用了该功能的客体机启动时起作用。

注意： 如果在 VirtualBox 内核模块运行期间你更新了模块（所属的软件包），为了使用新版本，你需要手动重新加载这些模块。在 root 权限下运行 `vboxreload` 即可重新加载。

### 从客体系统访问主机 USB 设备

将需要运行 VirtualBox 的用户名添加到 `vboxusers` 用户组，USB 设备才能被访问。

### 客体机插件光盘

建议在运行 VirtualBox 的主机系统上安装 virtualbox-guest-iso 软件包。这个包里有个 `.iso` 镜像文件，用来为 Arch 之外的客体系统安装插件。镜像文件的位置在 `/usr/lib/virtualbox/additions/VBoxGuestAdditions.iso`，手动在虚拟机的虚拟光驱里加载这个文件之后，即可在客体机里安装插件。

### 扩展包

Oracle Extension Pack 为虚拟机提供了额外功能。但它并不是以自由软件协议发布的，仅供个人使用。这些扩展包可以从 virtualbox-ext-oracleAUR 安装，从 seblu 仓库可以安装编译好的版本。

如果你喜欢使用传统的手动方法来安装扩展包：通过 GUI 下载并安装 (File > Preferences > Extensions) 或着手动下载后用 `VBoxManage extpack install <.vbox-extpack>` 命令来安装。你需要某种方式（例如 Polkit 等等）在安装时为 VirtualBox 授予 root 权限。

### 使用正确的前端

VirtualBox 自带三个前端：

- 如果你想通过常规 GUI 使用 VirtualBox，使用 `VirtualBox` 命令来启动 VirtualBox。
- 如果你想在命令行下启动与管理 VirtualBox，可以使用 `VBoxSDL` 命令。从 VBoxSDL 启动的虚拟机，其窗口仅包含虚拟机的画面，没有菜单或是其他控制项。
- 如果你想使用不想由任何 GUI（例如在服务器上）来使用 VirtualBox，使用 `VBoxHeadless` 命令。如果还想登录到这种虚拟机的图形界面，就需要安装 VRDP 扩展。

A security feature in Wayland (i.e. when using GDM) disallows VirtualBox to grab all keyboard input. This is annoying when you want to pass window manager shortcuts to your guest OS. It can be bypassed by whitelisting VirtualBox:

$ gsettings get org.gnome.mutter.wayland xwayland-grab-access-rules

$ gsettings set org.gnome.mutter.wayland xwayland-grab-access-rules "['VirtualBox Machine']"

The first command will show if any other applications are already whitelisted. If so, add 'VirtualBox Machine' to that list, rather than having it as the only one.

如果你想通过 web 界面来管理虚拟机，可以安装 PhpVirtualBox。

若要了解如何创建虚拟机，可以查阅 VirtualBox 手册。

警告： 如果你想把在虚拟机的硬盘镜像放到 Btrfs 文件系统上，在创建镜像之前，你应该考虑为镜像所处的文件夹关闭写时复制。

## 在 VirtualBox 中安装 Arch Linux

请参阅 VirtualBox (简体中文)/Install Arch Linux as a guest (简体中文)。

## 虚拟磁盘管理

### VirtualBox 支持的格式

VirtualBox 支持下列虚拟磁盘格式：

- VDI: Virtual Disk Image 格式是 VirtualBox 新建虚拟机时默认选用的格式。也是 VirtualBox 的自有开放格式。

- VMDK: Virtual Machine Disk 最初是由 VMware 为其产品研发的格式。该格式技术设计文档最初是闭源的，而现在已经开源，在 VirtualBox 里完全可用。这种格式有个功能是：把一个虚拟机的镜像分割成多个 2GB 大小的文件。如果你要把虚拟机镜像放在不支持大文件的文件系统（例如 FAT32）上，那么这个功能就非常有用。在其他的虚拟磁盘格式里，能做到同样功能的只有 Parallels 的 HDD。

- VHD: Virtual Hard Disk 是 Microsoft 为 Windows Virtual PC 与 Hyper-V 研发的格式。如果你想把虚拟机部署到这些平台上，那么你只能用这种格式。

  提示： Windows 7 开始可以直接把 VHD 文件挂载成虚拟盘进行读写。而不需要额外安装软件。

- VHDX (只读): 这是由 Microsoft 研发的 Virtual Hard Disk 格式的加强版。于 2012-09-04 与 Hyper-V 3.0 同步发布，二者都是 Windows Server 2012 的功能。该加强版的改进包括性能优化（源于区块对齐），支持大区块单位，还有应对断电的磁盘日志。VirtualBox 支持该格式的只读访问。

- HDD (V2): HDD 格式是由 Parallels Inc 研发的，由他们的虚拟机方案（如 Parallels Desktop for Mac）所使用。该格式的新版（v3 和 v4）由于缺少文档，又是专有格式，未能被 VirtualBox 支持。

注意： 关于该格式“仅支持 V2 版”的说法目前有争议。VirtualBox 官方手册 声称只支持 V2 版，但 Wikipedia 上的说法是 V1 版也能正常工作。如果你能为 V1 的支持状况做测试验证，非常欢迎。

- QED: QEMU Enhanced Disk 是旧版 QEMU 使用的格式。QEMU 也是一个开源免费的虚拟机方案。该格式于 2010 年设计出来，目的是要比 QCOW2 等格式更优秀。这种格式支持的功能包括全异步 I/O，数据高度完整性，文件备份，稀疏文件。VirtualBox 支持 QED 格式只是为了兼容由旧版 QEMU 创建的虚拟机。

- QCOW: QEMU Copy On Write 是 QEMU 现有版本支持的格式。QCOW 支持基于 zlib 实现的透明压缩与加密（加密功能有缺陷，不推荐使用）。QCOW 包括两个版本：QCOW 与 QCOW2。QCOW2 取代了旧版。VirtualBox 完全支持旧版 QCOW。QCOW2 包含两个修订版：QCOW2 0.10 和 QCOW2 1.1（QEMU 新建的虚拟机默认使用 1.1）。然而 VirtualBox 并不支持 QCOW2。

- OVF: Open Virtualization Format 是为了在让虚拟机在不同监视器方案间得到通用而设计的开放方案。VirtualBox 支持该格式的所有修订版，具体的支持方式是 VBoxManage import/export 命令，但也有部分功能受限。

- RAW: 虚拟磁盘可以不以任何文件格式封装，而直接以这种 RAW 模式供虚拟机使用。VirtualBox 对此有多种支持方案：将 RAW 磁盘 转换成上述某种格式；将物理盘转换成 RAW 格式；直接挂载一个指向物理盘或 RAW 格式文件的 VMDK 文件。

### 转换虚拟磁盘文件格式

VBoxManage clonehd 这个命令可以实现 VDI, VMDK, VHD 与 RAW 格式间的互转

    $ VBoxManage clonehd inputfile outputfile --format outputformat

以 VDI 转成 VMDK 为例：

    $ VBoxManage clonehd source.vdi destination.vmdk --format VMDK

#### QCOW

VirtualBox 不支持 QEMU 的 QCOW2 格式。若要让 VirtualBox 使用 QCOW2 格式的文件，你只能将其转换成已支持的格式。用 qemu-img 包提供的 `qemu-img` 程序可以做到。`qemu-img` 可以实现 QCOW 格式与 VDI, VMDK, VHDX, RAW 等其他格式间的互转。具体支持的格式可以通过运行 `qemu-img --help` 命令查看。

该命令的一般形式是：

    $ qemu-img convert -O output_fmt inputfile outputfile

以 QCOW2 转成 VDI 为例：

    $ qemu-img convert -O vdi source.qcow2 destination.vdi

提示： 转换时加上 `-p` 参数可以实时查看转换进度

QCOW2 有两个修订版： 0.10 和 1.1，用 `-o compat=revision` 参数可以具体指定。

### 在宿主机直接挂载并读写虚拟磁盘镜像

#### VDI

固定大小的 VDI 镜像（又名静态镜像）可以直接在宿主机挂载。动态镜像则没法轻松挂载。

首先要拿到 VDI 里数据分区的偏移量 `offData`：

    $ VBoxManage internalcommands dumphdinfo <storage.vdi> | grep "offData"

然后再加上 `32256` (例如 69632 + 32256 = 101888)，那么就用这个命令来挂载：

    # mount -t ext4 -o rw,noatime,noexec,loop,offset=101888 storage.vdi /mntpoint/

    For VDI disks with more partitions you can also use losetup:

    # losetup -o $offData -Pf

After this you should find the partitions under `/dev/loop*` (e.g. `/dev/loop0p1`). Then you can mount them as usual (e.g. `mount mount /dev/loop0p1 /mnt/`).

另一个办法是用 mount.vdi 脚本来完成挂载。首先要把脚本安装到 `/usr/bin/`，然后：

    # mount -t vdi -o fstype=ext4,rw,noatime,noexec vdi_file_location /mnt/

还有一个办法是用 qemu-img 的内核模块来实现[2]：

    # modprobe nbd max_part=16
    # qemu-nbd -c /dev/nbd0 <storage.vdi>
    # mount /dev/nbd0p1 /mnt/dir/
    # # to unmount:
    # umount /mnt/dir/
    # qemu-nbd -d /dev/nbd0

如果未能生成分区节点，试试运行命令：`partprobe /dev/nbd0`。另外，VDI 分区还可以直接用这个命令来映射到节点：`qemu-nbd -P 1 -c /dev/nbd0 <storage.vdi>`。

Another way is to use vdfuseAUR:

    # vdfuse -a -f storage.vdi mountpoint1

which mounts the disk in `mountpoint1` with the `PartitionN` naming format. Each partition can then be loop-mounted in `mountpoint2`:

    # mount -o loop mountpoint1/PartitionN mountpoint2

#### VHD

Like VDI, VHD images can be mounted with QEMU's nbd module:

    # modprobe nbd

    # qemu-nbd -c /dev/nbd0 storage.vhd

    # mount /dev/nbd0p1 /mnt

To unmount:

    # umount /mnt

    # qemu-nbd -d /dev/nbd0

### 压紧虚拟磁盘

只有 `.vdi` 格式的虚拟磁盘文件可以压紧。具体操作步骤如下。

启动虚拟机，手动删除无用文件，或者用自动的清理工具（如 bleachbit，同时也支持 Windows）来清理磁盘。

下一步要用零字节来填充可用空间。这有如下的可行方案：

- 如果你已经在用 Bleachbit 了，在 GUI 菜单里选择 System > Free disk space，或者在命令行执行：`bleachbit -c system.free_disk_space`；
- 在类 UNIX 系统里，`dd` 或 dcflddAUR 都可以做到，后者更推荐。（参阅 这里来了解两者的区别）；

      # dcfldd if=/dev/zero of=/fillfile bs=4M

  当 `fillfile` 文件的体积占满分区时，会出现这样的错误信息：`1280 blocks (5120Mb) written.dcfldd:: No space left on device`。这意味着所有的可用空间与未保留区块都已经被零字节填满了。因为 ext 类系统会为 root 用户默认保留一部分硬盘空间（见 `mkfs.ext4` 手册页对 `-m` 参数的解释，或者用 `tune2fs -l` 命令来查看具体为 root 保留了多少空间），所以运行这一命令时需要有 root 权限。
  前面一步操作完成后，手动把 `fillfile` 删掉。

- 在 Windows 系统里有两种办法：

  - 由 Sysinternals Suite 提供的 `sdelete` 命令，用法是 `sdelete -s -z c:`。在虚拟机里的每一个分区都要执行一遍（当然 c: 这个参数要对应地改成各个分区的盼覆）；
  - 如果你喜欢脚本，可以用这个 PowerShell 实现的方案，但依然要每个分区执行一次。

        PS> ./Write-ZeroesToFreeSpace.ps1 -Root c:\ -PercentFree 0

    注意： 该脚本需要在有管理员权限的 PowerShell 环境才能运行。默认的 PowerShell 默认配置下，这个脚本无法运行。需要把秩序策略至少调整到 `RemoteSigned`，而不能是 `Restricted`。用 `Get-ExecutionPolicy` 命令可以看到当前的执行策略，用 `Set-ExecutionPolicy RemoteSigned` 可以设置想要的执行策略。

完成这一步之后，将虚拟机停机。

下一次启动虚拟机时，推荐先进行文件系统检查：

- 在类 UNIX 系统上可以手动运行 `fsck` 来检查；

  - 在 GNU/Linux 系统上（包括 Arch）可以在系统启动时强行执行硬盘检查。详见 thanks to a kernel boot parameter；

- 在 Windows 系统上：

  - 可以用这个命令 `chkdsk c: /F`。其中 `c:` 可以替换成所有你希望检查的盘符；
  - 或者从 这里下载 `FsckDskAll`。这和前面的 `chkdsk` 基本一样，只是不必手动为每个分区执行一遍了。

接下来用 VBoxManage modifyhd 即可完成压紧过程：

    $ VBoxManage modifymedium disk  your_disk.vdi --compact

注意： 如果你的虚拟机有保存过快照，那么每个 `.vdi` 文件都要单独执行一遍压紧操作。

### 扩充虚拟硬盘容量

#### 一般方法

如果你在创建虚拟机时给虚拟硬盘分配的容量太小了，VirtualBox 推荐的扩容方案是用 VBoxManage modifyhd 这个命令。然而这个命令只支持 VDI 和 VHD 这两种格式，而且还需要设置成动态分配容量。如果你想为固定容量的虚拟磁盘扩容，下面的办法可以适用于 Windows 或类 UNIX 系统的虚拟机。

首先创建一个新的虚拟磁盘：

    $ VBoxManage createmedium disk -filename new.vdi --size 10000

`--size` 参数的值的单位是 MiB，在例子里 10000 MiB ~= 10 GiB，`new.vdi` 是新创建的镜像文件。

注意： 由这个命令创建的镜像文件默认是动态分配空间的。如果想让新镜像和旧镜像一样固定空间，需要追加参数 `--variant Fixed`。

接下来要把旧镜像的内容复制到新镜像里去，这一步骤可能会花些时间：

    $ VBoxManage clonemedium disk old.vdi new.vdi --existing

取下旧硬盘镜像，挂载新镜像，下面命令中的斜体字部分需要按照你的使用环境来换成真实的值：

    $ VBoxManage storageattach VM_name --storagectl SATA --port 0 --medium none
    $ VBoxManage storageattach VM_name --storagectl SATA --port 0 --medium new.vdi --type hdd

在上面的命令中，若要获知储存控制器的名字与端口号，可以使用命令：`VBoxManage showvminfo VM_name`。这会打印出如下的输出（斜体标注的信息是有用的）：

    [...]
    Storage Controller Name (0):            IDE
    Storage Controller Type (0):            PIIX4
    Storage Controller Instance Number (0): 0
    Storage Controller Max Port Count (0):  2
    Storage Controller Port Count (0):      2
    Storage Controller Bootable (0):        on
    Storage Controller Name (1):            SATA
    Storage Controller Type (1):            IntelAhci
    Storage Controller Instance Number (1): 0
    Storage Controller Max Port Count (1):  30
    Storage Controller Port Count (1):      1
    Storage Controller Bootable (1):        on
    IDE (1, 0): Empty
    SATA (0, 0): /home/wget/IT/Virtual_machines/GNU_Linux_distributions/ArchLinux_x64_EFI/Snapshots/{6bb17af7-e8a2-4bbf-baac-fbba05ebd704}.vdi (UUID: 6bb17af7-e8a2-4bbf-baac-fbba05ebd704)
    [...]

下载 GParted Live 可引导镜像，在虚拟机里用虚拟光驱加载之，启动虚拟机，调整分区大小 / 位置，取下镜像并重启。这样扩容就完成了。

注意： 如果虚拟盘用了 GPT 分区表，扩容会导致 GPT 备份头不再位于磁盘末尾。GParted 会询问是否要将其修复，此时两次询问都要点 Fix。如果是 MBR 分区，就不存在这一问题。

最后，从 VirtualBox 里注销旧的镜像文件，并删除掉：

    $ VBoxManage closemedium disk old.vdi
    $ rm old.vdi

#### VDI 格式的方法

如果你的虚拟磁盘是 VDI 格式的：

    $ VBoxManage modifymedium disk your_virtual_disk.vdi --resize the_new_size

然后回到上面的 Gparted 步骤，继续完成扩容操作。

### 修改 .vbox 文件来替换磁盘镜像

如果相比用 GUI 或 `VBoxManage` 来管理虚拟机，你觉得编辑 XML 文件更加简单直接。按下面的步骤修改虚拟机对应的 .vbox 文件，即可完成虚拟机的磁盘替换：

    ArchLinux_vm.vbox

    <HardDisk uuid="{670157e5-8bd4-4f7b-8b96-9ee412a712b5}" location="ArchLinux_vm.vdi" format="VDI" type="Normal"/>

找到 `<StorageController>` 的子元素 `<AttachedDevice>`，把 GUID 属性改成新镜像文件的值：

    ArchLinux_vm.vbox

    <AttachedDevice type="HardDisk" port="0" device="0">
      <Image uuid="{670157e5-8bd4-4f7b-8b96-9ee412a712b5}"/>
    </AttachedDevice>

注意： 如果你还不知道新镜像文件的 GUID 值，可以用命令 `VBoxManage showhdinfo file` 来查看。如果你用 `VBoxManage clonehd` 命令来处理过虚拟盘，那么在复制 / 转换过程完成时，也会打印出 GUID 值。随便写一个 GUID 上去是不行的，必须与 镜像文件里的 GUID 值相对应才行。

#### 将虚拟机从 Linux 宿主系统迁移到其他系统（或迁回）

.vbox 配置文件把虚拟盘和快照文件的位置记录在 `<HardDisks> .... </HardDisks>` 标签里。如果新宿主系统存放虚拟机文件的路径与旧宿主系统不同，你可以手动修改 .vbox 文件来调整路径。如果 .vbox 文件与虚拟盘 / 快照文件位于相同的目录，也可以用下面的脚本自动修改。该脚本会将修改后的新配置打印到标准输出。

    #!/bin/sh
    NewPath="${PWD}/"
    Snapshots="Snapshots/"
    Filename="$1"

     awk -v SetPath="$NewPath" -v SnapPath="$Snapshots" '{if(index($0,"<HardDisk uuid=") != 0){A=$3;split(A,B,"=");
    L=B[2];
     gsub(/\"/,"",L);
      sub(/^.*\//,"",L);
      sub(/^.*\\/,"",L);
     if(index($3,"{") != 0){SnapS=SnapPath}else{SnapS=""};
      print $1" "$2" location="\"SetPath SnapS L"\" "$4" "$5}
    else print $0}' "$Filename"

注意：

- 如果你想把虚拟机迁移到 Windows 宿主系统上去，文件路径里应该使用 \ 而不是 /。
- 这个脚本判断快照的逻辑是：文件名是否包含 `{`。
- 为了在新宿主机上运行起来，首先得在管理界面注册：点选菜单项 Machine -> Add... 或者按快捷键 Ctrl+A ，然后找到 .vbox 配置文件。也可以用命令行：`VBoxManage registervm filename.vbox`

### 复制虚拟盘并为其分配新 UUID

VirtualBox 广泛应用了 UUID。每个虚拟机，虚拟机的每个虚拟盘，都有属于自己的 UUID。用 VBoxManage list 命令可以列出 VirtualBox 管理的所有资源。

如果你想复制一台虚拟机，仅复制虚拟盘镜像文件是不够的。你还得给复制出的新镜像文件分配一个新的 UUID。否则在同一个 VirtualBox 的环境里无法同时注册两个具有相同 UUID 的镜像文件。

下面这个命令可以用来为虚拟盘分配新 UUID：

    $ VBoxManage internalcommands sethduuid /path/to/disk.vdi

提示： 用 VBoxManage clonehd 可以一次性完成复制内容与分配新 UUID
注意： 上述命令可以用于任意 VirtualBox 所支持的镜像格式。

## 使用技巧

## Tips and tricks

### Import/export VirtualBox virtual machines from/to other hypervisors

If you plan to use your virtual machine on another hypervisor or want to import in VirtualBox a virtual machine created with another hypervisor, you might be interested in reading the following steps.

#### Remove additions

Guest additions are available in most hypervisor solutions: VirtualBox comes with the Guest Additions, VMware with the VMware Tools, Parallels with the Parallels Tools, etc. These additional components are designed to be installed inside a virtual machine after the guest operating system has been installed. They consist of device drivers and system applications that optimize the guest operating system for better performance and usability by providing these features.

If you have installed the additions to your virtual machine, please uninstall them first. Your guest, especially if it is using an OS from the Windows family, might behave weirdly, crash or even might not boot at all if you are still using the specific drivers in another hypervisor.

#### Use the right virtual disk format

This step will depend on the ability to convert the virtual disk image directly or not.

##### Automatic tools

Some companies provide tools which offer the ability to create virtual machines from a Windows or GNU/Linux operating system located either in a virtual machine or even in a native installation. With such a product, you do not need to apply this and the following steps and can stop reading here.

- Parallels Transporter which is non free, is a product from Parallels Inc. This solution basically consists in an piece of software called agent that will be installed in the guest you want to import/convert. Then, Parallels Transporter, which only works on OS X, will create a virtual machine from that agent which is contacted either by USB or Ethernet network.
- VMware vCenter Converter which is free upon registration on the VMware webiste, works nearly the same way as Parallels Transporter, but the piece of software that will gather the data to create the virtual machine only works on a Windows platform.

##### Manual conversion

First, familiarize yourself with the formats supported by VirtualBox and those supported by third-party hypervisors.

- Importing or exporting a virtual machine from/to a VMware solution is not a problem at all if you use the VMDK or OVF disk format, otherwise converting VMDK to VDI and VDI to VMDK is possible and the aforementioned VMware vCenter Converter tool is available.
- Importing or exporting from/to QEMU is not a problem neither: some QEMU formats are supported directly by VirtualBox and conversion between QCOW2 to VDI and VDI to QCOW2 is still available if needed.
- Importing or exporting from/to Parallels hypervisor is the hardest way: Parallels does only support its own HDD format (even the standard and portable OVF format is not supported!).

  - To export your virtual machine to Parallels, you will need to use the Parallels Transporter tool described above.
  - To import your virtual machine to VirtualBox, you will need to use the VMware vCenter Converter described above to convert the VM to the VMware format first. Then, apply the solution to migrate from VMware.

#### Create the VM configuration for your hypervisor

Each hypervisor have their own virtual machine configuration file: `.vbox` for VirtualBox, `.vmx` for VMware, a `config.pvs` file located in the virtual machine bundle (`.pvm` file), etc. You will have thus to recreate a new virtual machine in your new destination hypervisor and specify its hardware configuration as close as possible as your initial virtual machine.

Pay a close attention to the firmware interface (BIOS or UEFI) used to install the guest operating system. While an option is available to choose between these 2 interfaces on VirtualBox and on Parallels solutions, on VMware, you will have to add manually the following line to your .vmx file.

    ArchLinux_vm.vmx

    firmware = "efi"

Finally, ask your hypervisor to use the existing virtual disk you have converted and launch the virtual machine.

Tip:

- On VirtualBox, if you do not want to browse the whole GUI to find the right location to add your new virtual drive device, you can Replace a virtual disk manually from the .vbox file, or use the `VBoxManage storageattach` described in #Increasing the size of VDI disks or in the VirtualBox manual page.
- Similarly, in VMware products, you can replace the location of the current virtual disk location by adapting the .vmdk file location in your .vmx configuration file.

### Virtual machine launch management

#### Starting virtual machines with a service (autostart)

Find hereafter the implementation details of a systemd service that will be used to consider a virtual machine as a service.

    /etc/systemd/system/vboxvmservice@.service

    [Unit]
    Description=VBox Virtual Machine %i Service
    Requires=systemd-modules-load.service
    After=systemd-modules-load.service

    [Service]
    User=username
    Group=vboxusers
    ExecStart=/usr/bin/VBoxManage startvm %i --type startmode
    ExecStop=/usr/bin/VBoxManage controlvm %i stopmode
    RemainAfterExit=yes

    [Install]
    WantedBy=multi-user.target

Note:

- Replace `username` with a user that is a member of the `vboxusers` group. Make sure the user chosen is the same user that will create/import virtual machines, otherwise the user will not see the VM appliances.
- Replace `startmode` with a VM frontend type, usually `gui`, `headless` or `separate`
- Replace `stopmode` with desired state switch, usually `savestate` or `acpipowerbutton`

Note: If you have multiple virtual machines managed by Systemd and they are not stopping properly, try to add `KillMode=none` and `TimeoutStopSec=40` at the end of `[Service]` section.

Enable the `vboxvmservice@your_virtual_machine_name` systemd unit in order to launch the virtual machine at next boot. To launch it directly, simply start the systemd unit.

VirtualBox 4.2 introduces a new way for UNIX-like systems to have virtual machines started automatically, other than using a systemd service.

#### Starting virtual machines with a keyboard shortcut

It can be useful to start virtual machines directly with a keyboard shortcut instead of using the VirtualBox interface (GUI or CLI). For that, you can simply define key bindings in `.xbindkeysrc`. Please refer to Xbindkeys for more details.

Example, using the `Fn` key of a laptop with an unused battery key (`F3` on the computer used in this example):

    "VBoxManage startvm 'Windows 7'"
    m:0x0 + c:244
    XF86Battery

Note: If you have a space in the name of your virtual machine, then enclose it with single apostrophes like made in the example just above.

### Use specific device in the virtual machine

#### Using USB webcam / microphone

Note: You will need to have VirtualBox extension pack installed before following the steps below. See #Extension pack for details.

1. Make sure the virtual machine is not running and your webcam / microphone is not being used.
2. Bring up the main VirtualBox window and go to settings for Arch machine. Go to USB section.
3. Make sure "Enable USB Controller" is selected. Also make sure that "Enable USB 2.0 (EHCI) Controller" is selected too.
4. Click the "Add filter from device" button (the cable with the '+' icon).
5. Select your USB webcam/microphone device from the list.
6. Now click OK and start your VM.

Note: If your Microphone does not show up in the "Add filter from device" menu, try the USB 3.0 and 1.1 options instead (In Step 3).

#### Detecting web-cams and other USB devices

Note: This will not do much if you are running a *NIX OS inside of your VM, as most do not have autodetection features.

If the device that you are looking for does not show up on any of the menus in the section above and you have tried all three USB controller options, boot up your VM three seperate times. Once using the USB 1.1 controller, another using the USB 2.0 controller, etc. Leave the VM running for at least 5 minutes after startup. Sometimes Windows will autodetect the device for you. Be sure you filter any devices that are not a keyboard or a mouse so they do not start up at boot. This ensures that Windows will detect the device at start-up.

### Access a guest server

To access Apache server on a Virtual Machine from the host machine only, simply execute the following lines on the host:

    $ VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/HostPort" 8888
    $ VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/GuestPort" 80
    $ VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/Apache/Protocol" TCP

where `8888` is the port the host should listen on and `80` is the port the VM will send Apache's signal on.

To use a port lower than 1024 on the host machine, changes need to be made to the firewall on that host machine. This can also be set up to work with SSH or any other services by changing "Apache" to the corresponding service and ports.

Note: `pcnet` refers to the network card of the VM. If you use an Intel card in your VM settings, change `pcnet` to `e1000`.

To communicate between the VirtualBox guest and host using ssh, the server port must be forwarded under Settings > Network. When connecting from the client/host, connect to the IP address of the client/host machine, as opposed to the connection of the other machine. This is because the connection will be made over a virtual adapter.

### D3D acceleration in Windows guests

Recent versions of Virtualbox have support for accelerating OpenGL inside guests. This can be enabled with a simple checkbox in the machine's settings, right below where video ram is set, and installing the Virtualbox guest additions. However, most Windows games use Direct3D (part of DirectX), not OpenGL, and are thus not helped by this method. However, it is possible to gain accelerated Direct3D in your Windows guests by borrowing the d3d libraries from Wine, which translate d3d calls into OpenGL, which is then accelerated. These libraries are now part of Virtualbox guest additions software.

After enabling OpenGL acceleration as described above, reboot the guest into safe mode (press F8 before the Windows screen appears but after the Virtualbox screen disappears), and install Virtualbox guest additions, during install enable checkbox "Direct3D support". Reboot back to normal mode and you should have accelerated Direct3D.

Note:

- This hack may or may not work for some games depending on what hardware checks they make and what parts of D3D they use.
- This was tested on Windows XP, 7 and 8.1. If method does not work on your Windows version please add data here.

### VirtualBox on a USB key

When using VirtualBox on a USB key, for example to start an installed machine with an ISO image, you will manually have to create VDMKs from the existing drives. However, once the new VMDKs are saved and you move on to another machine, you may experience problems launching an appropriate machine again. To get rid of this issue, you can use the following script to launch VirtualBox. This script will clean up and unregister old VMDK files and it will create new, proper VMDKs for you:

This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.

Reason: The following script parses the output of ls, which is very brittle and known to break. (Discuss in Talk:VirtualBox (简体中文))

    #!/bin/sh
    # Erase old VMDK entries
    rm ~/.VirtualBox/*.vmdk

    # Clean up VBox-Registry
    sed -i '/sd/d' ~/.VirtualBox/VirtualBox.xml

    # Remove old harddisks from existing machines
    find ~/.VirtualBox/Machines -name \*.xml | while read -r file; do
      line=$(grep -e "type\=\"HardDisk\"" -n "$file" | cut -d ':' -f 1)
      if [ -n "$line" ]; then
        sed -i "${line}"d "$file"
        sed -i "${line}"d "$file"
        sed -i "${line}"d "$file"
      fi
      sed -i "/rg/d" "$file"
    done

    # Delete prev-files created by VirtualBox
    find  ~/.VirtualBox/Machines -name \*-prev -exec rm '{}' \;

    # Recreate VMDKs
    ls -l /dev/disk/by-uuid | cut -d ' ' -f 9,11 | while read -r ln; do
      if [ -n "$ln" ]; then
        uuid=$(echo "$ln" | cut -d ' ' -f 1)
        device=$(echo "$ln" | cut -d ' ' -f 2 | cut -d '/' -f 3 | cut -b 1-3)

        # determine whether drive is mounted already
        checkstr1=$(mount | grep "$uuid")
        checkstr2=$(mount | grep "$device")
        checkstr3=$(ls ~/.VirtualBox/*.vmdk | grep "$device")
        if [ -z "$checkstr1" ] && [ -z "$checkstr2" ] && [ -z "$checkstr3" ]; then
          VBoxManage internalcommands createrawvmdk -filename ~/.VirtualBox/"$device".vmdk -rawdisk /dev/"$device" -register
        fi
      fi
    done

    # Start VirtualBox
    VirtualBox

Note that your user has to be added to the "disk" group to create VMDKs out of existing drives.

### Run a native Arch Linux installation inside VirtualBox

If you have a dual boot system between Arch Linux and another operating system, it can become tedious to switch back and forth if you need to work in both. You may also experience performance or compatibility issues when using a virtual machine, which can impact your ability to do certain tasks.

This guide will let you reuse, in a virtual machine, your native Arch Linux installation when you are running your second operating system. This way, you keep the ability to run each operating system natively, but have the option to run your Arch Linux installation inside a virtual machine.

#### Make sure you have a persistent naming scheme

Depending on your hard drive setup, device files representing your hard drives may appear differently when you will run your Arch Linux installation natively or in virtual machine. This problem occurs when using FakeRAID for example. The fake RAID device will be mapped in `/dev/mapper/` when you run your GNU/Linux distribution natively, while the devices are still accessible separately. However, in your virtual machine, it can appear without any mapping in `/dev/sdaX` for example, because the drivers controlling the fake RAID in your host operating system (e.g. Windows) are abstracting the fake RAID device.

To circumvent this problem, we will need to use an addressing scheme that is persistent to both systems. This can be achieved using UUIDs. Make sure your boot loader and fstab file is using UUIDs, otherwise fix this issue. Read fstab and Persistent block device naming.

Warning:

- Make sure your host partition is only accessible in read only from your Arch Linux virtual machine, this will avoid risk of corruptions if you were to corrupt that host partition by writing on it due to lack of attention.
- You should NEVER allow VirtualBox to boot from the entry of your second operating system, which, as a reminder, is used as the host for this virtual machine! Take thus a special care especially if your default boot loader/boot manager entry is your other operating system. Give a more important timeout or put it below in the order of preferences.

#### Make sure your mkinitcpio image is correct

Make sure your mkinitcpio configuration uses the HOOK `block`:

    /etc/mkinitcpio.conf

    ...
    HOOKS="base udev autodetect modconf block filesystems keyboard fsck"
    ...

If it is not present, add it and regenerate the initramfs.

#### Create a VM configuration to boot from the physical drive

##### Create a raw disk .vmdk image

Now, we need to create a new virtual machine which will use a RAW disk as virtual drive, for that we will use a ~ 1Kio VMDK file which will be mapped to a physical disk. Unfortunately, VirtualBox does not have this option in the GUI, so we will have to use the console and use an internal command of `VBoxManage`.

Boot the host which will use the Arch Linux virtual machine. The command will need to be adapted according to the host you have.

On a GNU/Linux host

There are 3 ways to achieve this: login as root, changing the access right of the device with `chmod`, adding your user to the `disk` group. The latter way is the more elegant, let us proceed that way:

    # gpasswd -a your_user disk

Apply the new group settings with:

    $ newgrp

Now, you can use the command:

    $ VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sdb -register

Adapt the above command to your need, especially the path and filename of the VMDK location and the raw disk location to map which contain your Arch Linux installation.

On a Windows host

Open a command prompt must be run as administrator.

Tip: On Windows, open your start menu/start screen, type `cmd`, and type `Ctrl+Shift+Enter`, this is a shortcut to execute the selected program with admin rights.

On Windows, as the disk filename convention is different from UNIX, use this command to determine what drives you have in your Windows system and their location:

    # wmic diskdrive get name,size,model

    Model                               Name                Size
    WDC WD40EZRX-00SPEB0 ATA Device     \\.\PHYSICALDRIVE1  4000783933440
    KINGSTON SVP100S296G ATA Device     \\.\PHYSICALDRIVE0  96024821760
    Hitachi HDT721010SLA360 ATA Device  \\.\PHYSICALDRIVE2  1000202273280
    Innostor Ext. HDD USB Device        \\.\PHYSICALDRIVE3  1000202273280

In this example, as the Windows convention is `\\.\PhysicalDriveX` where X is a number from 0, `\\.\PHYSICALDRIVE1` could be analogous to `/dev/sdb` from the Linux disk terminology.

To use the `VBoxManage` command on Windows, you can either, change the current directory to your VirtualBox installation folder first with `cd C:\Program Files\Oracle\VirtualBox\`

    # .\VBoxManage.exe internalcommands createrawvmdk -filename C:\file.vmdk -rawdisk \\.\PHYSICALDRIVE1

or use the absolute path name:

    # "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" internalcommands createrawvmdk -filename C:\file.vmdk -rawdisk \\.\PHYSICALDRIVE1

On another OS host

There are other limitations regarding the aforementioned command when used in other operating systems like OS X, please thus read carefully the manual page, if you are concerned.

##### Create the VM configuration file

Note:

- To make use of the VBoxManage command on Windows, you need to change the current directory to your VirtualBox installation folder first: cd C:\Program Files\Oracle\VirtualBox\.
- Windows makes use of backslashes instead of slashes, please replace all slashes "/" occurrences by backslashes "\" in the commands that follow when you will use them.

After, we need to create a new machine (replace the VM_name to your convenience) and register it with VirtualBox.

    $ VBoxManage createvm -name VM_name -register

Then, the newly raw disk needs to be attached to the machine. This will depend if your computer or actually the root of your native Arch Linux installation is on an IDE or a SATA controller.

If you need an IDE controller:

    $ VBoxManage storagectl VM_name --name "IDE Controller" --add ide
    $ VBoxManage storageattach VM_name --storagectl "IDE Controller" --port 0 --device 0 --type hdd --medium /path/to/file.vmdk

otherwise:

    $ VBoxManage storagectl VM_name --name "SATA Controller" --add sata
    $ VBoxManage storageattach VM_name --storagectl "SATA Controller" --port 0 --device 0 --type hdd --medium /path/to/file.vmdk

While you continue using the CLI, it is recommended to use the VirtualBox GUI, to personalise the virtual machine configuration. Indeed, you must specify its hardware configuration as close as possible as your native machine: turning on the 3D acceleration, increasing video memory, setting the network interface, etc.

Finally, you may want to seamlessly integrate your Arch Linux with your host operating system and allow copy pasting between both OSes. Please refer to VirtualBox/Install Arch Linux as a guest#Install the Guest Additions for that, since this Arch Linux virtual machine is basically an Arch Linux guest.

Warning: For Xorg to work in natively and in the virtual machine, since obviously it will be using different drivers, it is best if there is no `/etc/X11/xorg.conf`, so Xorg will pick up everything it needs on the fly. However, if you really do need your own Xorg configuration, maybe is it worth to set your default systemd target to `multi-user.target` with `systemctl isolate graphical.target` as root (more details at Systemd#Targets and Systemd#Change current target). In that way, the graphical interface is disabled (i.e. Xorg is not launched) and after you logged in, you can `startx`} manually with a custom `xorg.conf`.

### Install a native Arch Linux system from VirtualBox

In some cases it may be useful to install a native Arch Linux system while running another operating system: one way to accomplish this is to perform the installation through VirtualBox on a raw disk. If the existing operating system is Linux based, you may want to consider following Install from existing Linux instead.

This scenario is very similar to #Run a native Arch Linux installation inside VirtualBox, but will follow those steps in a different order: start by #Create a raw disk .vmdk image, then #Create the VM configuration file.

Now, you should have a working VM configuration whose virtual VMDK disk is tied to a real disk. The installation process is exactly the same as the steps described in VirtualBox/Install Arch Linux as a guest, but #Make sure you have a persistent naming scheme and #Make sure your mkinitcpio image is correct.

Warning:

- For BIOS systems and MBR disks, do not install a bootloader inside your virtual machine, this will not work since the MBR is not linked to the MBR of your real machine and your virtual disk is only mapped to a real partition without the MBR.
- For UEFI systems without CSM and GPT disks, the installation will not work at all since:

  - the ESP partition is not mapped to your virtual disk and Arch Linux requires to have the Linux kernel on it to boot as an EFI application (see EFISTUB for details);
  - and the efivars, if you are installing Arch Linux using the EFI mode brought by VirtualBox, are not the one of your real system: the bootmanager entries will hence not be registered.

- This is why, it is recommended to create your partitions in a native installation first, otherwize the partitions will not be taken into consideration in your MBR/GPT partition table.

After completing the installation, boot your computer natively with an GNU/Linux installation media (whether it be Arch Linux or not), chroot into your installed Arch Linux installation and install and configure a bootloader.

### Install MacOS guest

Before starting the VM, run the following commands on the host machine [3]:

    $ VBoxManage modifyvm "MyMacVM" --cpuid-set 00000001 000106e5 00100800 0098e3fd bfebfbff
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct" "iMac11,3"
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion" "1.0"
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Iloveapple"
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"
    $ VBoxManage setextradata "MyMacVM" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1
    $ VBoxManage setextradata "MyMacVM" VBoxInternal2/EfiGopMode 4

#### No keyboard/mouse input when attempting to install Mojave

If you are attempting to install Mojave, after doing the aforementioned steps, the installer will load up but you might not be able to send keyboard or mouse input. The reason seems to be that Mojave no longer supports the USB 1.1 controllers and in order to fix the issue you need to emulating USB 3.0. To do that first install the VirtualBox Extension pack.

Then go to Machine > Settings > USB and select USB 3.0. Input should work from this point onwards.

#### UEFI interactive shell after restart

If the installer is unable to properly format the bootable drive during installation and you end up in an UEFI shell, enter the following:

1. Type `exit` at the UEFI prompt
2. Select Boot Maintenance Manager
3. Select Boot From File

You will now be brought to couple of obscure PCI paths. The first one is the one that you just attempted to boot from and it did not work. The second (or third) one should be the one with the MacOS recovery partition that you need to load to continue the installation. Click the second Entry. If it is empty, press `Esc` to go back and select the third entry. Once you get one with folders click though the folders. It should be something like macOS Install Data > Locked Files > Boot Files > boot.efi. Once you click enter on the boot.efi you should boot into the MacOS installer and resume installation. Note that some of the subdirectories might be missing. Remember that you need to get to a `boot.efi`.[4]

### Move a native Windows installation to a virtual machine

If you want to migrate an existing native Windows installation to a virtual machine which will be used with VirtualBox on GNU/Linux, this use case is for you. This section only covers native Windows installation using the MSDOS/Intel partition scheme. Your Windows installation must reside on the first MBR partition for this operation to success. Operation for other partitions are available but have been untested (see #Known limitations for details).

Warning: If you are using an OEM version of Windows, this process is unauthorized by the end user license license. Indeed, the OEM license typically states the Windows install is tied with the hardware together. Transferring a Windows install to a virtual machine removes this link. Make thus sure you have a full Windows install or a volume license model before continuing. If you have a full Windows license but the latter is not coming in volume, nor as a special license for several PCs, this means you will have to remove the native installation after the transfer operation has been achieved.

A couple of tasks are required to be done inside your native Windows installation first, then on your GNU/Linux host.

#### Tasks on Windows

The first three following points comes from this outdated VirtualBox wiki page, but are updated here.

- Remove IDE/ATA controllers checks (Windows XP only): Windows memorize the IDE/ATA drive controllers it has been installed on and will not boot if it detects these have changed. The solution proposed by Microsoft is to reuse the same controller or use one of the same serial, which is impossible to achieve since we are using a Virtual Machine. MergeIDE, a German tool, developped upon another other solution proposed by Microsoft can be used. That solution basically consists in taking all IDE/ATA controller drivers supported by Windows XP from the initial driver archive (the location is hard coded, or specify it as the first argument to the `.bat` script), installing them and registering them with the regedit database.
- Use the right type of Hardware Abstraction Layer (old 32 bits Windows versions): Microsoft ships 3 default versions: `Hal.dll` (Standard PC), `Halacpi.dll` (ACPI HAL) and `Halaacpi.dll` (ACPI HAL with IO APIC). Your Windows install could come installed with the first or the second version. In that way, please disable the Enable IO/APIC VirtualBox extended feature.
- Disable any AGP device driver (only outdated Windows versions): If you have the files `agp440.sys` or `intelppm.sys` inside the `C:\Windows\SYSTEM32\drivers\` directory, remove it. As VirtualBox uses a PCI virtual graphic card, this can cause problems when this AGP driver is used.
- Create a Windows recovery disk: In the following steps, if things turn bad, you will need to repair your Windows installation. Make sure you have an install media at hand, or create one with Create a recovery disk from Vista SP1, Create a system repair disc on Windows 7 or Create a recovery drive on Windows 8.x).

#### Using Disk2vhd to clone Windows partition

Boot into Windows, clean up the installation (with CCleaner for example), use disk2vhd tool to create a VHD image. Include a reserved system partition (if present) and the actual Windows partition (usually disk C:). The size of Disk2vhd-created image will be the sum of the actual files on the partition (used space), not the size of a whole partition. If all goes well, the image should just boot in a VM and you will not have to go through the hassle with MBR and Windows bootloader, as in the case of cloning an entire partition.

#### Tasks on GNU/Linux

Tip: Skip the partition-related parts if you created VHD image with Disk2vhd.

- Reduce the native Windows partition size to the size Windows actually needs with `ntfsresize` available from ntfs-3g. The size you will specify will be the same size of the VDI that will be created in the next step. If this size is too low, you may break your Windows install and the latter might not boot at all.

  Use the `--no-action` option first to run a test:

      # ntfsresize --no-action --size 52Gi /dev/sda1

  If only the previous test succeeded, execute this command again, but this time without the aforementioned test flag.

- Install VirtualBox on your GNU/Linux host (see #Installation steps for Arch Linux hosts if your host is Arch Linux).

- Create the Windows disk image from the beginning of the drive to the end of the first partition where is located your Windows installation. Copying from the beginning of the disk is necessary because the MBR space at the beginning of the drive needs to be on the virtual drive along with the Windows partition. In this example two following partitions `sda2` and `sda3`will be later removed from the partition table and the MBR bootloader will be updated.

      # sectnum=$(( $(cat /sys/block/sda/sda1/start) + $(cat /sys/block/sda/sda1/size) ))

  Using `cat /sys/block/sda/sda1/size` will output the number of total sectors of the first partition of the disk `sda`. Adapt where necessary.

      # dd if=/dev/sda bs=512 count=$sectnum | VBoxManage convertfromraw stdin windows.vdi $(( $sectnum * 512 ))

  We need to display the size in byte, `$(( $sectnum * 512 ))` will convert the sector numbers to bytes.

- Since you created your disk image as root, set the right ownership to the virtual disk image:

      # chown your_user:your_group windows.vdi

- Create your virtual machine configuration file and use the virtual disk created previously as the main virtual hard disk.

- Try to boot your Windows VM, it may just work. First though remove and repair disks from the boot process as it may interfere (and likely will) booting into safe-mode.

- Attempt to boot your Windows virtual machine in safe mode (press the F8 key before the Windows logo shows up)... if running into boot issues, read #Fix MBR and Microsoft bootloader. In safe-mode, drivers will be installed likely by the Windows plug-and-play detection mechanism view. Additionally, install the VirtualBox Guest Additions via the menu Devices > Insert Guest Additions CD image.... If a new disk dialog does not appear, navigate to the CD drive and start the installer manually.

- You should finally have a working Windows virtual machine. Do not forget to read the #Known limitations.

- Performance tip: according to VirtualBox manual, SATA controller has a better performance than IDE. If you cannot boot Windows off virtual SATA controller right away, it is probably due to the lack of SATA drivers. Attach virtual disk to IDE controller, create an empty SATA controller and boot the VM - Windows should automatically install SATA drivers for the controller. You can then shutdown VM, detach virtual disk from IDE controller and attach it to SATA controller instead.

#### Fix MBR and Microsoft bootloader

If your Windows virtual machine refuses to boot, you may need to apply the following modifications to your virtual machine.

- Boot a GNU/Live live distribution inside your virtual machine before Windows starts up.

- Remove other partitions entries from the virtual disk MBR. Indeed, since we copied the MBR and only the Windows partition, the entries of the other partitions are still present in the MBR, but the partitions are not available anymore. Use `fdisk` to achieve this for example.

      fdisk ''/dev/sda''
      Command (m for help): a
      Partition number (''1-3'', default ''3''): ''1''

- Write the updated partition table to the disk (this will recreate the MBR) using the `m` command inside `fdisk`.

- Use testdisk (see here for details) to add a generic MBR:

      # testdisk > Disk /dev/sda... > [Proceed] >  [Intel] Intel/PC partition > [MBR Code] Write TestDisk MBR to first sector > Write a new copy of MBR code to first sector? (Y/n) > Y > Write a new copy of MBR code, confirm? (Y/N) > A new copy of MBR code has been written. You have to reboot for the change to take effect. > [OK]

- With the new MBR and updated partition table, your Windows virtual machine should be able to boot. If you are still encountering issues, boot your Windows recovery disk from on of the previous step, and inside your Windows RE environment, execute the commands described here.

#### Known limitations

- Your virtual machine can sometimes hang and overrun your RAM, this can be caused by conflicting drivers still installed inside your Windows virtual machine. Good luck to find them!
- Additional software expecting a given driver beneath may either not be disabled/uninstalled or needs to be uninstalled first as the drivers that are no longer available.
- Your Windows installation must reside on the first partition for the above process to work. If this requirement is not met, the process might be achieved too, but this had not been tested. This will require either copying the MBR and editing in hexadecimal see VirtualBox: booting cloned disk or will require to fix the partition table manually or by repairing Windows with the recovery disk you created in a previous step. Let us consider our Windows installation on the second partition; we will copy the MBR, then the second partition where to the disk image. `VBoxManage convertfromraw` needs the total number of bytes that will be written: calculated thanks to the size of the MBR (the start of the first partition) plus the size of the second (Windows) partition. `{ dd if=/dev/sda bs=512 count=$(cat /sys/block/sda/sda1/start) ; dd if=/dev/sda2 bs=512 count=$(cat /sys/block/sda/sda2/size) ; } | VBoxManage convertfromraw stdin windows.vdi $(( ($(cat /sys/block/sda/sda1/start) + $(cat /sys/block/sda/sda2/size)) * 512 ))`.

### Run a native Windows installation inside VirtualBox

Note: The technique outlined in this section only applies to UEFI systems.

In some cases, it is useful to be able to dual boot with Windows and access the partition in a virtual machine. This process is significantly different from #Move a native Windows installation to a virtual machine in several ways:

- The Windows partition is not copied to a virtual disk image. Instead, a raw VMDK file is created;
- Changes in the VM will be mirrored in the partition, and vice versa;
- OEM licenses should still be satisfied, since the Windows partition still boots directly on the hardware.

Warning: Some of the commands used here can corrupt either the Windows partition, the Arch Linux partition, or both. Use extreme caution when executing commands, and double check that they are being run in the correct shell. It would be a good idea to have a backup of the entire drive ready before beginning this process.
Note: Before proceeding be sure to have access to a Windows installation media (such as the Windows 11 ISO).

#### Creating the virtual machine

A VirtualBox virtual machine must be manually created. As of now do not add any storage device any disk to the virtual machine, it will be done manually later.

Configure the virtual machine with the following settings (settings panel can be opened by clicking the "Settings" button in the main toolbar):

- View: System:
  - Tab: Motherboard:
    - mark Enable I/O APIC;
    - mark Enable EFI;
    - mark Hardware Clock in UTC Time if is your case.
  - Tab: Processor:
    - mark Enable PAE/NX;
    - mark Enable VT-x/AMD-V;
  - Tab: Acceleration:
    - Chose the paravirtualization interface Hyper-V from the drop down menu;
    - mark Enable Nested Paging.

Optionally you can enable also the following settings:

- View: Display
  - Tab: Screen
    - mark Enable 3D Acceleration. Note that it could cause glitches.

Note: The Hyper-V setting is not required in order for the system to operate correctly, but it may help avoid licensing issues.

#### Creating virtual machine disks

To access the Windows partitions, create a raw VMDK file pointing to the relevant Windows partitions (root privileges are required to read disk partition table):

    # VBoxManage internalcommands createrawvmdk -filename VM_FOLDER/windows.vmdk -rawdisk WINDOWS_DISK -partitions WINDOWS_RESERVED_PARTITION_NUMBER,WINDOWS_BASIC_DATA_PARTITION_NUMBER -relative

Replace capitalized placeholder strings as follow:

- `VM_FOLDER` with the path of the virtual machine folder (usually a subfolder of `~/VirtualBox VMs`;
- `WINDOWS_DISK` must be replaced with the block device containing all the Windows partitions (e.g.: `/dev/sda` or `/dev/nvme0n1`);
- `WINDOWS_RESERVED_PARTITION_NUMBER` must be replaced with the number of partition labeled "Microsoft reserved partition" (e.g.: if the partition is the `/dev/sda2` the number will be `2`);
- `WINDOWS_PARTITION_NUMBER` must be replaced with the partition containing the Windows installation (e.g.: if the partition is the `/dev/sda3` the number will be `3`);

Example:

    $ sudo VBoxManage internalcommands createrawvmdk -filename "/home/user/VirtualBox VMs/windows.vmdk" -rawdisk /dev/nvme0n1 -partitions 2,3 -relative

The command will also create an extra file inside the virtual machine folder, "windows-pt.vmdk", that will be just ignored.

Note: `windows.vmdk` must be re-created if the partition table is changed.
Tip:

Partition numbers can be found also by running this command and looking at the MIN column:

    lsblk --output NAME,PARTLABEL,FSTYPE,MAJ:MIN,SIZE

    NAME        PARTLABEL                    FSTYPE UUID                                 MAJ:MIN   SIZE
    nvme0n1                                                                              259:0   931,5G
    ├─nvme0n1p1 EFI system partition         vfat   90DC-A6B3                            259:1     100M
    ├─nvme0n1p2 Microsoft reserved partition                                             259:2      16M
    ├─nvme0n1p3 Basic data partition         ntfs   D2A2A104A2A0EE63                     259:3     200G
    ...

Now change the virtual disk owner to give access the user and group running VirtualBox.

    # chown VIRTUALBOX_RUNNING_USER:VIRTUALBOX_RUNNING_GROUP VM_FOLDER/windows.vmdk VM_FOLDER/windows-pt.vmdk

Replace `VIRTUALBOX_RUNNING_USER` and `VIRTUALBOX_RUNNING_GROUP` with the user and the group that will run VirtualBox, which most likely will be your user.

#### Allowing VirtualBox to read physical partitions

VirtualBox must have raw disk access in order to run a Windows partition. Normally, this would require VirtualBox to be run with full root privileges, but more elegant options are available.

##### Higher security option: using a dedicated group for the Windows partitions

Here udev is configured to restrict the access to partitions Windows partitions to the vboxusers group, and then the user running VirtualBox is added to the group.

Assigning the disks to the vboxusers group can be done automatically by creating the following file:

    /etc/udev/rules.d/99-vbox.rules

    #
    # Rules to give VirtualBox users raw access to Windows partitions
    #

    # Microsoft Reserved partition
    SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="e3c9e316-0b5c-4db8-817d-f92df00215ae", GROUP="vboxusers"

    # Windows partition
    SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="ebd0a0a2-b9e5-4433-87c0-68b6b72699c7", GROUP="vboxusers"

    #
    # Rules to give VirtualBox users raw access to Windows disk
    #

    # sdb
    ENV{ID_PART_TABLE_UUID}=="WINDOWS_DISK_ID_PART_TABLE_UUID", GROUP="vboxusers"

`WINDOWS_DISK_ID_PART_TABLE_UUID` must be replaced with the value obtained from `udevadm info /dev/WINDOWS_DISK` (replace `WINDOWS_DISK` with the disk containing Windows partitions). The UUIDs in these rules correspond to particular GPT partition types while the other capitalized strings are supposed to be written that way, so those does not have to be replaced.

Then tge user running VirtualBox must be added to the vboxusers group. This can be done with the following command:

    # usermod -aG vboxusers VIRTUALBOX_RUNNING_USER

Replace `VIRTUALBOX_RUNNING_USER` and with the user that will run VirtualBox, which most likely will be your user.

##### Lower security option: using 'disk' group

To be able to add the vmdk file in Virtualbox Virtual Media Manager without running VirtualBox as root, the user running VirtualBox need to be in `vboxusers` and `disk` groups.

    # usermod -aG disk,vboxusers VIRTUALBOX_RUNNING_USER

Replace `VIRTUALBOX_RUNNING_USER` and with the user that will run VirtualBox, which most likely will be your user.

Warning: Be aware of the potential security implications of this edit, as you are giving your user account full read-write access all storage devices owned by the disk group.

#### Setting up a separate ESP partition

Virtual machine EFI boot files will refer to different disks than the ones in the physical EFI partition, so VirtualBox must not make use of the latter but instead of a EFI partition inside a dedicated virtual disk. This disk can be created with the following command:

    $ VBoxManage createmedium disk --filename VM_FOLDER/esp.vmdk --size 512 --format VMDK

Replace `VM_FOLDER` with the folder containing the virtual machine being built.

#### Adding virtual disks to the virtual machine

Configure the virtual machine storage devices (Settings panel - Storage) as following:

- add `esp.vmdk` as a SATA hard disk attached to the "SATA Port 0";
- add `windows.vmdk` as a SATA hard disk attached to the "SATA Port 1";
- mount Windows installation iso into the virtual optical drive .

Note:

- for adding a SATA hard disk use the second button on the right of the "Controller: SATA" device;
- the virtual optical drive should already be there as "Optical Drive".

#### Configuring the virtual UEFI firmware and creating Windows boot files

Now start the virtual machine and it should automatically boot from Windows installation disk. After choosing the installation locales click on the "Repair your computer" link, then choose "Troubleshoot" and then " Command Prompt" in order to launch a command prompt from the install media.

Enter the following commands to create a new GPT table in the esp.vmdk disk and install the Windows boot loader onto it using configuration from the existing Windows partition:

Open Diskpart:

    X:\ diskpart

List all disks identified by the system:

    DISKPART> list disk

The esp.vmkd disk should be labeled as `disk 0` due to the fact that was attached to the SATA port 0, ~512MB in size and unpartitioned. The `windows.vmdk` disk should be labeled as `disk 1`; note that the column "Size" displays the disk size, not the partition one.

Select the esp.vmdk disk:

    DISKPART> select Disk 0

Now create a GPT partition table, a UEFI partition big as the whole disk and assign to it a label and drive letter:

    DISKPART> clean
    DISKPART> convert gpt
    DISKPART> create partition efi size=500
    DISKPART> format quick fs=fat32 label="System"
    DISKPART> assign letter="S"

Check that the partiton has been correctly created:

    DISKPART> list volume

Our newly created UEFI boot partition will be labeled as "SYSTEM" with letter as "S".

Take note of the Windows installation volume letter because it will be used in next steps. Usually its `D` but it could be different: you can infer it from its label and its size. The size is the same as the Windows installation partition size on your physical hard disk.

Exit diskpart:

    DISKPART> exit

Install the Windows boot loader into the EFI partition.

    D:
    cd Windows\System32
    bcdboot D:\Windows /s S: /f UEFI

Now close the command prompt, power off the virtual machine and detach the Windows installation disk (from "Preferences > Devices" remove the optical disk). The virtual machine should now boot from the newly installed boot partition and load the physical Windows installation. It may show some UEFI related errors on the top of the virtual machine window and the first boot may take a while, but if everything has been done correctly you will be able to access your windows installation.

### Run an entire physical disk in Virtualbox

Note: You may refer to Virtualbox official documentation 9.8.1. Using a Raw Host Hard Disk From a Guest.

This works the same way as #Run a native Windows installation inside VirtualBox but the vmdk will contain the entire disk rather than one partion, and so you will not need to create a separate ESP or MBR partition as the one in the physical disk will be used.

Create the raw disk:

    # VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sdb

Then follow the same method as in #Run a native Windows installation inside VirtualBox for the configuration and virtual disk attachement.

### Set guest starting resolution

You can change the BIOS/UEFI booting resolution using `VBoxManage` tool. For example:

    $ VBoxManage setextradata "Your Virtual Machine Name" "VBoxInternal2/EfiGraphicsResolution" "2560x1440"

Recommended resolutions are 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900.

### SSH from host to guest

The network tab of the virtual machine settings contains, in "Advanced", a tool to create port forwarding. It is possible to use it to forward the Guest ssh port `22` to a Host port, e.g. `3022` :

    user@host$ ssh -p 3022 $USER@localhost

will establish a connection from Host to Guest.

#### SSHFS as alternative to the shared folder

Using this port forwarding and sshfs, it is straightforward to mount the Guest filesystem onto the Host one:

    user@host$ sshfs -p 3022 $USER@localhost:$HOME ~/shared_folder

and then transfer files between both.

## 故障排除

### 鼠标键盘都锁死在虚拟机里了

这是因为你的虚拟机捕获了键盘与鼠标的输入。只要按下右 `Ctrl` 键即可让输入焦点回到宿主系统。

如果想要不按切换键就能让鼠标在宿主机与虚拟机之间无缝切换，这需要安装客户机插件。如果你的虚拟机系统是 Arch Linux，可以参阅前面的章节：#安装客体机插件。其他系统请参阅 VirtualBox 的官方帮助文档。

### 无法新建 64 位虚拟机

如果新建虚拟机时看不到 64 位系统选项，这需要确认你的 CPU 是否支持虚拟化技术（通常称作 `VT-x`），并且还要在 BIOS 中启用。

如果你的宿主系统是 Windows，那么你得禁用 Hyper-V 功能。因为 Hyper-V 会妨碍 VirtualBox 使用 VT-x。[5]

### VirtualBox 图形管理界面和主机 GTK 主题样式不匹配

VirtualBox 的 GUI 是基于 Qt 实现的。为了修改这类应用的外观，见 Uniform look for Qt and GTK applications (简体中文)。

### 无法向虚拟机键入 Ctrl+Alt+Fn

如果你在虚拟机安装了某个 Linux 发行版，有时会需要按 `Ctrl+Alt+F2` 进入它的 TTY 界面，或者按 `Ctrl+Alt+Backspace` 来退出 X 会话。如果你的宿主系统也是 Linux，这些组合键默认会首先被宿主系统捕获。正确的做法是按 Host Key（默认是右 `Ctrl`）加 `F2` 来向虚拟机键入 `Ctrl+Alt+F2`。

### USB 功能不可用

在宿主系统里使用虚拟机的用户需要加入到 `vboxusers` 用户组。如果想要支持 USB 2 设备，还要安装 扩展包。此后在虚拟机的设置里即可开启 USB 2 支持，并且通过过滤规则来允许客体系统访问指定的 USB 设备。

如果用 root 身份运行 `VBoxManage list usbhost` 命令也没有列出任何 USB 设备，需要确认一下 `/etc/udev/rules.d/` 目录里没有遗留的 VirtualBox 4.x 的 udev 规则。VirtualBox 5.0 起会把 udev 规则文件安装到 `/usr/lib/udev/rules.d/` 目录。用 `pacman -Qo /usr/lib/udev/rules.d/60-vboxdrv.rules` 命令可以查看这些 udev 文件是否已经过期。

有时某些旧 Linux 宿主系统无法自动检测到 USB 子系统，就会出现这个错误：`Could not load the Host USB Proxy service: VERR_NOT_FOUND`。或者可能让宿主机也识别不了 USB 磁盘，哪怕用户已经加入了 `vboxusers` 用户组。出现这类问题的原因是 VirtualBox 从 3.0.8 版本开始，从 usbfs 转向使用 sysfs。如果宿主系统不支持这一改动，你可以在 shell 的启动脚本（举例：如果在用 bash 的话，就修改 `~/.bashrc` 文件）里声明这一环境变量，让 VirtualBox 回退到旧的行为：

    ~/.bashrc

    export VBOX_USB=usbfs

然后确保这行代码对环境变量的修改生效：重新登录，手动加载该文件，启动一个新 shell 会话，或者干脆重启。

另外，还应确保用户加入到了 `storage` 用户组。

### USB 调制解调器在宿主系统不可用

如果你的客体系统正在使用 USB 调制解调器，`kill` 掉虚拟机进程可能会造成它在宿主系统里不可用。杀掉并重启余下的 `VBoxSVC` 进程应该可以解决这一问题。

### 虚拟机启动时宿主系统卡死

一般来说，这类问题都是在 VirtualBox 或 Linux 内核版本更新之后初次出现。降级回到前一个版本就有可能解决问题。

### 模拟信号麦克风不可用

如果从模拟信号麦克风输入的音频信号在宿主系统可用，但在客体系统里不可用，可以试试在宿主系统上安装 PulseAudio 之类的音频服务器试试看。

如果装了 PulseAudio 之后麦克风还是不能用，在菜单项 VirtualBox > Machine > Settings > Audio 里把 Host Audio Driver 的值改成 ALSA Audio Driver 也许有用。

### 转换得来的 ISO 文件出现问题

有些镜像文件格式无法可靠地转换到 ISO 格式。例如：ccd2iso 在转换时会忽略 .ccd 和 .sub 文件里的信息，最终产出的 ISO 镜像里的文件就可能受损。

为了避免这种情况，可以使用 CDemu 或类似软件来在 Linux 客体系统里挂载光盘镜像。

### Host-only 网卡创建失败

确保所需的内核模块都已成功加载。详见 #加载 VirtualBox 内核模块。

如果还是不幸，点击文件 > 主机网络管理器 点击创建进行手动创建。

### 插入模块失败

如果你在加载模块时遇到如下错误信息：

    Failed to insert 'vboxdrv': Required key not available

将模块签名，或者在内核配置中禁用 `CONFIG_MODULE_SIG_FORCE`。

### VBOX_E_INVALID_OBJECT_STATE (0x80BB0007)

虚拟机不能平滑退出，就可能出现这个错误。试试下面这个命令：

    $ VBoxManage controlvm virtual_machine_name poweroff

### NS_ERROR_FAILURE 且菜单项缺失

可能是安装了 virtualbox-ext-oracleAUR，但是没有和最新的 virtualbox 版本同步更新。

还可能是创建虚拟机时选择了 QCOW/QCOW2/QED 虚拟盘格式，有时就会出现这个错误。

如果初次启动虚拟机时遇到下面的错误消息：

    Failed to open a session for the virtual machine debian.
    Could not open the medium '/home/.../VirtualBox VMs/debian/debian.qcow'.
    QCow: Reading the L1 table for image '/home/.../VirtualBox VMs/debian/debian.qcow' failed (VERR_EOF).
    VD: error VERR_EOF opening image file '/home/.../VirtualBox VMs/debian/debian.qcow' (VERR_EOF).

    Result Code:
    NS_ERROR_FAILURE (0x80004005)
    Component:
    Medium

退出 VirtualBox，把新建虚拟机的相关文件都删除，并且在 VirtualBox 的配置文件中找到 `MachineRegistry` 元素，从这里删除你所创建的格式错误的虚拟机（一般是其最后一个子元素）：

    ~/.config/VirtualBox/VirtualBox.xml

    ...
    <MachineRegistry>
      <MachineEntry uuid="{00000000-0000-0000-0000-000000000000}" src="/home/void/VirtualBox VMs/debian/debian.vbox"/>
      <MachineEntry uuid="{00000000-0000-0000-0000-000000000000}" src="/home/void/VirtualBox VMs/ubuntu/ubuntu.vbox"/>
      <MachineEntry uuid="{00000000-0000-0000-0000-000000000000}" src="/home/void/VirtualBox VMs/lastvmcausingproblems/lastvmcausingproblems.qcow"/>
    </MachineRegistry>
    ...

### 缺少硬件虚拟化导致 OpenBSD 不稳定

据称在其他的虚拟机平台上，OpenBSD 可以不依赖虚拟化指令集（VT-X，AMD-V）正常运行，VirtualBox 上的 OpenBSD 则不然。具体现象是出现大量的分段错误（segfault）。解决办法是在启动虚拟机时加上 `-norawr0` 参数。例如：

    $ VBoxSDL -norawr0 -vm name_of_OpenBSD_VM

### Windows: "The specified path does not exist. Check the path and then try again."

当在 Windows 客体系统里运行位于共享目录里 `.exe` 程序，而这一程序又需要管理员权限时，就可能出现这一错误信息。[6]

一个解决办法是把文件复制到虚拟硬盘上再运行。或者直接从UNC 路径 (`\\vboxsvr`) 运行程序。详见 [7]。

### Windows 8.x 出现错误代码 0x000000C4

如果你在创建虚拟机时选择了 Win 8 系统，但在启动时还是遇到这一错误，可以尝试启用 `CMPXCHG16B` CPU 指令集。命令如下：

    $ vboxmanage setextradata virtual_machine_name VBoxInternal/CPUM/CMPXCHG16B 1

### Windows 8, 8.1 或 10 无法安装、启动或报错 "ERR_DISK_FULL"

修改虚拟机设置，在菜单项 Settings > Storage > Controller:SATA 里勾选 "Use Host I/O Cache"。

### WinXP: 颜色深度不得多于 16 位

如果只显示 16 位色，桌面图标看起来会模糊 / 结块。但是将色深调高时，系统可能会将桌面分辨率限制得较低，或者根本不允许改变色身。解决办法是在 Windows XP 虚拟机里运行 `regedit`，并写入这一项：

    [HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services]
    "ColorDepth"=dword:00000004

然后再去“桌面属性”窗口里修改色深。如果还是不见效，强制让屏幕重绘（比如按 `Host+f` 进入全屏模式）试试。

### Windows: 开启3D加速后屏幕闪烁

VirtualBox > 4.3.14 has a regression in which Windows guests with 3D acceleration flicker.

由于r120678补丁已经添加识别environment variable设置，可像如下启动VirtualBox：

    $ CR_RENDER_FORCE_PRESENT_MAIN_THREAD=0 VirtualBox

请确保没有VirtualBox服务还在运行，并参考VirtualBox bug 13653。

### Arch Linux guest虚拟机中没有硬件3D加速

virtualbox-guest-utils软件包从5.2.16-2版开始不再包含文件`VBoxEGL.so`。这导致Arch Linux guest虚拟机没有适当的3D加速。参见49752 FS# 49752。

要解决此问题，请应用位于FS#49752#comment152254的补丁集。需要对补丁集进行一些修复，才能使其适用于5.2.16-2版。

### 无法在Wayland上启动VirtualBox：段错误

此问题通常是由Wayland上的Qt引起的，请参见FS#58761。

最好的办法是，在不影响其余的Qt应用程序（通常在Wayland中正常运行）的情况下，取消在VirtualBox的desktop entry中的`QT_QPA_PLATFORM` environment variable设置。

请按照Desktop entries#Modify environment variables中的说明进行操作，并修改Exec：

    Exec=VirtualBox ...

为

    Exec=env -u QT_QPA_PLATFORM VirtualBox ...

如果不起作用，则可能需要将`QT_QPA_PLATFORM`设置为`xcb`：

    Exec=env QT_QPA_PLATFORM=xcb VirtualBox ...

### Windows: Screen flicker if 3D acceleration enabled

VirtualBox > 4.3.14 has a regression in which Windows guests with 3D acceleration flicker. Since r120678 a patch has been implemented to recognize an environment variable setting, launch VirtualBox like this:

    $ CR_RENDER_FORCE_PRESENT_MAIN_THREAD=0 VirtualBox

Make sure no VirtualBox services are still running. See VirtualBox bug 13653.

### Cannot launch VirtualBox with Wayland: Segmentation fault

This problem is caused by Qt detecting Wayland (e.g., if `XDG_SESSION_TYPE=wayland`), while VirtualBox does not work on Wayland yet. See FS#58761 and the upstream bug.

The Qt platform detection can be disabled and X11 forced over Wayland by setting the environment variable `QT_QPA_PLATFORM=xcb`.

To not affect the other Qt applications (which usually work well with Wayland), `QT_QPA_PLATFORM=xcb` should only be set when launching VirtualBox.

If starting through the desktop entry, follow the instructions in Desktop entries#Modify environment variables and change the lines starting with `Exec=VirtualBox ...` to `Exec=env QT_QPA_PLATFORM=xcb VirtualBox ...`. If starting from the shell, alias (Bash#Aliases) `virtualbox` to `env QT_QPA_PLATFORM=xcb virtualbox`.

Note: If you have mouse or keyboard related issue in Wayland, you can try above setting too.

### Random freezing in guests with intel graphics

With Intel cpu and graphics, allocating more processors for the guest can lower render performance, thus cause random freezing. Allocating less or one processor can help.

### Unable to view desktop in fullscreen mode

Disable the Mini Toolbar by selecting Machine > Settings, select the User Interface tab and uncheck the Mini Toolbar checkbox

### Random crashes with Windows 10 guest OS with Intel Tiger Lake chipset

Disable split lock detection by adding `split_lock_detect=off` to the kernel parameters.

Details are described in VirtualBox's Ticket #20180.

### Freeze during virtual machine startup with 11th generation Intel CPU

If the message `traps: Missing ENDBR` and `kernel BUG at arch/x86/kernel/traps.c` appears in the journal you can try adding `ibt=off` as a kernel parameter. Seems to be linked to FS#74891.

### Failed to save the settings when enabling Secure Boot

In VirtualBox 7.0.0, enabling Secure Boot in a virtual machine that was created in a previous VirtualBox version will fail with a nondescript error (FS#76234):

Failed to save the settings.

The solution is to click the Reset Keys to Default button right below the Enable Secure Boot checkbox.

## 参阅

- VirtualBox User Manual
- Wikipedia:VirtualBox

Categories:

- Hypervisors (简体中文)
- Oracle (简体中文)

Hidden category:

- Pages or sections flagged with Template:Style