使用GRUB Multiboot2引導自制作業系統

千松發表於2024-10-08

使用GRUB Multiboot2引導自制作業系統

前言

之前花了一週時間,從頭學習了傳統 BIOS 的啟動流程。驚訝於背後豐富的技術細節的同時,也感嘆 x86 架構那厚重的歷史包袱。畢竟,誰能想到,一個現代 CPU 竟然需要透過操作“鍵盤控制器暫存器”來啟用一條地址線呢。

最終,出於相容性和功能性的考慮,我還是決定投入 GRUB 的懷抱。況且,讓自己寫的作業系統和本機的 Linux 一同出現在 GRUB 選單中併成功引導啟動,也是一件非常有成就感的事。

完整程式碼在附錄部分

開發環境

專案 版本
系統 Windows Subsystem for Linux - Arch (2.3.24)
編譯器 gcc version 14.2.1 20240910 (GCC)
載入程式 grub-install (GRUB) 2:2.12-3
虛擬機器 QEMU emulator version 9.1.50 / VirtualBox 7.0.6

1 Multiboot2 規範

想讓 GRUB 識別並引導我們自制的作業系統,就得先了解 Multiboot2 規範。

官方文件:Multiboot2 Specification version 2.0

1.1 Multiboot2 header

An OS image must contain an additional header called Multiboot2 header, besides the headers of the format used by the OS image. The Multiboot2 header must be contained completely within the first 32768 bytes of the OS image, and must be 64-bit aligned. In general, it should come as early as possible, and may be embedded in the beginning of the text segment after the real executable header.

這段話的大致意思是:

在 Multiboot2 規範中,作業系統映象的前 32768 位元組內,必須包含一個名為 Multiboot2 header 的資料結構,並且起始地址必須 64-bit 對齊。

Multiboot2 header 的具體結構如下:

Offset Type Field Name
0 u32 magic
4 u32 architecture
8 u32 header_length
12 u32 checksum
16-XX tags

1.1.1 Magic fields

Multiboot2 header 的前四個欄位,也就是0~15位元組的內容,被稱為 magic fields

magic 欄位是 Multiboot2 header 的識別標誌,它必須是十六進位制值 0xE85250D6

architecture 欄位指定 CPU 的架構。0 表示 i386 的 32 位保護模式,4 表示 32 位 MIPS 架構

header_length 欄位記錄了 Multiboot2 header 的長度(以位元組為單位)

checksum 欄位是一個 32 位無符號數,當它與 magic fields 其他欄位(即 magicarchitectureheader_length )相加時,其 32 位無符號和必須為零。

1.1.2 Tags

Tags 由一個接一個的 tag 結構體組成,在必要時進行填充,以確保每個 tag 都從 8 位元組對齊的地址開始。Tags 以一個 type = 0 且 size = 8 的 tag 作為結束標誌(相當於字串結尾的'\0')。

值得注意的是,官方文件給出的 boot.S 程式碼並 沒有 給 tag 的地址進行 8 位元組對齊。這會導致 GRUB 讀取 tag 時出現錯位,出現各種奇怪的錯誤(比如 error: unsupported tag: xxx)

每個 tag 都有如下基本結構:

        +-------------------+
u16     | type              |
u16     | flags             |
u32     | size              |
        +-------------------+

type 用於表示 tag 的型別,因為不同的 tag 在 size 之後可能還會有其他資料欄位。

如果flags 的第 0 位(也稱為 optional)為 1,表示如果引導載入程式缺乏相關支援,它可以忽略這個 tag。

size 表示整個 tag 的長度。

例如,表示程式入口地址的 entry address tag 結構如下:

        +-------------------+
u16     | type = 3          |
u16     | flags             |
u32     | size              |
u32     | entry_addr        |
        +-------------------+

GRUB 會根據 type = 3 判斷它是 entry address tag,並在準備工作完成後,跳轉到 entry_addr 欄位中的地址執行作業系統。

除此之外,還有專門在 EFI 引導使用的 EFI i386 entry address tag

        +-------------------+
u16     | type = 8          |
u16     | flags             |
u32     | size              |
u32     | entry_addr        |
        +-------------------+

其結構與 entry address tag 相同,只是 type = 8 。既然都是指定程式入口,那麼二者同時存在時會發生什麼呢?

在使用 EFI 引導的情況下,entry address tag 將被忽略,引導載入程式會跳轉到 EFI i386 entry address tag 提供的地址。

而使用傳統 BIOS 引導時,引導載入程式會直接報錯 error: unsupported tag: 0x08 。這是因為傳統引導方式不支援 EFI 相關的 tag ,此時 flags 就派上用場了。只要把 flags 最低位設為 1 ,就可以讓載入程式在不相容時忽略這個 tag,而在 EFI 引導時又能正常使用它。

如此一來,我們的啟動程式就能夠相容多種啟動方式。

除此之外的 tag 型別,可以在 Multiboot2 Specification version 2.0 的 3.1.3 ~ 3.1.13 節找到詳細說明。

1.2 機器狀態

官方文件中的 3.3 I386 machine state 說明了引導載入程式呼叫 32 位作業系統時的機器狀態。

除了開啟保護模式和啟用 A20 gate 這些常規操作以外,還有兩條比較重要的內容:

  1. EAX 必須包含標識值 0x36d76289,該值的存在向作業系統表明它是由相容 Multiboot2 的引導載入程式載入的。
  2. EBX 必須包含引導載入程式提供的 Multiboot2 資訊結構體的 32 位實體地址(請參閱 Boot information format)。

