汇编实现启动扇区02

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zllvincent/article/details/83270444

前言

软盘的启动扇区头512字的内容是需要使用汇编实现,内核加载器需要把操作系统加载进内存,实现加载完成后就可使用C语言编写操作系统。

目标

1.使用汇编实现hello,world 的输出

文件名:boot.s

;能用于操作内存的寄存器只能是bx、bp、si、di
;0x7c00--0x7dff 这512字节用于启动区
;对内存的访问都必须指定段寄存器,没有显示指定时将使用ds作为段寄存器

org 0x7c00;

mov ax,0
mov ss,ax
mov ds,ax
mov es,ax
mov si,msg

putloop:
mov al,[si]
add si,1
cmp al,0
je fin
mov ah,0x0e     ;中断调用参数
mov bx,15       ;字符颜色
int 0x10        ;中断调用号
jmp putloop

fin:
hlt
jmp fin


msg:
db 0x0a,0x0a
db "hello world"
db  0x0a
db 0

nasm 汇编器(如果没有nasm汇编器,可参看https://blog.csdn.net/Zllvincent/article/details/83269154)编译boot.s 文件,终端运行 nasm boot.s -o boot.bat

2.使用gcc 编译os.c文件

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


void makeFloppy(char *fname){
    char img[512];
    FILE *fp = fopen(fname,"r");
    if(fp==NULL){
        printf("fopen error\n");
        exit(1);
    }
    fread(img,512,1,fp);
    img[510] = 0x55;
    img[511] = 0xaa;
    
    FILE *out = fopen("system.img","w");
    if(out==NULL){
        printf("fopen error\n");
        exit(1);
    }
    for(int i=0;i<2*80*18;i++){
        fwrite(img,512,1,out);
        memset(img,0,512);
    }
    fclose(fp);
    fclose(out);
    printf("---------success\n");
    
}


int main(int argc,char **argv){
    makeFloppy("boot.bat");
    return 1;
}

终端运行: gcc os.c

3.终端运行:./a.out ,生成system.img文件如下图:
在这里插入图片描述

使用虚拟机加载system.img文件
在这里插入图片描述

至此,我们的汇编编写的头512字节输出hello world 成功完成,是不是很简单?

总结

软盘还是文件,保存的都是2进制数据,2者可以完全等效。我们使用C语言实现的功能就是把汇编编译生成的机器码使用C语言写入文件,制作成虚拟软盘。

猜你喜欢

转载自blog.csdn.net/Zllvincent/article/details/83270444