VirtualBox (Português)

From ArchWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Status de tradução: Esse artigo é uma tradução de VirtualBox. Data da última tradução: 2020-06-23. Você pode ajudar a sincronizar a tradução, se houver alterações na versão em inglês.

Tango-preferences-desktop-locale.pngEste artigo ou esta seção precisa de tradução.Tango-preferences-desktop-locale.png

Notas: Several sections are not translated (Discuta em Talk:VirtualBox (Português)#)

VirtualBox é um hipervisor usado para executar sistemas operacionais em um ambiente especial, chamado de máquina virtual, sobre o sistema operacional existente. O VirtualBox está em constante desenvolvimento e novos recursos são implementados continuamente. Ele vem com uma interface GUI Qt, além de ferramentas de linha de comando SDL para gerenciar e executar máquinas virtuais.

A fim de integrar funções do sistema hospedeiro aos convidados, incluindo pastas compartilhadas e área de transferência, aceleração de vídeo e um modo de integração de janela transparente, os "adicionais para convidado" (guest additions) são fornecidos para alguns sistemas operacionais convidados.

Etapas de instalação para hospedeiros Arch Linux

Para iniciar as máquinas virtuais do VirtualBox na sua caixa Arch Linux, siga estas etapas de instalação.

Instalar os pacotes principais

Instale o pacote virtualbox. Você precisará escolher um pacote para fornecer os módulos de hospedeiro:

Para compilar os módulos do VirtualBox fornecidos pelo virtualbox-host-dkms, também será necessário instalar o(s) pacote(s) apropriado(s) para o(s) seu(s) kernel(s) instalado(s) (p.ex., linux-lts-headers para linux-lts). [1] Quando o VirtualBox ou o kernel é atualizado, os módulos do kernel serão recompilados automaticamente graças ao hook do pacman de DKMS.

Assinar módulos

Ao usar um kernel personalizado com a opção CONFIG_MODULE_SIG_FORCE ativada, você deve assinar seus módulos com uma chave gerada durante a compilação do kernel.

Navegue até a pasta da árvore do kernel e execute o seguinte comando:

# for module in `ls /lib/modules/$(uname -r)/kernel/misc/{vboxdrv.ko,vboxnetadp.ko,vboxnetflt.ko,vboxpci.ko}` ; do ./scripts/sign-file sha1 certs/signing_key.pem certs/signing_key.x509 $module ; done
Nota: O algoritmo de hashing não precisa corresponder ao configurado, mas deve ser integrado ao kernel.

Carregar os módulos de kernel do VirtualBox

virtualbox-host-modules-arch e virtualbox-host-dkms usam systemd-modules-load.service para carregar módulos do VirtualBox automaticamente no momento da inicialização. Para que os módulos sejam carregados após a instalação, reinicie ou carregue os módulos uma vez manualmente; a lista de módulos pode ser encontrada em /usr/lib/modules-load.d/virtualbox-host-modules-arch.conf ou /usr/lib/modules-load.d/virtualbox-host-dkms.conf.

Nota: Se você não quer que os módulos do VirtualBox sejam carregados automaticamente no momento da inicialização, você tem que usar mask para mascarar o padrão /usr/lib/modules-load.d/virtualbox-host-modules-arch.conf (ou /usr/lib/modules-load.d/virtualbox-host-dkms.conf) criando um arquivo vazio (ou um link simbólico para /dev/null) com o mesmo nome em /etc/modules-load.d/.

Dentre os módulos de kernel que o VirtualBox usa, existe um módulo obrigatório chamado vboxdrv, que deve ser carregado antes que qualquer máquina virtual possa ser executada.

Para carregar o módulo manualmente, executar:

# modprobe vboxdrv

Os seguintes módulos são necessários somente em configurações avançadas:

  • vboxnetadp e vboxnetflt são necessários quando você pretende usar os recursos de conexão em modo Bridge ou Rede Interna. Mais precisamente, o vboxnetadp é necessário para criar a interface do hospedeiro nas preferências globais do VirtualBox, e vboxnetflt é necessário para iniciar uma máquina virtual usando essa interface de rede.
Nota: Se os módulos do kernel do VirtualBox foram carregados no kernel enquanto você atualizou os módulos, você precisa recarregá-los manualmente para usar a nova versão atualizada. Para fazer isso, execute vboxreload como root.

Acessando dispositivos USB do hospedeiro no convidado

Para usar as portas USB de sua máquina do hospedeiro em suas máquinas virtuais, adicione usuários que serão autorizados a usar esse recurso para o grupo de usuários vboxusers.

Disco de adicionais para convidado

Também é recomendado instalar o pacote virtualbox-guest-iso no hospedeiro executando o VirtualBox. Este pacote funcionará como uma imagem de disco que pode ser usada para instalar os adicionais para convidado em sistemas convidados que não sejam o Arch Linux. O arquivo .iso estará localizado em /usr/lib/virtualbox/additions/VBoxGuestAdditions.iso, e pode ter que ser montado manualmente dentro da máquina virtual. Uma vez montado, você pode executar o instalador de adicionais para convidado dentro da máquina convidado.

Pacote de extensões

O Oracle Extension Pack fornece funcionalidades adicionais e é lançado sob uma licença não-livre disponível apenas para uso pessoal. Para instalá-lo, o pacote virtualbox-ext-oracleAUR está disponível, e uma versão pré-compilada pode ser encontrada no repositório seblu.

Se você preferir usar o modo tradicional e manual: baixe a extensão manualmente e instale-a através da GUI (Arquivo > Preferências > Extensões) ou via VBoxManage extpack install <.vbox-extpack>, verifique se você tem um kit de ferramentas como Polkit para conceder acesso privilegiado ao VirtualBox. A instalação desta extensão requer acesso de root.

Front-ends

VirtualBox vem com três front-ends:

  • Se você quiser usar o VirtualBox com a GUI regular, use VirtualBox.
  • Se você deseja iniciar e gerenciar suas máquinas virtuais a partir da linha de comando, use o comando VBoxSDL, que fornece apenas uma janela simples para a máquina virtual, sem nenhuma sobreposição.
  • Se você quiser usar o VirtualBox sem executar qualquer GUI (por exemplo, em um servidor), use o comando VBoxHeadless. Com a extensão VRDP, você ainda pode acessar remotamente as exibições de suas máquinas virtuais.

Um recurso de segurança no Wayland (ou seja, ao usar o GDM) não permite que o VirtualBox pegue todas as entradas do teclado. Isso é irritante quando você deseja passar atalhos do gerenciador de janelas para o sistema operacional convidado. Isso pode ser contornado colocando o VirtualBox em uma lista de permissões:

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

O primeiro comando mostrará se outros aplicativos já estão na lista de permissões. Nesse caso, adicione 'VirtualBox Machine' a essa lista, em vez de tê-lo como o único.

Finalmente, você também pode usar phpVirtualBox para administrar suas máquinas virtuais via uma interface web.

Confira o manual do VirtualBox para aprender como criar máquinas virtuais.

Atenção: Se você pretende armazenar imagens de disco virtuais em um sistema de arquivos Btrfs, antes de criar quaisquer imagens, considere a possibilidade de desabilitar copy-on-write (também conhecido como "cópia em gravação") para o destino diretório dessas imagens.

Etapas de instalação para convidados Arch Linux

Veja VirtualBox/Instalar Arch Linux como convidado.

Gerenciamento de discos virtuais

Veja também Importar/exportar máquinas virtuais do VirtualBox de/para outros hipervisores.

Formatos suportados pelo VirtualBox

VirtualBox possui suporte aos seguintes formatos de disco virtual:

  • VDI: O Virtual Disk Image é o próprio contêiner aberto do VirtualBox usado por padrão quando você cria uma máquina virtual com o VirtualBox.
  • VMDK: O Virtual Machine Disk foi inicialmente desenvolvido pela VMware para seus produtos. A especificação foi inicialmente de código fechado, mas tornou-se agora um formato aberto que é totalmente suportado pelo VirtualBox. Este formato oferece a possibilidade de ser dividido em vários arquivos de 2GB. Esse recurso é especialmente útil se você quiser armazenar a máquina virtual em máquinas que não suportam arquivos muito grandes. Outros formatos, excluindo o formato HDD da Parallels, não fornecem esse recurso equivalente.
  • VHD: O Virtual Hard Disk é o formato usado pela Microsoft no Windows Virtual PC e no Hyper-V. Se você pretende usar qualquer um desses produtos da Microsoft, terá que escolher esse formato.
Dica: Desde o Windows 7, esse formato pode ser montado diretamente sem qualquer aplicativo adicional.
  • VHDX (somente leitura): Esta é a versão estendida ("eXtended") do formato Virtual Hard Disk desenvolvido pela Microsoft, que foi lançado em 2012-09-04 com o Hyper-V 3.0 vindo com o Windows Server 2012. Esta nova versão do formato de disco oferece desempenho aprimorado (melhor bloco alinhamento), tamanho de blocos maiores e suporte a journal, o que resulta em resiliência de falha de energia. O VirtualBox deve ter suporte este formato somente leitura.
  • HDD (versão 2): O formato HDD é desenvolvido pela Parallels Inc e usado em suas soluções de hipervisor, como o Parallels Desktop for Mac. Versões mais recentes deste formato (ou seja, 3 e 4) não são suportadas devido à falta de documentação para este formato proprietário.
    Nota: Há atualmente uma controvérsia a cerca do suporte à versão 2 do formato. Enquanto o manual oficial do VirtualBox só relata ter suporte à segunda versão do formato de arquivo HDD, contribuidores do Wikipédia relatam que a primeira versão pode funcionar também. Ajuda é bem-vinda se você puder realizar alguns testes com a primeira versão do formato HDD.
  • QED: O formato de disco aprimorado do QEMU é um formato de arquivo antigo para o QEMU, outro hipervisor de código aberto e software livre. Este formato foi projetado a partir de 2010 de forma a fornecer uma alternativa superior ao QCOW2 e outros. Esse formato apresenta um caminho de E/S totalmente assíncrono, integridade de dados forte, arquivos de apoio e arquivos esparsos. Há suprote ao formato QED apenas para compatibilidade com máquinas virtuais criadas com versões antigas do QEMU.
  • QCOW: O formato QEMU Copy On Write é o formato atual do QEMU. O formato QCOW possui suporte a compressão e criptografia transparentes baseadas em zlib (o último é falho e não é recomendado). O QCOW está disponível em duas versões: QCOW e QCOW2. QCOW2 tende a substituir o primeiro. O QCOW possui atualmente total suporte pelo VirtualBox. O QCOW2 vem em duas revisões: QCOW2 0.10 e QCOW2 1.1 (que é o padrão quando você cria um disco virtual com o QEMU). O VirtualBox não posssui suporte a QCOW2.
  • OVF: O Open Virtualization Format é um formato aberto que foi projetado para interoperabilidade e distribuição de máquinas virtuais entre diferentes hipervisores. O VirtualBox possui suporte a todas as revisões deste formato através do recurso de importação/exportação do VBoxManage, mas com limitações conhecidas.
  • RAW: Esse é o modo quando o disco virtual é exposto diretamente ao disco sem estar contido em um contêiner de formato de arquivo específico. O VirtualBox possui suporte a esse recurso de várias maneiras: convertendo disco RAW para um formato específico ou clonando um disco para RAW ou usando diretamente um arquivo VMDK que aponta para um disco físico ou um arquivo simples.

Conversão de formato de imagem de disco

VBoxManage clonehd pode ser usado para converter entre VDI, VMDK, VHD e RAW.

$ VBoxManage clonehd arquivo_entrada arquivo_saída --format formato_saída

Por exemplo, para converter VDI em VMDK:

$ VBoxManage clonehd origem.vdi destino.vmdk --format VMDK

QCOW

O VirtualBox não possui suporte ao formato de imagem de disco QCOW2 do QEMU. Para usar uma imagem de disco QCOW2 com o VirtualBox, você precisa convertê-la, o que você pode fazer com o comando qemu do qemu-img. qemu-img pode converter QCOW para/de VDI, VMDK, VHDX, RAW e vários outros formatos (que você pode ver executando qemu-img --help).

$ qemu-img convert -O formato_saída arquivo_entrada arquivo_saída

Por exemplo, para converter QCOW2 em VDI:

$ qemu-img convert -O vdi origem.qcow2 destino.vdi
Dica: O parâmetro -p é usado para obter o progresso da tarefa de conversão.

Há duas revisões do QCOW2: 0.10 e 1.1. Você pode especificar a revisão a ser usada com -o compat=revisão.

Montar discos virtuais

VDI

A montagem de imagens VDI só funciona com imagens de tamanho fixo (também imagens estáticas); imagens dinâmicas (alocação dinâmica de tamanho) não são facilmente montáveis.

O deslocamento da partição (dentro da VDI) é necessário, em seguida, adicione o valor de offData a 32256 (por exemplo, 69632 + 32256 = 101888):

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

O armazenamento pode agora ser montado com:

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

Para discos VDI com mais partições, você também pode usar losetup:

# losetup -o $offData -Pf

Depois disso você deve encontrar as partições como /dev/loop* (por exemplo, /dev/loop0p1). Então, você pode montá-las como de costume (por exemplo, mount mount /dev/loop0p1 /mnt/).

Você também pode usar o script mount.vdi, o qual você pode usar como (instale o script em /usr/bin/):

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

Alternativamente, você pode usar o módulo de kernel do qemu que pode fazer essa atribuição:

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

Se os nós da partição não forem propagados, tente usar partprobe/dev/nbd0; caso contrário, uma partição VDI pode ser mapeada diretamente para um nó por: qemu-nbd -P 1 -c /dev/nbd0 <armazenamento.vdi>.

VHD

Como em VDI, imagens VHD podem ser montadas com o módulo nbd do QEMU:

# modprobe nbd
# qemu-nbd -c /dev/nbd0 armazenamento.vhd
# mount /dev/nbd0p1 /mnt

Para desmontar:

# umount /mnt
# qemu-nbd -d /dev/nbd0

Compactar discos virtuais

A compactação de discos virtuais só funciona com arquivos .vdi e consiste basicamente nas seguintes etapas.

Inicialize sua máquina virtual e remova todo o inchaço manualmente ou usando ferramentas de limpeza como bleachbit que está disponível para sistemas Windows também.

A limpeza do espaço livre com zeros pode ser alcançado por meio de várias ferramentas:

  • Se você estava usando Bleachbit anteriormente, marque a caixa de seleção Sistema > Espaço livre em disco na GUI, ou use bleachbit -c system.free_disk_space na CLI;
  • Em sistemas baseados em UNIX, usando dd ou preferencialmente dcflddAUR (veja aqui para aprender as diferenças):
# dcfldd if=/dev/zero of=/arquivo_para_preencher bs=4M

Quando arquivo_para_preencher atingir o limite da partição, você receberá uma mensagem como 1280 blocks (5120Mb) written.dcfldd:: No space left on device. Isso significa que todos os blocos de espaço do usuário e não reservados da partição serão preenchidos com zeros. Usar esse comando como root é importante para garantir que todos os blocos livres tenham sido sobrescritos. De fato, por padrão, ao usar partições com sistema de arquivos ext, uma porcentagem especificada de blocos do sistema de arquivos é reservada para o superusuário (veja o argumento -m nas páginas man do mkfs.ext4 ou use tune2fs -l para ver quanto espaço é reservado para aplicativos da raiz).

Quando o processo supramencionado estiver concluído, você poderá remover o arquivo arquivo_para_preencher que você criou.
  • No Windows, há duas ferramentas disponíveis:
    • sdelete da Sysinternals Suite, digite sdelete -s -z c:, sendo que você precisa reexecutar o comando para cada unidade existente em sua máquina virtual;
    • ou, se você gosta de scripts, há uma solução em PowerShell, mas que ainda precisa ser repetida para todas as unidades.
PS> ./Write-ZeroesToFreeSpace.ps1 -Root c:\ -PercentFree 0
Nota: Este script deve ser executado em um ambiente do PowerShell com privilégios de administrador. Por padrão, os scripts não podem ser executados, certifique-se de que a política de execução esteja, pelo menos, em RemoteSigned e não em Restricted. Isso pode ser verificado com Get-ExecutionPolicy e a política necessária pode ser definida com Set-ExecutionPolicy RemoteSigned.

Uma vez que o espaço livre em disco tenha sido apagado, desligue sua máquina virtual.

Na próxima vez que você inicializar sua máquina virtual, é recomendável fazer uma verificação do sistema de arquivos.

  • Em sistemas baseados em UNIX, você pode usar fsck manualmente;
  • Nos sistemas Windows, você pode usar:
    • chkdsk c: /F sendo que c: precisa ser substituído por cada disco que você precisa verificar e corrigir erros;
    • ou FsckDskAll [2] que é basicamente o mesmo software que chkdsk, mas sem a necessidade de repetir o comando para todas as unidades;

Agora, remova os zeros do arquivo .vdi com VBoxManage modifyhd:

$ VBoxManage modifyhd seu_disco.vdi --compact
Nota: Se sua máquina virtual tiver snapshots, você precisará aplicar o comando acima em cada arquivo .vdi que você possui.

Aumentar discos virtuais

Procedimento geral

Se você está ficando sem espaço devido ao pequeno tamanho do disco rígido que você selecionou quando criou sua máquina virtual, a solução recomendada pelo manual do VirtualBox é usar VBoxManage modifyhd. No entanto, esse comando só funciona para discos VDI e VHD e apenas para as variantes alocadas dinamicamente. Se você quiser redimensionar um disco de disco virtual de tamanho fixo também, leia este truque que funciona para uma máquina virtual do Windows ou UNIX.

Primeiro, crie um novo disco virtual próximo ao que você deseja aumentar:

$ VBoxManage createhd -filename novo.vdi --size 10000

sendo que o tamanho está em MiB, neste exemplo 10000MiB ~= 10GiB e novo.vdi é o nome do novo disco rígido a ser criado.

Nota: Por padrão, esse comando usa a variante de formato de arquivo Standard (correspondente à dinâmica alocada) e, portanto, não usará a mesma variante de formato de arquivo do disco virtual de origem. Se o seu antigo.vdi tiver um tamanho fixo e você quiser manter essa variante, adicione o parâmetro --variant Fixed.

Em seguida, o disco virtual antigo precisa ser clonado para o novo, o que pode levar algum tempo:

$ VBoxManage clonehd antigo.vdi novo.vdi --existing

Desanexe o disco rígido antigo e anexe um novo, substitua todos os argumentos itálicos obrigatórios pelos seus valores apropriados:

$ VBoxManage storageattach nome_VM --storagectl SATA --port 0 --medium none
$ VBoxManage storageattach nome_VM --storagectl SATA --port 0 --medium novo.vdi --type hdd

Para obter o nome do controlador de armazenamento e o número da porta, você pode usar o comando VBoxManage showvminfo nome_VM. Entre os resultados, você obterá esse resultado (o que você está procurando está em itálico):

[...]
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)
[...]