這兩個暫存器中的資料,會在後續核心程式碼中用到。

2 程式碼實現

官方文件提供了對應的示例程式碼:4.4 Example OS code

但是!

前文有提過,文件給出的 boot.S 是有 BUG 的!因為 沒有 給 tag 的地址進行 8 位元組對齊,導致了 GRUB 讀取 tag 會出現錯位。

我將完整的程式碼放在了附錄部分。 本章節主要內容是依據 Multiboot2 規範,對程式碼片段進行分析。

2.1 定義 Multiboot header

#include "multiboot2.h"

        .text
        
multiboot_header:
        /*  Align 64 bits boundary. */
        .align  8
        /*  magic */
        .long   MULTIBOOT2_HEADER_MAGIC
        /*  ISA: i386 */
        .long   MULTIBOOT_ARCHITECTURE_I386
        /*  Header length. */
        .long   multiboot_header_end - multiboot_header
        /*  checksum */
        .long   -(MULTIBOOT2_HEADER_MAGIC + MULTIBOOT_ARCHITECTURE_I386 + (multiboot_header_end - multiboot_header))

entry_address_tag_start:    
        /* 每個 tag 都要 8 位元組對齊 */
        .align  8
        .short MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS
        .short MULTIBOOT_HEADER_TAG_OPTIONAL
        .long entry_address_tag_end - entry_address_tag_start
        /*  entry_addr */
        .long multiboot_entry
entry_address_tag_end:

        /* 終止 tag 表示 tags 部分結束 */
end_tag_start:
        /* 每個 tag 都要 8 位元組對齊 */
        .align  8
        .short MULTIBOOT_HEADER_TAG_END
        .short 0
        .long end_tag_end - end_tag_start
end_tag_end:
multiboot_header_end:

multiboot_entry:
        /* ...... */

為了程式碼的可讀性,使用宏定義來表示數值。具體內容參考: multiboot2.h

根據規範要求,我們將 Multiboot header 定義在了 text 段的開頭,使資料儘量靠前。

這裡使用了 entry address tag 表示程式入口的地址,也就是 GRUB 執行核心時要跳轉的目標。不過,其實還有一個方法可以設定程式入口。

#include "multiboot2.h"

        .text

        jmp     multiboot_entry
        
multiboot_header:
        /*  Align 64 bits boundary. */
        .align  8
        /*  magic */
        .long   MULTIBOOT2_HEADER_MAGIC
        /*  ISA: i386 */
        .long   MULTIBOOT_ARCHITECTURE_I386
        /*  Header length. */
        .long   multiboot_header_end - multiboot_header
        /*  checksum */
        .long   -(MULTIBOOT2_HEADER_MAGIC + MULTIBOOT_ARCHITECTURE_I386 + (multiboot_header_end - multiboot_header))

        /* 終止 tag 表示 tags 部分結束 */
end_tag_start:
        /* 每個 tag 都要 8 位元組對齊 */
        .align  8
        .short MULTIBOOT_HEADER_TAG_END
        .short 0
        .long end_tag_end - end_tag_start
end_tag_end:
multiboot_header_end:

multiboot_entry:
        /* ...... */

相較於上一個程式碼,我們在 text 段的開頭新增 jmp multiboot_entry ,並刪除 entry address tag ,也能實現相同的功能。

這是因為,在沒有使用 tag 指定程式入口時, GRUB 會直接執行我們的作業系統程式。此時,執行的第一條指令就是我們新增的 jmp multiboot_entry

2.2 啟動入口

#include "multiboot2.h"

#ifdef HAVE_ASM_USCORE
# define EXT_C(sym)                     _ ## sym
#else
# define EXT_C(sym)                     sym
#endif

#define STACK_SIZE                      0x4000
        
        .text
        
multiboot_header:
        /* ...... */
multiboot_header_end:

        /* 程式入口位置 */
multiboot_entry:
        /*  Initialize the stack pointer. */
        movl    $(stack + STACK_SIZE), %esp

        /*  Reset EFLAGS. */
        pushl   $0
        popf

        /*  Push the pointer to the Multiboot information structure. */
        pushl   %ebx
        /*  Push the magic value. */
        pushl   %eax

        /*  Now enter the C main function... */
        call    EXT_C(cmain)

        /*  Halt. */
        pushl   $halt_message
        call    EXT_C(printf)
        
loop:   hlt
        jmp     loop

halt_message:
        .asciz  "Halted."

        /*  Our stack area. */
        .comm   stack, STACK_SIZE

接下來,到了作業系統入口位置。

首先,需要做的事情是初始化棧指標:

  1. #define STACK_SIZE 0x4000:用宏定義表示棧的大小
  2. .comm stack, STACK_SIZE.comm 指令用來分配一塊未初始化的資料段記憶體,這裡分配了 STACK_SIZE 位元組的空間給 stack
  3. movl $(stack + STACK_SIZE), %esp:因為棧從頂部向下生長,所以將棧的頂部地址放入棧指標暫存器 %esp

接著清空 EFLAGS 暫存器:

  1. pushl $0:將立即數 0 壓入棧
  2. popf:將棧頂的值彈出,並載入到 EFLAGS 暫存器

