从0创建一个OS (二) boot_sector的“裸骨架“

本节将学习如何创建一个能够boot的文件

关键字: assembler; BIOS

目标: 创建一个文件,使BIOS能够将其当作能够boot的硬盘

理论基础

当PC启动时,BIOS并不知道如何启动操作系统,所以BIOS将启动操作系统的任务委派给boot sector,因此boot sector必须放置到一个大家都知道的地方,人们约定,这个地方,应该在硬盘的第一个存储空间中(cylinder 0, head 0, sector 0),该存储空间占用512个字节.

同时,为了确认硬盘是否能够启动(boot) OS, 人们制定标准,boot sector 的第511和第512个字节应该为0xAA55,如以下示例:

e9 fd ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 16×29行00 ] 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 aa

注意大小端,x86是小端机制,大端情况下,上面标红的数据应该为AA 55

源码

详情见代码中的注释.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<code-pre class="code-pre" id="pre-zRRkme"><code-line class="line-numbers-rows"></code-line>; ========================================
<code-line class="line-numbers-rows"></code-line>; 文件名: boot_sect_simple.asm
<code-line class="line-numbers-rows"></code-line>; 该程序对硬盘的第一个分区进行写入,总计512个字节
<code-line class="line-numbers-rows"></code-line>; 其中第511,512个字节必须为0xAA55
<code-line class="line-numbers-rows"></code-line>; 剩余的510个字节自定义,作为boot功能,用来启动os
<code-line class="line-numbers-rows"></code-line>; ========================================
<code-line class="line-numbers-rows"></code-line>
<code-line class="line-numbers-rows"></code-line>; 无限循环
<code-line class="line-numbers-rows"></code-line>loop:
<code-line class="line-numbers-rows"></code-line>    jmp loop
<code-line class="line-numbers-rows"></code-line>; 以0填充除上面两行、结尾的0xAA55之外的部分
<code-line class="line-numbers-rows"></code-line>; $ 表示本行代码的偏移量(offset) $$ 代表本段的地址(segment)
<code-line class="line-numbers-rows"></code-line>times 510 - ($ - $$) db 0
<code-line class="line-numbers-rows"></code-line>dw 0xAA55
</code-pre>

  

编译

使用工具nasm进行编译,进入你存放源码的文件夹中,使用以下命令

1
2
<code-pre class="code-pre" id="pre-AbPHPk"><code-line class="line-numbers-rows"></code-line># -f 设置编译输出的文件格式 -o 设置编译输出的文件名
<code-line class="line-numbers-rows"></code-line>nasm -f bin -o boot_sect_simple.bin boot_sect_simple.asm</code-pre>

编译完成后可以看到你存放源码的文件夹中多了一个名为boot_sect_simple.bin的文件.

Boot

使用qemu可以从刚才生成的文件中启动,使用以下命令

1
<code-pre class="code-pre" id="pre-MXJK5G"><code-line class="line-numbers-rows"></code-line>qemu-system-x86_64 boot_sect_simple.bin</code-pre>

结果

在这里插入图片描述

 

__EOF__

本文作者EwanHai
本文链接https://www.cnblogs.com/haiyonghao/p/14623206.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   EwanHai  阅读(187)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示