Baixe a imagem do GParted live e monte-a como um arquivo de CD/DVD virtual, inicialize sua máquina virtual, aumente/mova suas partições, desmonte o GParted live e reinicie.

Nota: Nos discos GPT, aumentar o tamanho do disco resultará no backup do cabeçalho GPT não estar no final do dispositivo. O GParted pedirá para corrigir isso, clique em Corrigir nas duas vezes. Nos discos MBR, você não tem esse problema como essa tabela de partições como nenhum trailer no final do disco.

Finalmente, cancele o registro do disco virtual do VirtualBox e remova o arquivo:

$ VBoxManage closemedium disk antigo.vdi
$ rm antigo.vdi

Aumentando o tamanho de discos VDI

Se o seu disco for um VDI, execute:

$ VBoxManage modifyhd seu_disco_virtual.vdi --resize o_novo_tamanho

Em seguida, retorne à etapa Gparted para aumentar o tamanho da partição no disco virtual.

Substituir um disco virtual manualmente a partir do arquivo .vbox

Se você acha que editar um simples arquivo XML é mais conveniente do que brincar com a GUI ou com VBoxManage e você deseja substituir (ou adicionar) um disco virtual à sua máquina virtual, no arquivo de configuração .vbox correspondente à sua máquina virtual, basta substituir o GUID, o local do arquivo e o formato de acordo com suas necessidades:

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