初始化完成後,就可以呼叫核心入口的 C 語言函式。我們之前在 1.2 機器狀態中提到過, EAXEBX 暫存器儲存著標識值和 Multiboot2 資訊結構體地址,接下來核心會用到這些資料。由於核心程式碼是 C 函式,因此我們需要根據 C 語言的傳參標準,按函式引數相反的順序將資料壓入棧中:

/* 核心入口函式定義: */
/* void cmain (unsigned long magic, unsigned long addr) */

pushl   %ebx
pushl   %eax

call    EXT_C(cmain)

2.3 核心程式碼

這部分的程式碼和官方文件中的 kernel.c 一致。該核心的主要功能是在螢幕上列印出 Multiboot2 資訊結構,主要用於測試 Multiboot2 引導載入程式,同時也可作為實現 Multiboot2 核心的參考示例。

2.4 程式碼構建

需要先在附錄中獲取 boot.S, kernel.cmultiboot2.h 程式碼

CC = gcc
LD = ld
CFLAGS = -m32 -fno-builtin -fno-stack-protector -nostartfiles
LDFLAGS = -Ttext 0x100000 -melf_i386 -nostdlib
KERNEL_NAME = kernel.bin

all: $(KERNEL_NAME)

$(KERNEL_NAME): boot.o kernel.o
	$(LD) $(LDFLAGS) $^ -o $@

boot.o: boot.S
	$(CC) -c $(CFLAGS) $< -o $@

kernel.o: kernel.c
	$(CC) -c $(CFLAGS) $< -o $@

clean:
	rm -f *.o $(KERNEL_NAME)

簡單說明一下編譯選項:

CFLAGS = -m32 -fno-builtin -fno-stack-protector -nostartfiles
  • -m32:讓編譯器生成 32 位程式碼
  • -fno-builtin:禁用編譯器對標準庫函式(如 memcpy、strlen 等)的內建最佳化實現。確保這些函式不被替換為編譯器最佳化版本
  • -fno-stack-protector:禁用棧保護功能,否則會編譯報錯
  • -nostartfiles:不使用標準啟動檔案,因為作業系統的啟動方式與常規程式不同
LDFLAGS = -Ttext 0x100000 -melf_i386 -nostdlib

這些是傳遞給連結器(如 ld)的選項,用於控制連結行為:

  • -Ttext 0x100000:表示程式的程式碼段(text segment)將被放置在記憶體地址 0x100000 處,這是載入作業系統常用的位置
  • -melf_i386:指定輸出檔案的目標格式是 32 位的 ELF 格式(適用於 i386 架構),這是 Multiboot2 規範建議的格式
  • -nostdlib:讓連結器不要連結標準庫。這是必要的,因為在核心或載入程式中,不會使用標準 C 庫,而是會自己實現所需的功能或直接操作硬體

3 映象製作

總所周知,現代 PC 有 LegacyUEFI 兩種啟動方式,而接下來的映象將會使用 Legacy + MBR 的啟動方式。

選擇 Legacy 的主要原因是,EFI 似乎只能輸出畫素,無法直接列印文字。這會導致我們無法檢視核心列印的資訊。

具體說法可以參考這個連結:https://forum.osdev.org/viewtopic.php?f=1&t=28429

3.1 建立映象

使用 dd 命令建立一個 64M 的檔案:

dd if=/dev/zero of=disk.img bs=1M count=64

使用 parted 為映象檔案分割槽:

parted -s disk.img mklabel msdos mkpart primary ext2 1MiB 100%

將映象檔案作為虛擬磁碟掛載,並建立 ext2 檔案系統和掛載分割槽

sudo losetup -P /dev/loop0 disk.img
sudo mkfs.ext2 /dev/loop0p1
sudo mount /dev/loop0p1 /mnt

3.2 安裝 GRUB

安裝 Legacy 啟動相容的 GRUB ,並建立 grub.cfg 配置檔案

sudo grub-install --target=i386-pc --boot-directory=/mnt/boot /dev/loop0

sudo mkdir -p /mnt/boot/grub
cat <<EOF > /mnt/boot/grub/grub.cfg
set timeout=20
set default=0

menuentry "MyOS" {
    multiboot2 /boot/kernel.bin
    boot
}
EOF

配置檔案裡的啟動方式要寫 multiboot2 而不是 multiboot

安裝完成後,取消掛載

sudo umount /mnt
sudo losetup -d /dev/loop0

4 虛擬機器執行

4.1 QEMU

執行目標平臺為 i386 的 QEMU,記憶體要大於 128 M

qemu-system-i386 -m 1G -hda disk.img

img

img

這條藍線也是 kernel.c 繪製的。如果你的機器和 GRUB 是 EFI 啟動,就會發現無法輸出字元,但是這個藍線還在。因為,它是透過設定 framebuffer 畫素實現的。

4.2 VirtualBox

在 VirtualBox 中執行需要先將映象檔案轉換為 vdi 格式

VBoxManage convertdd disk.img disk.vdi --format VDI

接著註冊硬碟,並新增到虛擬機器的 IDE 控制器中

img

img

在設定中關閉 EFI

img

這樣就可以正常啟動了

img

附錄:完整程式碼

write_grub_cfg.sh

別忘了加上可執行許可權 chmod +x write_grub_cfg.sh

#!/bin/bash

KERNEL_NAME=$1
GRUB_CFG_PATH=$2

