学写操作系统(一) -- 第一个“操作系统”

时间:2021-05-27 15:44:09

一直想动手写一个操作系统,借此来深化多线程、并发等知识的理解,后来看到市面上有一本叫《一个操作系统的实现》,决定跟着别人的脚印来学习。

废话少说,首先介绍需要用到的环境

1.windows xp

2.nasm

3.bochs虚拟机

4.dd for windows

下面贴上第一段“操作系统”代码,这里是边学边写,很多地方我也是不懂的学写操作系统(一) -- 第一个“操作系统”

文件保存为boot.asm

org07c00h; 告诉编译器程序加载到7c00处
movax, cs
movds, ax
moves, ax
callDispStr; 调用显示字符串例程
jmp$; 无限循环
DispStr:
movax, BootMessage
movbp, ax; ES:BP = 串地址
movcx, 16; CX = 串长度
movax, 01301h; AH = 13, AL = 01h
movbx, 000ch; 页号为0(BH = 0) 黑底红字(BL = 0Ch,高亮)
movdl, 0
int10h; 10h 号中断
ret
BootMessage:db"Hello, OS world!"
times 510-($-$$)db0; 填充剩下的空间,使生成的二进制代码恰好为512字节
dw 0xaa55; 结束标志

然后是编译上面的汇编代码,得到boot.bin二进制文件

nasm boot.asm -o boot.bin

最后把上面的二进制文件写到虚拟软盘里面(给后面的虚拟机使用)

首先用bochs自带的bximg工具新建一个虚拟软盘:

学写操作系统(一) -- 第一个“操作系统”


接下来把二进制文件boot.bin写入磁盘镜像(a.img):

dd if=boot.bin of=a.img bs=512 conv=ontrunc

最后就是把你的镜像塞进虚拟机里面里了

首先修改一下bochs根目录的dlxlinux目录下的bochsrc配置文件

###############################################################
# bochsrc.txt file for DLX Linux disk image.
###############################################################

# how much memory the emulated machine will have
megs: 32

# filename of ROM images
romimage: file=../BIOS-bochs-latest
vgaromimage: file=../VGABIOS-lgpl-latest

# what disk images will be used
floppya: 1_44=a.img, status=inserted
#floppyb: 1_44=floppyb.img, status=inserted

# hard disk
ata0: enabled=1, ioaddr1=0x1f0, ioaddr2=0x3f0, irq=14
ata0-master: type=disk, path="hd10meg.img", cylinders=306, heads=4, spt=17

# choose the boot disk.
boot: floppy

# default config interface is textconfig.
#config_interface: textconfig
#config_interface: wx

#display_library: x
# other choices: win32 sdl wx carbon amigaos beos macintosh nogui rfb term svga

# where do we send log messages?
log: bochsout.txt

# disable the mouse, since DLX is text only
mouse: enabled=0

# enable key mapping, using US layout as default.
#
# NOTE: In Bochs 1.4, keyboard mapping is only 100% implemented on X windows.
# However, the key mapping tables are used in the paste function, so
# in the DLX Linux example I'm enabling keyboard mapping so that paste
# will work. Cut&Paste is currently implemented on win32 and X windows only.

#keyboard: keymap=$BXSHARE/keymaps/x11-pc-us.map
#keyboard: keymap=$BXSHARE/keymaps/x11-pc-fr.map
#keyboard: keymap=$BXSHARE/keymaps/x11-pc-de.map
#keyboard: keymap=$BXSHARE/keymaps/x11-pc-es.map

最后启动我们的虚拟机,可以看到有一个Hello world在左上角~!

学写操作系统(一) -- 第一个“操作系统”