então, na sub-tag <AttachedDevice> de <StorageController>, substitua o GUID pelo novo.

ArchLinux_vm.vbox
<AttachedDevice type="HardDisk" port="0" device="0">
  <Image uuid="{670157e5-8bd4-4f7b-8b96-9ee412a712b5}"/>
</AttachedDevice>
Nota: Se você não souber o GUID da unidade que deseja adicionar, poderá usar o VBoxManage showhdinfo arquivo. Se você usou anteriormente o VBoxManage clonehd para copiar/converter seu disco virtual, este comando deveria ter gerado o GUID logo após a conclusão da cópia/conversão. O uso de um GUID aleatório não funciona, pois cada UUID é armazenado dentro de cada imagem de disco.

Transferir entre hospedeiro Linux e outro SO

As informações sobre o caminho para discos rígidos e snapshots são armazenadas entre as tags <HardDisks> .... </HardDisks> no arquivo com a extensão .vbox. Você pode editá-las manualmente ou usar este script onde você precisará alterar apenas o caminho ou usar os padrões, presumindo que .vbox está no mesmo diretório com um disco virtual e a pasta de instantâneos. Ele imprimirá a nova configuração na stdout.

#!/bin/bash
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"
Nota:
  • Se você for preparar a máquina virtual para uso em um hospedeiro Windows, no final do nome do caminho, use a barra invertida \ em vez de /.
  • O script detecta snapshots procurando { no nome do arquivo.
  • Para executá-lo em um novo hospedeiro, você precisará adicioná-lo primeiro ao registrador clicando em Máquina -> Adicionar... ou usando as teclas de atalho Ctrl+A e depois navegue até arquivo .vbox que contém configuração ou linha de comando de uso VBoxManage registervm nome_de_arquivo. vbox

Clonar um disco virtual e atribuição de um novo UUID a ele

Os UUIDs são amplamente utilizados pelo VirtualBox. Cada máquina virtual e cada disco virtual de uma máquina virtual deve ter um UUID diferente. Quando você inicia uma máquina virtual no VirtualBox, o VirtualBox rastreia todos os UUIDs da sua instância de máquina virtual. Veja a VBoxManage list para listar os itens registrados no VirtualBox.

Se clonou um disco virtual manualmente copiando o arquivo de disco virtual, você precisará atribuir um novo UUID à unidade virtual clonada se desejar usar o disco na mesma máquina virtual ou mesmo em outra (se essa já tiver sido aberto, e assim registrado, com o VirtualBox).

Você pode usar este comando para atribuir um novo UUID a um disco virtual:

$ VBoxManage internalcommands sethduuid /caminho/para/disco.vdi
Dica: Para evitar a cópia do disco virtual e atribuir um novo UUID ao seu arquivo manualmente, você pode usar VBoxManage clonehd.
Nota: Os comando acima possuem suporte a todos os formatos de discos virtuais suportados pelo VirtualBox.

Dicas e truques

Tango-preferences-desktop-locale.pngEste artigo ou esta seção precisa de tradução.Tango-preferences-desktop-locale.png

Notas: Esta seção está sendo traduzida. (Discuta em Talk:VirtualBox (Português)#)

Importar/exportar máquinas virtuais do VirtualBox de/para outros hipervisores

Se você planeja usar sua máquina virtual em outro hipervisor ou deseja importar no VirtualBox uma máquina virtual criada com outro hipervisor, você pode estar interessado em ler as etapas a seguir.

Remover adicionais

Adicionais para convidados estão disponíveis na maioria das soluções de hipervisor: o VirtualBox vem com as adicionais para convidados, o VMware com as VMware Tools, o Parallels com as Parallels Tools etc. Esses componentes adicionais foram projetados para serem instalados dentro de uma máquina virtual após a instalação do sistema operacional convidado. Eles consistem em drivers de dispositivo e aplicativos de sistema que otimizam o sistema operacional convidado para melhor desempenho e usabilidade fornecendo esses recursos.

Se você instalou os adicionais à sua máquina virtual, desinstale-os primeiro. Seu convidado, especialmente se estiver usando um sistema operacional da família Windows, pode se comportar de maneira estranha, travar ou até não inicializar se você ainda estiver usando os drivers específicos em outro hipervisor.

Usar o formato de disco virtual correto

Esta etapa dependerá da capacidade de converter a imagem do disco virtual diretamente ou não.

Ferramentas automáticas

Algumas empresas fornecem ferramentas que oferecem a capacidade de criar máquinas virtuais a partir de um sistema operacional Windows ou GNU/Linux localizado em uma máquina virtual ou mesmo em uma instalação nativa. Com esse produto, você não precisa aplicar esta e as etapas a seguir e pode parar de ler aqui.

  • Parallels Transporter que não é gratuito, é um produto da Parallels Inc. Essa solução basicamente consiste em um software chamado agente que será instalado no convidado que você deseja importar/converter. Em seguida, o Parallels Transporter, que funciona apenas no OS X, criará uma máquina virtual a partir desse agente que será contatado pelo USB ou por rede Ethernet.
  • VMware vCenter Converter que é gratuito após o registro no site da VMware, funciona quase da mesma maneira que o Parallels Transporter, mas o software que reúne os dados para criar a máquina virtual funciona apenas em uma plataforma Windows.
Conversão manual

Primeiro, familiarize-se com os formatos suportados pelo VirtualBox e compatíveis com os hipervisores de terceiros.

  • A importação ou exportação de uma máquina virtual de/para uma solução VMware não é um problema se você usar o formato de disco VMDK ou OVF; caso contrário, é possível converter VMDK para VDI e VDI para VMDK e a ferramenta VMware vCenter Converter mencionada acima está disponível.
  • A importação ou exportação de/para QEMU também não é um problema: alguns formatos QEMU são suportados diretamente pelo VirtualBox e a conversão entre QCOW2 em VDI e VDI em QCOW2 ainda está disponível, se necessário.
  • A importação ou exportação de/para o hipervisor Parallels é a maneira mais difícil: o Parallels suporta apenas seu próprio formato HDD (mesmo o formato OVF padrão e portátil não é suportado!).
  • Para exportar sua máquina virtual para o Parallels, você precisará usar a ferramenta Parallels Transporter descrita acima.
  • Para importar sua máquina virtual para o VirtualBox, você precisará usar o VMware vCenter Converter descrito acima para converter a VM no formato VMware primeiro. Em seguida, aplique a solução para migrar do VMware.

Criar a configuração VM para seu hipervisor

Cada hipervisor possui seu próprio arquivo de configuração da máquina virtual: .vbox para VirtualBox, .vmx para VMware, um arquivo config.pvs localizado no pacote da máquina virtual (arquivo .pvm) etc. Você precisará recriar uma nova máquina virtual em seu novo hipervisor de destino e especificar sua configuração de hardware o mais próximo possível da sua máquina virtual inicial.

Preste muita atenção à interface do firmware (BIOS ou UEFI) usada para instalar o sistema operacional convidado. Embora haja uma opção disponível para escolher entre essas duas interfaces nas soluções VirtualBox e Parallels, no VMware, você precisará adicionar manualmente a seguinte linha ao seu arquivo .vmx.

ArchLinux_vm.vmx
firmware = "efi"

Por fim, peça ao seu hipervisor para usar o disco virtual existente que você converteu e inicie a máquina virtual.

Dica:

Gerenciamento de lançamento de máquina virtual

Iniciando máquinas virtuais com um serviço (inicialização automática)

A seguir, veja os detalhes de implementação de um serviço systemd que será usado para considerar uma máquina virtual como um serviço.

/etc/systemd/system/vboxvmservice@.service
[Unit]
Description=VBox Virtual Machine %i Service
Requires=systemd-modules-load.service
After=systemd-modules-load.service

[Service]
User=nome_de_usuário
Group=vboxusers
ExecStart=/usr/bin/VBoxManage startvm %i --type modo_início
ExecStop=/usr/bin/VBoxManage controlvm %i modo_parada
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
Nota:
  • Substitua nome_de_usuário por um usuário que seja membro do grupo vboxusers. Verifique se o usuário escolhido é o mesmo que criará/importará máquinas virtuais, caso contrário, o usuário não verá os dispositivos da VM.
  • Substitua modo_início por um tipo de front-end da VM, geralmente gui, headless ou separate
  • Substitua modo_parada pela opção de estado desejada, geralmente savestate ou acpipowerbutton
Nota: Se você possui várias máquinas virtuais gerenciadas pelo Systemd e elas não estão parando corretamente, tente adicionar KillMode=none e TimeoutStopSec=40 no final da seção [Service].

Habilite a unit de systemd vboxvmservice@nome_da_sua_máquina_virtual para iniciar a máquina virtual na próxima inicialização. Para iniciá-la diretamente, basta iniciar a unit de systemd.

O VirtualBox 4.2 apresenta uma nova maneira[link inativo 2021-11-19 ⓘ] para sistemas do tipo UNIX para que máquinas virtuais sejam iniciadas automaticamente, exceto pelo uso de um serviço systemd.

Iniciando máquinas virtuais com um atalho de teclado

Pode ser útil iniciar máquinas virtuais diretamente com um atalho de teclado em vez de usar a interface VirtualBox (GUI ou CLI). Para isso, você pode simplesmente definir ligações de teclas em .xbindkeysrc. Por favor, consulte Xbindkeys para mais detalhes.

Exemplo, usando a tecla Fn de um laptop com uma tecla de bateria não utilizada (F3 no computador usado neste exemplo):

 "VBoxManage startvm 'Windows 7'"
 m: 0x0 + c: 244
 XF86Battery
Nota: Se você tiver um espaço no nome da sua máquina virtual, coloque-o com aspas simples, como feito no exemplo acima.

Usar dispositivo específico na máquina virtual

Usando webcam / microfone USB

Nota: Você precisará ter o pacote de extensão do VirtualBox instalado antes de seguir as etapas abaixo. Veja #Pacote de extensões para detalhes.
  1. Certifique-se de que a máquina virtual não esteja funcionando e que sua webcam / microfone não esteja sendo usada(o).
  2. Abra a janela principal do VirtualBox e vá para as configurações da máquina Arch. Vá para a seção USB.
  3. Certifique-se de que "Habilitar Controladora USB" esteja selecionado. Certifique-se também de que "Habilitar Controladora USB 2.0 (EHCI)" também esteja selecionado.
  4. Clique no botão "Acrescentar filtro de dispositivo" (o cabo com o ícone "+").
  5. Selecione seu dispositivo de webcam / microfone USB na lista.
  6. Agora, clique em OK e inicie sua VM.
Nota: Se o seu microfone não aparecer no menu "Adicionar filtro do dispositivo", tente as opções USB 3.0 e 1.1 (na etapa 3).

Detectando webcams e outros dispositivos USB

Nota: Isso não vai adiantar muito se você estiver executando um sistema operacional *NIX dentro de sua VM, pois a maioria não tem recursos de detecção automática.

Se o dispositivo que você está procurando não aparecer em nenhum dos menus da seção acima e você tiver tentado todas as três opções de controlador USB, inicialize sua VM três vezes separadas. Uma vez usando o controlador USB 1.1, outra usando o controlador USB 2.0, etc. Deixe a VM funcionando por pelo menos 5 minutos após a inicialização. Às vezes, o Windows detecta automaticamente o dispositivo para você. Certifique-se de filtrar quaisquer dispositivos que não sejam um teclado ou mouse, para que não sejam inicializados na inicialização. Isso garante que o Windows detectará o dispositivo na inicialização.

Acessar um servidor convidado

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.

Aceleração D3D em convidados Windows

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.
Note: This was tested on Windows XP, 7 and 8.1. If method does not work on your Windows version please add data here.

VirtualBox em um teclado USB

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:

#!/bin/bash

# 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 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 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.

Executar uma instalação nativa do Arch Linux no VirtualBox

If you have a dual boot system between Arch Linux and another operating system, it can become rapidly tedious to switch back and forth if you need to work in both. Also, by using virtual machines, you just have a tiny fragment of your computer power, which can cause issues when working on projects requiring performance.

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.

Verificar se você tem um esquema de nomeação persistente

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.

Atenção:
  • 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.

Verificar se a imagem do seu mkinitcpio está correta

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.

Criar uma configuração de VM para inicializar a partir da unidade física

Criar uma imagem .vmdk de disco raw

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.

Dica: 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.

Criar o arquivo de configuração da VM
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.

Atenção: 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.

Instalar um sistema Arch Linux nativo a partir do 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[link quebrado: seção inválida], but will follow those steps in a different order: start by #Create a raw disk .vmdk image[link quebrado: seção inválida], then #Create the VM configuration file[link quebrado: seção inválida].

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[link quebrado: seção inválida] and #Make sure your mkinitcpio image is correct[link quebrado: seção inválida].

Atenção:
  • 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.

Instalar convidado MacOS

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/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

Nenhuma entrada do teclado/mouse ao iniciar a instalação do 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[link quebrado: seção inválida].

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

Shell interativo UEFI após reiniciar

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]

Mover uma instalação nativa do Windows para uma máquina virtual

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[link quebrado: seção inválida] for details).