cat <<EOF > $GRUB_CFG_PATH
set timeout=20
set default=0

menuentry "MyOS" {
    multiboot2 /boot/$KERNEL_NAME
    boot
}
EOF

Makefile

CC = gcc
LD = ld
CFLAGS = -m32 -fno-builtin -fno-stack-protector -nostartfiles
LDFLAGS = -Ttext 0x100000 -melf_i386 -nostdlib
KERNEL_NAME = kernel.bin
IMG_NAME = disk.img
IMG_SIZE = 64

all: img

$(KERNEL_NAME): boot.o kernel.o
	$(LD) $(LDFLAGS) $^ -o $@

boot.o: boot.S
	$(CC) -c $(CFLAGS) $< -o $@

kernel.o: kernel.c
	$(CC) -c $(CFLAGS) $< -o $@

.PHONY: img
img: $(IMG_NAME) $(KERNEL_NAME)
	sudo losetup -P /dev/loop0 $(IMG_NAME)
	sudo mount /dev/loop0p1 /mnt
	sudo ./write_grub_cfg.sh $(KERNEL_NAME) /mnt/boot/grub/grub.cfg
	sudo cp $(KERNEL_NAME) /mnt/boot/
	sudo umount /mnt
	sudo losetup -d /dev/loop0


$(IMG_NAME):
	dd if=/dev/zero of=$(IMG_NAME) bs=1M count=$(IMG_SIZE)
	parted -s $(IMG_NAME) mklabel msdos mkpart primary ext2 1MiB 100%
	sudo losetup -P /dev/loop0 $(IMG_NAME)
	sudo mkfs.ext2 /dev/loop0p1
	sudo mount /dev/loop0p1 /mnt
	sudo grub-install --target=i386-pc --boot-directory=/mnt/boot /dev/loop0
	sudo mkdir -p /mnt/boot/grub
	sudo umount /mnt
	sudo losetup -d /dev/loop0

qemu: img
	qemu-system-i386 -m 1G -hda $(IMG_NAME)

clean:
	sudo umount /mnt || true
	sudo losetup -d /dev/loop0 || true
	rm -f *.o $(KERNEL_NAME) $(IMG_NAME)

boot.S

/*  boot.S - bootstrap the kernel */
/*  Copyright (C) 1999, 2001, 2010  Free Software Foundation, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#define ASM_FILE        1
#include "multiboot2.h"

/*  C symbol format. HAVE_ASM_USCORE is defined by configure. */
#ifdef HAVE_ASM_USCORE
# define EXT_C(sym)                     _ ## sym
#else
# define EXT_C(sym)                     sym
#endif

/*  The size of our stack (16KB). */
#define STACK_SIZE                      0x4000
        
        .text
        
multiboot_header:
        /*  Align 64 bits boundary. */
        .align  8
        /*  magic */
        .long   MULTIBOOT2_HEADER_MAGIC
        /*  ISA: i386 */
        .long   MULTIBOOT_ARCHITECTURE_I386
        /*  Header length. */
        .long   multiboot_header_end - multiboot_header
        /*  checksum */
        .long   -(MULTIBOOT2_HEADER_MAGIC + MULTIBOOT_ARCHITECTURE_I386 + (multiboot_header_end - multiboot_header))
entry_address_tag_start:        
        .align  8
        .short MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS
        .short MULTIBOOT_HEADER_TAG_OPTIONAL
        .long entry_address_tag_end - entry_address_tag_start
        /*  entry_addr */
        .long multiboot_entry
entry_address_tag_end:
end_tag_start:
        .align  8
        .short MULTIBOOT_HEADER_TAG_END
        .short 0
        .long end_tag_end - end_tag_start
end_tag_end:
multiboot_header_end:
multiboot_entry:
        /*  Initialize the stack pointer. */
        movl    $(stack + STACK_SIZE), %esp

        /*  Reset EFLAGS. */
        pushl   $0
        popf

        /*  Push the pointer to the Multiboot information structure. */
        pushl   %ebx
        /*  Push the magic value. */
        pushl   %eax

        /*  Now enter the C main function... */
        call    EXT_C(cmain)

        /*  Halt. */
        pushl   $halt_message
        call    EXT_C(printf)
        
loop:   hlt
        jmp     loop

halt_message:
        .asciz  "Halted."

        /*  Our stack area. */
        .comm   stack, STACK_SIZE

kernel.c

/*  kernel.c - the C part of the kernel */
/*  Copyright (C) 1999, 2010  Free Software Foundation, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "multiboot2.h"

/*  Macros. */

/*  Some screen stuff. */
/*  The number of columns. */
#define COLUMNS                 80
/*  The number of lines. */
#define LINES                   24
/*  The attribute of an character. */
#define ATTRIBUTE               7
/*  The video memory address. */
#define VIDEO                   0xB8000

/*  Variables. */
/*  Save the X position. */
static int xpos;
/*  Save the Y position. */
static int ypos;
/*  Point to the video memory. */
static volatile unsigned char *video;

/*  Forward declarations. */
void cmain (unsigned long magic, unsigned long addr);
static void cls (void);
static void itoa (char *buf, int base, int d);
static void putchar (int c);
void printf (const char *format, ...);

/*  Check if MAGIC is valid and print the Multiboot information structure
   pointed by ADDR. */
