俺啥也不懂-不知道什么时候才会编写操作系统-一个hello world写一年-为什么能输出hello world
有时候想啊,自己要是写一个操作系统也不赖,看着网上那些讲解都太糙了,不适合我这种啥都不懂的人,如果给我来写,一个hello world能写一年
先贴一个hello world的代码
org 07c00h ; 告诉编译器程序加载到7c00处
mov ax, cs
mov ds, ax
mov es, ax
call DispStr ; 调用显示字符串例程
jmp $ ; 无限循环
DispStr:
mov ax, msg
mov bp, ax ; ES:BP = 串地址
mov cx, 16 ; CX = 串长度
mov ax, 01301h ; AH = 13, AL = 01h
mov bx, 000ch ; 页号为0(BH = 0) 黑底红字(BL = 0Ch,高亮)
mov dl, 1
int 10h ; 10h 号中断
ret
msg: db "Hello, OS world!"
times 510-($-$$) db 0 ; 填充剩下的空间,使生成的二进制代码恰好为512字节
dw 0xaa55 ; 结束标志
按照我的习惯,遇到这个代码,第一个反应是写个makefile
outputFilePath=/usr/local/myAll/output/os/
boot.img:boot.bin
dd conv=sync if=$(outputFilePath)$< of=$(outputFilePath)$@ bs=1440k count=1
boot.bin:boot.asm
nasm $< -o $(outputFilePath)$@
clean:
rm -rf $(outputFilePath)*.bin $(outputFilePath)*.img
话说,为啥俺一直说要写makefile,因为现在文件结构还简单,先写着,慢慢的复杂度越来越高,慢慢的就看懂更复杂的makefile了。
这个makefile翻译过来就两句,参考如下
[root@localhost day1]# ls
boot.asm makefile
[root@localhost day1]# nasm boot.asm -o boot.bin
[root@localhost day1]# dd conv=sync if=boot.bin of=boot.img bs=1440k count=1
0+1 records in
1+0 records out
1474560 bytes (1.5 MB) copied, 0.00139761 s, 1.1 GB/s
[root@localhost day1]# ls
boot.asm boot.bin boot.img makefile
[root@localhost day1]#
最终是为了生成一个img文件,img文件如何使用不讲,反正虚拟机能出结果。
这个最终运行的结果是黑底红字的hello world,各位,看过俺前面文章的都应该知道,这时候咱们应该研究啥了,第二个反应是,研究int 10h中断,这个下次讲
我一开始不大明白,虽然知道这个img是镜像文件,但是它和bin文件究竟是什么关系,一直没搞明白,直到有一天看了一篇文章用cat命令把bin文件写入img才知道,嗯,原来是这样的,忘了存作者的地址,不替作者宣传。
那么我们可以提前生成一个boot.img文件,代码如下:
[root@localhost day1]# ls
boot.asm makefile
[root@localhost day1]# dd conv=sync if=/dev/null of=boot.img bs=1440k
0+0 records in
0+0 records out
0 bytes (0 B) copied, 0.000214884 s, 0.0 kB/s
[root@localhost day1]# ls
boot.asm boot.img makefile
[root@localhost day1]# nasm boot.asm -o boot.bin
[root@localhost day1]# cat boot.bin > boot.img
效果自然相同
其它的先不讲,先说这里的mov cx,16,16是字符串的长度,俺试着将它该小,那最终界面显示的字符串就少了几位。
在https://asmtutor.com/上有如何计算字符串的长度,俺试了一下,靠谱,大家可以自己试一下,我是会写的,毕竟hello world还要写好久。