Atenção: 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.

Tarefas no 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).

Usando Disk2vhd para clonar partição do Windows

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.

Tarefas no GNU/Linux

Dica: Skip the partition-related parts if you created VHD image with Disk2vhd[link quebrado: seção inválida].
  • 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.
  • 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 sda3will 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[link quebrado: seção inválida]. 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.
  • 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.

Corrigir MBR e gerenciador de boot da Microsoft

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.
# 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.

Limitações conhecidas

  • 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 )).

Executar uma partição do Windows no 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[link quebrado: seção inválida] 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
Atenção: 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.
Dica: It will be useful to have the Arch install ISO readily available, as it will be used the configure the EFI system partition in the VM. It is also worth having access to Windows installation media (such as the Windows 10 ISO) in case the Windows partition is corrupted.

Configurar o udev para fornecer ao VirtualBox acesso de raw às partições do Windows

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 udev can be configured to restrict access to certain partitions. One convenient way to do this assign all Windows-related partitions to the vboxusers group, which can be done with the following udev rules:

Note: The UUIDs in these rules correspond to particular GPT partition types. In this case, the UUIDs correspond to all Microsoft Reserved (msftres) and Microsoft basic data (msftdata) partitions.
/etc/udev/rules.d/99-vbox.rules
# Rules to give VirtualBox users raw access to Windows partitions

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