void
cmain (unsigned long magic, unsigned long addr)
{  
  struct multiboot_tag *tag;
  unsigned size;

  /*  Clear the screen. */
  cls ();

  /*  Am I booted by a Multiboot-compliant boot loader? */
  if (magic != MULTIBOOT2_BOOTLOADER_MAGIC)
    {
      printf ("Invalid magic number: 0x%x\n", (unsigned) magic);
      return;
    }

  if (addr & 7)
    {
      printf ("Unaligned mbi: 0x%x\n", addr);
      return;
    }

  size = *(unsigned *) addr;
  printf ("Announced mbi size 0x%x\n", size);
  for (tag = (struct multiboot_tag *) (addr + 8);
       tag->type != MULTIBOOT_TAG_TYPE_END;
       tag = (struct multiboot_tag *) ((multiboot_uint8_t *) tag 
                                       + ((tag->size + 7) & ~7)))
    {
      printf ("Tag 0x%x, Size 0x%x\n", tag->type, tag->size);
      switch (tag->type)
        {
        case MULTIBOOT_TAG_TYPE_CMDLINE:
          printf ("Command line = %s\n",
                  ((struct multiboot_tag_string *) tag)->string);
          break;
        case MULTIBOOT_TAG_TYPE_BOOT_LOADER_NAME:
          printf ("Boot loader name = %s\n",
                  ((struct multiboot_tag_string *) tag)->string);
          break;
        case MULTIBOOT_TAG_TYPE_MODULE:
          printf ("Module at 0x%x-0x%x. Command line %s\n",
                  ((struct multiboot_tag_module *) tag)->mod_start,
                  ((struct multiboot_tag_module *) tag)->mod_end,
                  ((struct multiboot_tag_module *) tag)->cmdline);
          break;
        case MULTIBOOT_TAG_TYPE_BASIC_MEMINFO:
          printf ("mem_lower = %uKB, mem_upper = %uKB\n",
                  ((struct multiboot_tag_basic_meminfo *) tag)->mem_lower,
                  ((struct multiboot_tag_basic_meminfo *) tag)->mem_upper);
          break;
        case MULTIBOOT_TAG_TYPE_BOOTDEV:
          printf ("Boot device 0x%x,%u,%u\n",
                  ((struct multiboot_tag_bootdev *) tag)->biosdev,
                  ((struct multiboot_tag_bootdev *) tag)->slice,
                  ((struct multiboot_tag_bootdev *) tag)->part);
          break;
        case MULTIBOOT_TAG_TYPE_MMAP:
          {
            multiboot_memory_map_t *mmap;

            printf ("mmap\n");
      
            for (mmap = ((struct multiboot_tag_mmap *) tag)->entries;
                 (multiboot_uint8_t *) mmap 
                   < (multiboot_uint8_t *) tag + tag->size;
                 mmap = (multiboot_memory_map_t *) 
                   ((unsigned long) mmap
                    + ((struct multiboot_tag_mmap *) tag)->entry_size))
              printf (" base_addr = 0x%x%x,"
                      " length = 0x%x%x, type = 0x%x\n",
                      (unsigned) (mmap->addr >> 32),
                      (unsigned) (mmap->addr & 0xffffffff),
                      (unsigned) (mmap->len >> 32),
                      (unsigned) (mmap->len & 0xffffffff),
                      (unsigned) mmap->type);
          }
          break;
        case MULTIBOOT_TAG_TYPE_FRAMEBUFFER:
          {
            multiboot_uint32_t color;
            unsigned i;
            struct multiboot_tag_framebuffer *tagfb
              = (struct multiboot_tag_framebuffer *) tag;
            void *fb = (void *) (unsigned long) tagfb->common.framebuffer_addr;

            switch (tagfb->common.framebuffer_type)
              {
              case MULTIBOOT_FRAMEBUFFER_TYPE_INDEXED:
                {
                  unsigned best_distance, distance;
                  struct multiboot_color *palette;
            
                  palette = tagfb->framebuffer_palette;

                  color = 0;
                  best_distance = 4*256*256;
            
                  for (i = 0; i < tagfb->framebuffer_palette_num_colors; i++)
                    {
                      distance = (0xff - palette[i].blue) 
                        * (0xff - palette[i].blue)
                        + palette[i].red * palette[i].red
                        + palette[i].green * palette[i].green;
                      if (distance < best_distance)
                        {
                          color = i;
                          best_distance = distance;
                        }
                    }
                }
                break;

              case MULTIBOOT_FRAMEBUFFER_TYPE_RGB:
                color = ((1 << tagfb->framebuffer_blue_mask_size) - 1) 
                  << tagfb->framebuffer_blue_field_position;
                break;

              case MULTIBOOT_FRAMEBUFFER_TYPE_EGA_TEXT:
                color = '\\' | 0x0100;
                break;

              default:
                color = 0xffffffff;
                break;
              }
            
            for (i = 0; i < tagfb->common.framebuffer_width
                   && i < tagfb->common.framebuffer_height; i++)
              {
                switch (tagfb->common.framebuffer_bpp)
                  {
                  case 8:
                    {
                      multiboot_uint8_t *pixel = fb
                        + tagfb->common.framebuffer_pitch * i + i;
                      *pixel = color;
                    }
                    break;
                  case 15:
                  case 16:
                    {
                      multiboot_uint16_t *pixel
                        = fb + tagfb->common.framebuffer_pitch * i + 2 * i;
                      *pixel = color;
                    }
                    break;
                  case 24:
                    {
                      multiboot_uint32_t *pixel
                        = fb + tagfb->common.framebuffer_pitch * i + 3 * i;
                      *pixel = (color & 0xffffff) | (*pixel & 0xff000000);
                    }
                    break;

                  case 32:
                    {
                      multiboot_uint32_t *pixel
                        = fb + tagfb->common.framebuffer_pitch * i + 4 * i;
                      *pixel = color;
                    }
                    break;
                  }
              }
            break;
          }

        }
    }
  tag = (struct multiboot_tag *) ((multiboot_uint8_t *) tag 
                                  + ((tag->size + 7) & ~7));
  printf ("Total mbi size 0x%x\n", (unsigned) tag - addr);
}    

