Write Your Own OS (I) - Create a bootable hard disk image

Dec 2, 2008 10:21 PM posted by Wei Hu  [updated Dec 3, 2008 2:57 AM]
Note1: The steps described here are slightly more complex than creating a floppy image, because we need to worry about partitioning the hard disk with fdisk.

Note2: Here we build a disk image from scratch. We can also use bochs' bximage tool to create one.

# bytes per sector
bytes=512
# sectors per track
sectors=63
# heads per track
heads=16
# bytes per cylinder is bytes*sectors*head
bpc=$(( bytes*sectors*heads ))
# number of cylinders
# A image of $size MB
size=5
cylinders=$(( ($size*1024*1024) / $bpc ))

# Path to disk image
image="/opt/writeos/hd.img"
# Path to location to mount image
mount="/mnt/os"

# Create raw disk image
dd if=/dev/zero of=$image bs=$bpc count=$cylinders

# Attach image as raw device and partition it
# losetup -a lists all the loop devices used.
losetup /dev/loop0 $image
fdisk -u -C$cylinders -S$sectors -H$heads /dev/loop0
# Create a partition
# With commands like these;
# n p 1 <return> <return> a 1 p w

# Suppose you chose the default value for the start of the partition, i.e. Cylinder 1
# MBR resides in sector 0, this leaves sectors 1 through 62 unused.
start=63

# Detach the disk, and mount the specific partition
losetup -d /dev/loop0
offset=$(( start*bytes ))
losetup -o$offset /dev/loop0 $image

# Format the partition, reserving 0 blocks for root
mkfs.ext3 -m 0 /dev/loop0

# Mount the partition
mount /dev/loop0 $mount

# Unmount the partition
umount /dev/loop0
losetup -d /dev/loop0

#
# Installing GRUB into the raw disk image
#

# Easy mounting
mount -oloop=/dev/loop0,offset=$offset $image $mount

# Copy across needed grub images
cd $mount
mkdir -p boot/grub
cd /boot/grub
cp stage1 stage2 e2fs_stage1_5 $mount/boot/grub
umount -d $mount

# Install grub
losetup /dev/loop0 $image
grub --batch --device-map=/dev/null <<EOF
device (hd0) /dev/loop0
root (hd0,0)
setup (hd0)
quit
EOF

# Finally, try it out with bochs

bochsrc

config_interface: wx
display_library: wx
romimage: file=/usr/share/bochs/BIOS-bochs-latest
megs: 32
vgaromimage: file=/usr/share/vgabios/vgabios.bin
ata0: enabled=1
ata0-master: type=disk, path="hd.img", mode=flat, cylinders=10, heads=16, spt=63
ata1: enabled=0
boot: disk
#gdbstub: enabled=1, port=1234, text_base=0, data_base=0, bss_base=0
#keyboard_mapping: enabled=1, map=/usr/share/bochs/keymaps/x11-pc-us.map
info: action=ignore
log: /dev/stdout

# Grub successfully boots and shows a shell. We can copy the host's menu.lst and kernel image to test that grub can boot the kernel.

Attachments (0)

Attach a file:

Comments (0)

  Home   Sitemap   Recent site activity   Terms   Report Abuse   Print  |  Powered by Google Sites