# Windows partitions (msftdata)
SUBSYSTEM=="block", ENV{ID_PART_ENTRY_TYPE}=="ebd0a0a2-b9e5-4433-87c0-68b6b72699c7", GROUP="vboxusers"
Dica: Useful udev environment variables and attributes corresponding to a particular partition can be found by running udevadm info /dev/sdXX.

Configuração do VirtualBox

A VirtualBox VM must be manually created with a custom configuration.

Note: Do not add a virtual disk during the initial creation of the VM.

Configure the VM with the following settings:

  • System
    • Motherboard
      • Enable I/O APIC
      • Enable EFI
      • Hardware Clock in UTC Time
    • Acceleration
      • Paravirtualization Interface: Hyper-V
      • Enable VT-x/AMD-V
      • Enable Nested Paging
  • Display > Screen > Acceleration
    • Enable 3D Acceleration
    • Enable 2D Acceleration
  • USB > Enable USB Controller
Note: The Hyper-V setting is not required in order for the system to operate correctly, but it may help avoid licensing issues.
Criar arquivos de imagem de disco virtual

To access the Windows partitions, create a raw VMDK file pointing to the relevant Windows partitions and set the ownership:

# vboxmanage internalcommands createrawvmdk -filename /path/to/vm/folder/windows.vmdk -rawdisk /dev/sdx -partitions res,data -relative
# chown user:group /path/to/vm/folder/windows.vmdk
Note: When creating the raw VMDK file...
  • Root access because VirtualBox must read the partition table
  • The -rawdisk parameter should point to a block device, not a partition
  • res is the partition number of the Microsoft Reserved Partition
  • data is the partition number of the Microsoft basic data partition (i.e. the Windows installation)
  • An extra file (windows-pt.vmdk) will also be created
  • windows.vmdk will need to be re-created if the partition table is changed