/*  Clear the screen and initialize VIDEO, XPOS and YPOS. */
static void
cls (void)
{
  int i;

  video = (unsigned char *) VIDEO;
  
  for (i = 0; i < COLUMNS * LINES * 2; i++)
    *(video + i) = 0;

  xpos = 0;
  ypos = 0;
}

/*  Convert the integer D to a string and save the string in BUF. If
   BASE is equal to ’d’, interpret that D is decimal, and if BASE is
   equal to ’x’, interpret that D is hexadecimal. */
static void
itoa (char *buf, int base, int d)
{
  char *p = buf;
  char *p1, *p2;
  unsigned long ud = d;
  int divisor = 10;
  
  /*  If %d is specified and D is minus, put ‘-’ in the head. */
  if (base == 'd' && d < 0)
    {
      *p++ = '-';
      buf++;
      ud = -d;
    }
  else if (base == 'x')
    divisor = 16;

  /*  Divide UD by DIVISOR until UD == 0. */
  do
    {
      int remainder = ud % divisor;
      
      *p++ = (remainder < 10) ? remainder + '0' : remainder + 'a' - 10;
    }
  while (ud /= divisor);

  /*  Terminate BUF. */
  *p = 0;
  
  /*  Reverse BUF. */
  p1 = buf;
  p2 = p - 1;
  while (p1 < p2)
    {
      char tmp = *p1;
      *p1 = *p2;
      *p2 = tmp;
      p1++;
      p2--;
    }
}

/*  Put the character C on the screen. */
static void
putchar (int c)
{
  if (c == '\n' || c == '\r')
    {
    newline:
      xpos = 0;
      ypos++;
      if (ypos >= LINES)
        ypos = 0;
      return;
    }

  *(video + (xpos + ypos * COLUMNS) * 2) = c & 0xFF;
  *(video + (xpos + ypos * COLUMNS) * 2 + 1) = ATTRIBUTE;

  xpos++;
  if (xpos >= COLUMNS)
    goto newline;
}

/*  Format a string and print it on the screen, just like the libc
   function printf. */
void
printf (const char *format, ...)
{
  char **arg = (char **) &format;
  int c;
  char buf[20];

  arg++;
  
  while ((c = *format++) != 0)
    {
      if (c != '%')
        putchar (c);
      else
        {
          char *p, *p2;
          int pad0 = 0, pad = 0;
          
          c = *format++;
          if (c == '0')
            {
              pad0 = 1;
              c = *format++;
            }

          if (c >= '0' && c <= '9')
            {
              pad = c - '0';
              c = *format++;
            }

          switch (c)
            {
            case 'd':
            case 'u':
            case 'x':
              itoa (buf, c, *((int *) arg++));
              p = buf;
              goto string;
              break;

            case 's':
              p = *arg++;
              if (! p)
                p = "(null)";

            string:
              for (p2 = p; *p2; p2++);
              for (; p2 < p + pad; p2++)
                putchar (pad0 ? '0' : ' ');
              while (*p)
                putchar (*p++);
              break;

            default:
              putchar (*((int *) arg++));
              break;
            }
        }
    }
}

multiboot2.h

/*   multiboot2.h - Multiboot 2 header file. */
/*   Copyright (C) 1999,2003,2007,2008,2009,2010  Free Software Foundation, Inc.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to
 *  deal in the Software without restriction, including without limitation the
 *  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 *  sell copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL ANY
 *  DEVELOPER OR DISTRIBUTOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 *  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
 *  IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef MULTIBOOT_HEADER
#define MULTIBOOT_HEADER 1

/*  How many bytes from the start of the file we search for the header. */
#define MULTIBOOT_SEARCH                        32768
#define MULTIBOOT_HEADER_ALIGN                  8

/*  The magic field should contain this. */
#define MULTIBOOT2_HEADER_MAGIC                 0xe85250d6

/*  This should be in %eax. */
#define MULTIBOOT2_BOOTLOADER_MAGIC             0x36d76289

/*  Alignment of multiboot modules. */
#define MULTIBOOT_MOD_ALIGN                     0x00001000

/*  Alignment of the multiboot info structure. */
#define MULTIBOOT_INFO_ALIGN                    0x00000008

/*  Flags set in the ’flags’ member of the multiboot header. */