After creating the image, change the ownership so that the desired user/group has access:

In order to boot the virtual machine in UEFI mode, a dedicated virtual disk for the EFI system partition must be created:

$ vboxmanage createmedium disk --filename /path/to/vm/folder/esp.vmdk --size 512 --format VMDK
Anexar imagens de disco virtual à VM
Configuração de permissões do sistema de arquivos com segurança mais alta

Add your user in virtualbox group:

# usermod -aG vboxusers user

Determine the UUID of the targeted disk.

# udevadm info /dev/sdb | grep UUID

Example of output:

E: ID_PART_TABLE_UUID=01234567-89ab-cdef-0123-456789abcde

Create an udev rule with the found UUID:

/etc/udev/rules.d/99-vbox.rules
# Rules to give VirtualBox users raw access to Windows disk

# sdb
ENV{ID_PART_ENTRY_TYPE}=="1234567-89ab-cdef-0123-456789abcde", GROUP="vboxusers"
Configuração de permissões do sistema de arquivos com segurança mais baixa

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

# usermod -aG disk,vboxusers user

Once the disk is added to the Virtual Media Manager, it is possible to attach it to a virtual machine through the GUI.

Atenção: Be aware of the potential security implications of this, as you will probably be giving your user account full read-write access to some or all storage devices.

Configurar uma ESP separada no VirtualBox

Configure the settings of the virtual machine and add the previously created ESP disk (ie /path/to/vm/folder/esp.vmdk) to the virtual machine.

Configurar o firmware UEFI virtual para usar o gerenciador de boot do Windows

This will require a Windows Installation disk (successfully tested Windows 10 Pro Build 1903).

(Note: The following disk order may not matter) Configure the Virtual Machine with the previously created disks as following:

  • Add the newly created ESP disk as a SATA device (SATA Port 0).
  • Add the newly created rawdisk as a SATA device (SATA Port 1).
  • Mount the Windows Installation disk into an optical drive.

Start the Virtual Machine and boot from the Windows Installation disk.

Prior to partitioning and installation, press SHIFT+F10 to launch command prompt from the install media.

Enter the following commands to create a new GPt partitioned disk (the ESP vmdk), and install the Windows Boot Loader onto it using configuration from the existing Windows partition:

From the Command Prompt, open Diskpart.

diskpart

List all disks identified by the system

list disk

The desired disk should be 500MB in size and unpartitioned. If the disk order was adhered to as above, it should be disk 0.

Select and use the desired disk

Here we will use disk 0

select disk 0

Format as UEFI and assign a label and drive letter

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

List all known volumes

list volume
exit

It is likely that the original Windows partition will be listed as C here. Our newly created UEFI boot partition will be labelled as S with System.

Installed the Windows Boot Loader onto UEFI disk

Again, assuming out original Windows install is detected as 'C' and our new UEFI disk is 'S'

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

Now simply detach the Windows Installation disk from the VM and reboot. The VM should now boot from the newly installed boot partition on ESP vmdk, and load the original Windows installation. It may display 'detecting disks' for a short while prior to booting up.

Executar um disco totalmente físico no 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 Windows partition in VirtualBox[link quebrado: seção inválida] 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 Windows partition in VirtualBox[link quebrado: seção inválida] for the configuration and virtual disk attachement.

Definir a resolução inicial do convidado

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 do hospedeiro para o convidado

A aba de rede das configurações da máquina virtual contém, em Avançado, uma ferramenta para criar o encaminhamento de porta. É possível usá-lo para encaminhar a porta ssh do convidado 22 para uma porta do hospedeiro, por exemplo, 3022:

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

vai estabelecer uma conexão entre hospedeiro e o convidado.

SSHFS como alternativa à pasta compartilhada

Usando este encaminhamento de porta e o sshfs, é simples montar o sistema de arquivos do convidado no do hospedeiro:

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

e transferir arquivos entre ambos.

Solução de problemas

Teclado e mouse estão travados na máquina virtual

Isso significa que sua máquina virtual capturou a entrada do teclado e do mouse. Simplesmente pressione a tecla Ctrl e sua entrada deve controlar seu hospedeiro novamente.

Para controlar de forma transparente sua máquina virtual com o mouse indo e voltando de seu hospedeiro, sem ter que pressionar nenhuma tecla e, assim, ter uma integração perfeita, instale os adicionais para convidados dentro do convidado. Leia a partir do passo #Instalar os adicionais para convidado[link quebrado: seção inválida] se o convidado for o Arch Linux, caso contrário leia a ajuda oficial do VirtualBox.

Nenhuma opção para cliente de SO 64 bits

Ao iniciar um cliente VM e nenhuma opção de 64 bits estiver disponível, verifique se os recursos de virtualização da CPU (geralmente denominados VT-x) estão habilitados na BIOS.

Se você estiver usando um hospedeiro do Windows, talvez seja necessário desabilitar o Hyper-V, já que ele impede que o VirtualBox use o VT-x. [5]

VirtualBox GUI não corresponde ao tema GTK do hospedeiro

Veja Uniform look for Qt and GTK applications para informações sobre aplicação de temas em aplicativos baseados no Q, como o VirtualBox.

Não é possível enviar Ctrl+Alt+Fn para o convidado

O sistema operacional do convidado é uma distribuição GNU/Linux e você deseja abrir um novo shell TTY pressionando Ctrl+Alt+F2 ou sair da sessão atual com Ctrl+Alt+Backspace. Se você digitar esses atalhos de teclado sem qualquer adaptação, o convidado não receberá nenhuma entrada e o hospedeiro (se for uma distribuição GNU/Linux também) interceptará essas teclas de atalho. Para enviar Ctrl+Alt+F2 para o convidado, por exemplo, simplesmente pressione a Tecla do Hospedeiro (normalmente a tecla Ctrl da direita) e pressione F2 simultaneamente.

Subsistema USB não funciona

Seu usuário deve estar no grupo vboxusers e você precisa instalar o pacote de extensões se quiser suporte a USB 2. Em seguida, você poderá ativar o USB 2 nas configurações da VM e adicionar um ou vários filtros para os dispositivos que deseja acessar no sistema operacional do convidado.

Se VBoxManage list usbhost não mostrar nenhum dispositivo USB, mesmo que seja executado como root, certifique-se de que não há regras antigas do udev (do VirtualBox 4.x) em /etc/udev/rules.d/. O VirtualBox 5.0 instala as regras do udev para /usr/lib/udev/rules.d/. Você pode usar o comando como pacman -Qo /usr/lib/udev/rules.d/60-vboxdrv.rules para determinar se o arquivo de regras do udev está desatualizado.

Às vezes, em hospedeiros Linux antigos, o subsistema USB não é detectado automaticamente, resultando em um erro Could not load the Host USB Proxy service: VERR_NOT_FOUND ou em uma unidade USB não visível no hospedeiro, mesmo quando o usuário está no grupo vboxusers. Este problema é devido ao fato de que o VirtualBox mudou de usbfs para sysfs na versão 3.0.8. Se o hospedeiro não entender essa alteração, você poderá reverter para o comportamento antigo definindo a seguinte variável de ambiente em qualquer arquivo originado pelo seu shell (por exemplo, ~/.bashrc se estiver usando bash):

~/.bashrc
VBOX_USB=usbfs

Em seguida, certifique-se de que o ambiente tenha conhecimento dessa alteração (reconecte, crie o arquivo manualmente, ative uma nova instância do shell ou reinicialize).

Certifique-se também de que seu usuário seja membro do grupo storage.

Modem USB não funciona no hospedeiro

Se você tiver um modem USB que está sendo usado pelo sistema operacional convidado, a eliminação do sistema operacional convidado pode fazer com que o modem fique inutilizável pelo sistema hospedeiro. Matar e reiniciar VBoxSVC deve corrigir este problema.

Dispositivo USB trava o convidado

Se a conexão de um dispositivo USB ao convidado causar uma falha ou qualquer outro comportamento incorreto, tente alternar o controlador USB de USB 2 (EHCI) para USB 3 (xHCI) ou vice-versa.

Hospedeiro trava ao iniciar máquina virtual

Geralmente, tais problemas são observados após a atualização do VirtualBox ou do kernel do Linux. Fazer downgrade para as versões anteriores deles pode resolver o problema.

Desabilitar virtualização de hardware (VT-x/AMD-V) pode resolver o problema.

Microfone analógico não funciona