#define MULTIBOOT_TAG_ALIGN                  8
#define MULTIBOOT_TAG_TYPE_END               0
#define MULTIBOOT_TAG_TYPE_CMDLINE           1
#define MULTIBOOT_TAG_TYPE_BOOT_LOADER_NAME  2
#define MULTIBOOT_TAG_TYPE_MODULE            3
#define MULTIBOOT_TAG_TYPE_BASIC_MEMINFO     4
#define MULTIBOOT_TAG_TYPE_BOOTDEV           5
#define MULTIBOOT_TAG_TYPE_MMAP              6
#define MULTIBOOT_TAG_TYPE_VBE               7
#define MULTIBOOT_TAG_TYPE_FRAMEBUFFER       8
#define MULTIBOOT_TAG_TYPE_ELF_SECTIONS      9
#define MULTIBOOT_TAG_TYPE_APM               10
#define MULTIBOOT_TAG_TYPE_EFI32             11
#define MULTIBOOT_TAG_TYPE_EFI64             12
#define MULTIBOOT_TAG_TYPE_SMBIOS            13
#define MULTIBOOT_TAG_TYPE_ACPI_OLD          14
#define MULTIBOOT_TAG_TYPE_ACPI_NEW          15
#define MULTIBOOT_TAG_TYPE_NETWORK           16
#define MULTIBOOT_TAG_TYPE_EFI_MMAP          17
#define MULTIBOOT_TAG_TYPE_EFI_BS            18
#define MULTIBOOT_TAG_TYPE_EFI32_IH          19
#define MULTIBOOT_TAG_TYPE_EFI64_IH          20
#define MULTIBOOT_TAG_TYPE_LOAD_BASE_ADDR    21

#define MULTIBOOT_HEADER_TAG_END  0
#define MULTIBOOT_HEADER_TAG_INFORMATION_REQUEST  1
#define MULTIBOOT_HEADER_TAG_ADDRESS  2
#define MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS  3
#define MULTIBOOT_HEADER_TAG_CONSOLE_FLAGS  4
#define MULTIBOOT_HEADER_TAG_FRAMEBUFFER  5
#define MULTIBOOT_HEADER_TAG_MODULE_ALIGN  6
#define MULTIBOOT_HEADER_TAG_EFI_BS        7
#define MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS_EFI32  8
#define MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS_EFI64  9
#define MULTIBOOT_HEADER_TAG_RELOCATABLE  10

#define MULTIBOOT_ARCHITECTURE_I386  0
#define MULTIBOOT_ARCHITECTURE_MIPS32  4
#define MULTIBOOT_HEADER_TAG_OPTIONAL 1

#define MULTIBOOT_LOAD_PREFERENCE_NONE 0
#define MULTIBOOT_LOAD_PREFERENCE_LOW 1
#define MULTIBOOT_LOAD_PREFERENCE_HIGH 2

#define MULTIBOOT_CONSOLE_FLAGS_CONSOLE_REQUIRED 1
#define MULTIBOOT_CONSOLE_FLAGS_EGA_TEXT_SUPPORTED 2

#ifndef ASM_FILE

typedef unsigned char           multiboot_uint8_t;
typedef unsigned short          multiboot_uint16_t;
typedef unsigned int            multiboot_uint32_t;
typedef unsigned long long      multiboot_uint64_t;

struct multiboot_header
{
  /*  Must be MULTIBOOT_MAGIC - see above. */
  multiboot_uint32_t magic;

  /*  ISA */
  multiboot_uint32_t architecture;

  /*  Total header length. */
  multiboot_uint32_t header_length;

  /*  The above fields plus this one must equal 0 mod 2^32. */
  multiboot_uint32_t checksum;
};

struct multiboot_header_tag
{
  multiboot_uint16_t type;
  multiboot_uint16_t flags;
  multiboot_uint32_t size;
};

struct multiboot_header_tag_information_request
{
  multiboot_uint16_t type;
  multiboot_uint16_t flags;
  multiboot_uint32_t size;
  multiboot_uint32_t requests[0];
};

struct multiboot_header_tag_address
{
  multiboot_uint16_t type;
  multiboot_uint16_t flags;
  multiboot_uint32_t size;
  multiboot_uint32_t header_addr;
  multiboot_uint32_t load_addr;
  multiboot_uint32_t load_end_addr;
  multiboot_uint32_t bss_end_addr;
};

struct multiboot_header_tag_entry_address
{
  multiboot_uint16_t type;
  multiboot_uint16_t flags;
  multiboot_uint32_t size;
  multiboot_uint32_t entry_addr;
};

struct multiboot_header_tag_console_flags
{
  multiboot_uint16_t type;
  multiboot_uint16_t flags;
  multiboot_uint32_t size;
  multiboot_uint32_t console_flags;
};

struct multiboot_header_tag_framebuffer
{
  multiboot_uint16_t type;
  multiboot_uint16_t flags;
  multiboot_uint32_t size;
  multiboot_uint32_t width;
  multiboot_uint32_t height;
  multiboot_uint32_t depth;
};

struct multiboot_header_tag_module_align
{
  multiboot_uint16_t type;
  multiboot_uint16_t flags;
  multiboot_uint32_t size;
};

struct multiboot_header_tag_relocatable
{
  multiboot_uint16_t type;
  multiboot_uint16_t flags;
  multiboot_uint32_t size;
  multiboot_uint32_t min_addr;
  multiboot_uint32_t max_addr;
  multiboot_uint32_t align;
  multiboot_uint32_t preference;
};

struct multiboot_color
{
  multiboot_uint8_t red;
  multiboot_uint8_t green;
  multiboot_uint8_t blue;
};