Se a entrada de áudio de um microfone analógico está funcionando corretamente no hospedeiro, mas nenhum som parece passar para o convidado, apesar do dispositivo de microfone aparentemente ser detectado normalmente, instalar um servidor de som como como PulseAudio no hospedeiro pode corrigir o problema.

Se depois de instalar o PulseAudio o microfone ainda se recusar a funcionar, configurar Driver de áudio do Hospedeiro (em VirtualBox > Máquina > Configurações > Áudio) como Driver de áudio ALSA pode ajudar.

Microfone não funciona após atualização

Houve problemas relatados em torno da entrada de som nas versões 5.1.x. Ticket #16191

Fazendo downgrade pode resolver o problema. Você pode usar virtualbox-bin-5.0AUR para facilitar o downgrade.

Problemas com imagens convertidas para ISO

Alguns formatos de imagem não podem ser convertidos de forma confiável para ISO. Por exemplo, ccd2iso ignora arquivos .ccd e .sub, que podem resultar em imagens de disco com arquivos quebrados.

Neste caso, você terá que usar o CDemu para Linux dentro do VirtualBox ou qualquer outro utilitário usado para montar imagens de disco.

Falha ao criar a interface de rede interna

Certifique-se de que todos os módulos do kernel necessários estejam carregados. Veja #Carregar os módulos de kernel do VirtualBox.

Se todos os módulos do kernel necessários forem carregados e você ainda não conseguir criar o adaptador somente para hospedeiro, navegue até Arquivo > Gerenciar rede do hospedeiro e clique no botão Criar para adicionar a interface de rede.

Falha ao inserir módulo

Quando você obtiver o seguinte erro ao tentar carregar módulos:

Failed to insert 'vboxdrv': Required key not available

Assine seus módulos ou desative CONFIG_MODULE_SIG_FORCE na configuração do seu kernel.

VBOX_E_INVALID_OBJECT_STATE (0x80BB0007)

Isso pode ocorrer se uma VM for encerrada de modo inadequado. Execute o seguinte comando:

$ VBoxManage controlvm nome_da_máquina_virtual poweroff

NS_ERROR_FAILURE e itens de menu em falta

Isso acontece algumas vezes ao selecionar o formato de disco QCOW/QCOW2/QED ao criar um novo disco virtual.

Se você encontrar essa mensagem na primeira vez que iniciar a máquina virtual:

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

Saia do VirtualBox, exclua todos os arquivos da nova máquina e, do arquivo de configuração do virtualbox, remova a última linha do menu MachineRegistry (ou a máquina incorreta que você está criando):

~/.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 inutilizável quando instruções de virtualização estão indisponíveis

Embora o OpenBSD funcione bem em outros hipervisores sem as instruções de virtualização (VT-x AMD-V) ativadas, uma máquina virtual OpenBSD funcionando no VirtualBox sem essas instruções será inutilizável, manifestando-se com um monte de falhas de segmentação. Iniciar o VirtualBox com o argumento -norawr0 pode resolver o problema. Você pode fazer assim:

$ VBoxSDL -norawr0 -vm nome_da_VM_OpenBSD

Windows: "O caminho especificado não existe. Verifique o caminho e tente novamente."

Essa mensagem de erro pode aparecer ao executar um arquivo .exe que requer privilégios de administrador de uma pasta compartilhada em convidados do windows. [6]

Como solução alternativa, copie o arquivo para a unidade virtual ou use caminhos UNC (\\vboxsvr). Consulte [7] para obter mais informações.

Erro no Windows 8.x com código 0x000000C4

Se você receber este código de erro durante a inicialização, mesmo que você escolha o tipo de sistema operacional Windows 8, tente habilitar a instrução da CPU CMPXCHG16B:

$ vboxmanage setextradata nome_da_máquina_virtual VBoxInternal/CPUM/CMPXCHG16B 1

Windows 8, 8.1 ou 10 falha em instalar, inicializar ou tem erro "ERR_DISK_FULL"

Atualize as configurações da VM indo em Configurações > Armazenamento > Controladora: SATA e marque a opção Utilizar cache de I/O do hospedeiro.

WinXP: Profundidade de bits não pode ser maior que 16

Se você estiver executando em profundidade de cor de 16 bits, os ícones podem aparecer difusos/instáveis. No entanto, ao tentar alterar a profundidade de cor para um nível mais alto, o sistema pode restringi-lo a uma resolução mais baixa ou simplesmente não permitir que você altere a profundidade. Para corrigir isso, execute regedit no Windows e adicione a seguinte chave ao registro da VM do Windows XP:

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

Em seguida, atualize a profundidade de cor na janela "propriedades da área de trabalho". Se nada acontecer, force a tela a redesenhar através de algum método (por exemplo, Host+f para redesenhar/entrar em tela cheia).

Windows: Oscilação da tela se a aceleração 3D estiver ativada

VirtualBox > 4.3.14 traz um problema em que os convidados Windows com aceleração 3D ficam oscilando. Desde que o r120678 foi implementado um patch para reconhecer uma configuração de variável de ambiente, abra o VirtualBox assim:

$ CR_RENDER_FORCE_PRESENT_MAIN_THREAD=0 VirtualBox

Certifique-se de que nenhum serviço do VirtualBox ainda esteja em execução. Consulta o bug 13653 do VirtualBox.

Não é possível iniciar o VirtualBox com Wayland: Falha de segmentação

Este problema é causado pelo Qt detectando Wayland (p.ex., se XDG_SESSION_TYPE=wayland), mas o VirtualBox não funciona no Wayland ainda. Veja FS#58761 e o relatório de erro do upstream.

A detecção da plataforma Qt pode ser desativada e o X11 forçado sobre Wayland configurando a variável de ambiente QT_QPA_PLATFORM=xcb. Para não afetar os outros aplicativos Qt (que geralmente funcionam bem com Wayland), QT_QPA_PLATFORM=xcb deve ser definido apenas ao iniciar o VirtualBox.

Se estiver iniciando pela entrada de desktop, siga as instruções em Entradas de desktop#Modificar variáveis de ambiente e altere as linhas começando com Exec=VirtualBox ... para Exec=env QT_QPA_PLATFORM=xcb VirtualBox .... Se estiver iniciando no shell, alias (Bash#Aliases]) virtualbox para env QT_QPA_PLATFORM=xcb virtualbox.

Congelamento aleatório em convidados com placa de vídeo da intel

Com cpu e placa de vídeo da Intel, alocar mais processadores para o convidado pode baixar o desempenho da renderização, causando congelamentos aleatórios. Alocar menos ou apenas um processador por ajudar.

Veja também