struct multiboot_mmap_entry
{
  multiboot_uint64_t addr;
  multiboot_uint64_t len;
#define MULTIBOOT_MEMORY_AVAILABLE              1
#define MULTIBOOT_MEMORY_RESERVED               2
#define MULTIBOOT_MEMORY_ACPI_RECLAIMABLE       3
#define MULTIBOOT_MEMORY_NVS                    4
#define MULTIBOOT_MEMORY_BADRAM                 5
  multiboot_uint32_t type;
  multiboot_uint32_t zero;
};
typedef struct multiboot_mmap_entry multiboot_memory_map_t;

struct multiboot_tag
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
};

struct multiboot_tag_string
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  char string[0];
};

struct multiboot_tag_module
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t mod_start;
  multiboot_uint32_t mod_end;
  char cmdline[0];
};

struct multiboot_tag_basic_meminfo
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t mem_lower;
  multiboot_uint32_t mem_upper;
};

struct multiboot_tag_bootdev
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t biosdev;
  multiboot_uint32_t slice;
  multiboot_uint32_t part;
};

struct multiboot_tag_mmap
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t entry_size;
  multiboot_uint32_t entry_version;
  struct multiboot_mmap_entry entries[0];  
};

struct multiboot_vbe_info_block
{
  multiboot_uint8_t external_specification[512];
};

struct multiboot_vbe_mode_info_block
{
  multiboot_uint8_t external_specification[256];
};

struct multiboot_tag_vbe
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;

  multiboot_uint16_t vbe_mode;
  multiboot_uint16_t vbe_interface_seg;
  multiboot_uint16_t vbe_interface_off;
  multiboot_uint16_t vbe_interface_len;

  struct multiboot_vbe_info_block vbe_control_info;
  struct multiboot_vbe_mode_info_block vbe_mode_info;
};

struct multiboot_tag_framebuffer_common
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;

  multiboot_uint64_t framebuffer_addr;
  multiboot_uint32_t framebuffer_pitch;
  multiboot_uint32_t framebuffer_width;
  multiboot_uint32_t framebuffer_height;
  multiboot_uint8_t framebuffer_bpp;
#define MULTIBOOT_FRAMEBUFFER_TYPE_INDEXED 0
#define MULTIBOOT_FRAMEBUFFER_TYPE_RGB     1
#define MULTIBOOT_FRAMEBUFFER_TYPE_EGA_TEXT     2
  multiboot_uint8_t framebuffer_type;
  multiboot_uint16_t reserved;
};

struct multiboot_tag_framebuffer
{
  struct multiboot_tag_framebuffer_common common;

  union
  {
    struct
    {
      multiboot_uint16_t framebuffer_palette_num_colors;
      struct multiboot_color framebuffer_palette[0];
    };
    struct
    {
      multiboot_uint8_t framebuffer_red_field_position;
      multiboot_uint8_t framebuffer_red_mask_size;
      multiboot_uint8_t framebuffer_green_field_position;
      multiboot_uint8_t framebuffer_green_mask_size;
      multiboot_uint8_t framebuffer_blue_field_position;
      multiboot_uint8_t framebuffer_blue_mask_size;
    };
  };
};

struct multiboot_tag_elf_sections
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t num;
  multiboot_uint32_t entsize;
  multiboot_uint32_t shndx;
  char sections[0];
};

struct multiboot_tag_apm
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint16_t version;
  multiboot_uint16_t cseg;
  multiboot_uint32_t offset;
  multiboot_uint16_t cseg_16;
  multiboot_uint16_t dseg;
  multiboot_uint16_t flags;
  multiboot_uint16_t cseg_len;
  multiboot_uint16_t cseg_16_len;
  multiboot_uint16_t dseg_len;
};

struct multiboot_tag_efi32
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t pointer;
};

struct multiboot_tag_efi64
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint64_t pointer;
};

struct multiboot_tag_smbios
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint8_t major;
  multiboot_uint8_t minor;
  multiboot_uint8_t reserved[6];
  multiboot_uint8_t tables[0];
};

struct multiboot_tag_old_acpi
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint8_t rsdp[0];
};

struct multiboot_tag_new_acpi
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint8_t rsdp[0];
};

struct multiboot_tag_network
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint8_t dhcpack[0];
};

struct multiboot_tag_efi_mmap
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t descr_size;
  multiboot_uint32_t descr_vers;
  multiboot_uint8_t efi_mmap[0];
}; 

struct multiboot_tag_efi32_ih
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t pointer;
};

struct multiboot_tag_efi64_ih
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint64_t pointer;
};

struct multiboot_tag_load_base_addr
{
  multiboot_uint32_t type;
  multiboot_uint32_t size;
  multiboot_uint32_t load_base_addr;
};

#endif /*  ! ASM_FILE */

#endif /*  ! MULTIBOOT_HEADER */

參考文獻

Multiboot2 Specification version 2.0

寫作業系統 之 GRUB 到 multiboot ——從 multiboot 開始對接核心(轉載)

[作業系統原理與實現]Multiboot與GRUB_multiboot2-CSDN部落格

grub2詳解(翻譯和整理官方手冊) - 駿馬金龍 - 部落格園

用 GRUB 引導自己的作業系統_切換grub以實現系統的正常引導-CSDN部落格

作業系統實現 - 055 multiboot2 頭_嗶哩嗶哩_bilibili

MBR和GPT_mbr gap-CSDN部落格


本文釋出於2023年10月8日

最後修改於2024年10月8日

相關文章