Ada Bare Bones:用 Ada 编写 Multiboot 内核的裸机教程
文章目录
本教程的目标是用 Ada 编程语言编写一个小型 Multiboot 内核。
前言
人们在 Freenode 的 Ada IRC 频道上最先问的问题之一是 "Ada 能用于操作系统开发吗?" ,而答案是响亮的 是。
先决条件
以下章节详细说明成功构建内核所需的先决软件。
交叉编译器
- 主条目: GNAT 交叉编译器
本教程需要使用支持 Ada 的 交叉编译器 ,目标为 i686-elf 架构。理论上,任何能够为该架构生成裸机 ELF 二进制文件的 Ada 编译器都适用。推荐的编译器是 GNAT,它是自由软件基金会维护的 GNU Compiler Collection 的一部分。历史上,为 GNAT 创建交叉编译器构建很困难,但近期版本的 GCC 使这变得简单得多。关于如何设置 GNAT 交叉编译器的教程,请参阅 本文。
GPRbuild
本教程需要使用 GPRBuild 工具来构建 GNAT 项目文件。GPRbuild 是一个通用构建工具,专为构建多语言系统而设计。它包含在 AdaCore 的专有 GNAT 编译器发行版中: [1] ,或者可以从 AdaCore 的 github 主页获取源文件自行构建。自由软件基金会分发的较旧版本 GNAT 能够使用 gnatmake 工具构建 GNAT 项目文件,但较新版本不支持所有必需的功能。
上述交叉编译器需要与 GPRbuild 及其相关工具正确集成。这可以通过遵循 此处 中详述的指南来完成。
Ada 运行时库
- 主条目: Ada 运行时库
Ada 运行时库负责实现 Ada 语言参考手册中定义的标准库。并非参考手册中列出的所有功能都需要在每个平台上实现。由于内核将在没有底层操作系统支持的独立环境中运行,它将使用所谓的 零占用运行时系统 (通常缩写为 'ZFP')来构建。零占用 RTS 通常仅为目标架构提供最低限度的功能。
以下步骤将详细说明如何创建适合构建内核的初始零占用运行时库。
第一步是设置用于存放运行时库的目录结构。GNAT 要求运行时库符合固定的目录结构。它要求存在两个目录: adalib 和 adainclude。adainclude 包含运行时包的规格说明和源文件,其用法类似于 C 中的包含文件。adalib 包含运行时库编译后的二进制产物。
以下代码演示了为 RTS 设置目录结构:
$ mkdir -p bare_bones/src/pc $ cd bare_bones $ mkdir -p rts/boards/i386/adalib $ mkdir -p rts/boards/i386/adainclude $ mkdir -p rts/src $ mkdir -p obj
创建新运行时库的最佳方式是以系统 GNAT 安装中获得的现有源文件为基础,并在必要时进行修改。
以下代码演示了将所需文件从主机系统 GNAT 安装的运行时库复制到 rts/src ,然后创建指向 rts/boards/${arch}/adainclude的符号链接。其中 ${arch} 为 i386, armv6等。源位置需要修改以反映系统编译器的位置。
system_compiler_dir="/usr/lib/gcc/x86_64-linux-gnu/8" rts_dir="${PWD}/rts" for f in "ada.ads" "a-unccon.ads" "a-uncdea.ads" "gnat.ads" "g-souinf.ads" \ "interfac.ads" "s-atacco.adb" "s-atacco.ads" "s-maccod.ads" "s-stoele.adb" \ "s-stoele.ads" do cp "${system_compiler_dir}/adainclude/$f" "${rts_dir}/src/" ln -s "${rts_dir}/src/$f" "${rts_dir}/rts/boards/i386/adainclude/$f" done
文件
gnat.adc
编译时,GNAT 编译器会在当前工作目录中查找名为 gnat.adc 的文件。该文件应包含一个或多个配置 pragma,这些 pragma 将应用于当前编译。这些 pragma 指令指示编译器应限制运行时的哪些功能。这对内核开发尤为重要,因为 Ada 的许多功能在独立的裸机环境中不受支持。
这些 pragma 指令也可以放在运行时库的 system.ads 文件开头(见下文),但按照惯例使用 gnat.adc 文件来实现此目的。
此外,还可以通过在 GNAT 项目文件的 Builder 包中追加以下行来应用额外的全局配置文件:
package Builder is -- ... for Global_Configuration_Pragmas use "kernel.adc"; end Builder;
也可以使用命令行开关 -gnatec=path 指示编译器将包含配置 pragma 的额外文件应用于当前编译。这些配置 pragma 会与 gnat.adc中的配置 pragma(如果存在)一起应用。 有关配置文件的更多信息,请参阅 GNAT 文档: [2]
GNAT 参考手册和 Ada 参考手册提供了有关各种配置 pragma 的信息。 以下列出了对裸机内核和运行时有用的限制 pragma:
pragma Discard_Names; pragma Restrictions (No_Enumeration_Maps); pragma Normalize_Scalars; pragma Restrictions (No_Exception_Propagation); pragma Restrictions (No_Finalization); pragma Restrictions (No_Tasking); pragma Restrictions (No_Protected_Types); pragma Restrictions (No_Delay); pragma Restrictions (No_Recursion); pragma Restrictions (No_Allocators); pragma Restrictions (No_Dispatch); pragma Restrictions (No_Implicit_Dynamic_Code); pragma Restrictions (No_Secondary_Stack);
注意: 不要使用 pragma No_Run_Time。它已过时。
以下是对这些配置 pragma 的说明:
| 限制 | 用途 |
|---|---|
| Discard_Names | Ada 编译器会自动生成包含枚举数据类型等名称的字符串。这些字符串可用于 I/O。
type Fruit is (Orange, Banana, Apple); -- Ada defines the following strings, "Orange", "Banana" and "Apple" in an array. -- These strings can be accessed using the 'Image attribute, as in Put (Fruit'Image (Orange)); -- Prints "Orange" to the console. 此指令指示编译器不要生成这些字符串。 |
| Normalize_Scalars | 强制初始化所有标量。更多信息请参阅 GNAT RM:Normalize_Scalars 。 |
| No_Exception_Propagation | 此指令强制编译器禁止任何跨越子程序边界引发异常的尝试。更多信息请参阅 GNAT RM:No_Exception_Propagation 。
注意: GNAT High Integrity Edition 文档指出:
所有未在其子程序内通过显式异常处理程序处理的异常,都将由 Last_Chance_Handler 子程序捕获。这将在编译时产生一条警告。 |
| No_Exception_Registration | 确保不对 Ada.Exceptions 中声明的类型执行流操作。参见 GNAT RM:No_Exception_Registration 了解更多信息。 |
| No_Finalization | 限制受控类型的使用。参见 GNAT RM:No_Finalization 了解更多信息。 |
| No_Tasking | 此指令限制所有与任务(tasking)相关的特性,包括保护对象的使用。参见 GNAT RM:No_Tasking 了解更多信息。 |
| No_Protected_Types | 这进一步强化了上述限制。参见 GNAT RM:No_Protected_Types 了解更多信息。 |
| No_Delay | 限制 delay 语句或日历包的使用。参见 GNAT RM:No_Delay 了解更多信息。 |
| No_Recursion | 限制递归的使用。参见 GNAT RM:No_Recursion 了解更多信息。 |
| No_Allocators | 限制动态内存的使用。这对于裸机应用程序至关重要,因为没有用于分配动态内存的底层设施。参见 GNAT RM:No_Allocators 了解更多信息。 |
| No_Dispatch | 禁止使用 Ada 的面向对象机制调用子程序。参见 GNAT RM:No_Dispatch 了解更多信息。 |
| No_Implicit_Dynamic_Code | 禁止嵌套子程序或任何其他在栈上生成 trampoline 的特性。参见 GNAT RM:No_Implicit_Dynamic_Code 了解更多信息。 |
| No_Secondary_Stack | Ada 使用 次级栈 来返回不受约束的类型,例如任意长度的字符串或变体记录。此指令告知编译器不存在次级栈,并限制需要次级栈的代码的使用。参见 GNAT RM:No_Secondary_Stack 了解更多信息。 |
将 -r 标志传递给绑定器,会指示它输出一份可以应用于该项目的进一步限制列表。
package Binder is for Default_Switches ("Ada") use ("-r"); end Binder;
system.ads
每个 Ada 程序都必须能够访问 System 包,这实际上告诉编译器我们正在为哪种硬件进行构建,因此你的内核支持的每种架构都会有 1 个 system.ads 文件。
从 GCC 中复制一个与你正在处理的目标相匹配的 system.ads,在我们的例子中是 gcc-<version>/gcc/ada/system-linux-x86.ads,将其命名为 system.ads 并放入 rts/boards/i386/adainclude/ 中,我们需要对其进行一些编辑。
我们不需要更改顶部的任何内容,因为所有整数大小都应该是正确的。转到规范的私有部分并更改以下值:
- Command_Line_Args => False
- Configurable_Run_Time => True
- Exit_Status_Supported => False
- Stack_Check_Probes => False
- Suppress_Standard_Library => True
- ZCX_By_Default => False
- GCC_ZCX_Support => False
有关这些选项的更多信息,请参阅 gcc-<version>/gcc/ada/targparm.ads。
此外,在包的私有部分中添加以下行:
private Run_Time_Name : constant String := "Bare Bones Run Time";
根据 targparm.ads,它必须是 private 关键字之后的第一项。它也应该以括号形式出现在错误消息中,但到目前为止我还没能让它显示出来。这很有用,因为它应该会显示你当前正在使用哪个 RTS,以防你错误地配置了构建。
最后机会处理程序
Ada 运行时要求存在一个 Last_Chance_Handler 子程序。该子程序用作任何未在其子程序内显式处理的异常的处理程序。在出现未处理异常的情况下,对 Last_Chance_Handler 过程的这些调用将由编译器自动生成。
为此,最后机会处理程序过程必须定义在程序中的某个位置。通常它定义在运行时中。最后机会处理程序过程可以使用任何名称,但编译器会搜索一个具有外部链接、名称为 __gnat_last_chance_handler 的过程。
在 rts/boards/${arch}/adainclude 中创建以下文件:
last_chance_handler.ads
with System; procedure Last_Chance_Handler (Source_Location : System.Address; Line : Integer); pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");
last_chance_handler.adb
procedure Last_Chance_Handler (Source_Location : System.Address; Line : Integer) is pragma Unreferenced (Source_Location, Line); begin -- TODO: Add in board-specific code to dump exception information to serial/screen. loop null; end loop; end Last_Chance_Handler;
Last_Chance_Handler 过程的内容需要针对内核的具体平台进行定制。通常,该过程会将有关异常的信息转储到输出介质,例如 串口。
编译运行时
在根目录中创建一个名为 gnat.gpr 的文件,内容如下:
library project gnat is type Arch_Name is ("i386", "arm"); type Board_Name is ("pc", "rpi"); Arch : Arch_Name := "i386"; Board : Board_Name := external ("Board"); case Board is when "pc" => Arch := "i386"; when "rpi" => Arch := "arm"; end case; for Source_Dirs use ("rts/boards/" & Arch & "/adainclude"); for Object_Dir use "obj"; --"rts/boards/" & Arch & "/adalib"; package Builder is Basic_Switches := ("-gnat2005", "-g", "-x", "-a", "-gnatg", "-gnatec=../gnat.adc"); case Board is when "pc" => for Default_Switches ("Ada") use Basic_Switches & ("-m32", "-march=i386"); when "rpi" => for Default_Switches ("Ada") use Basic_Switches & ("-march=armv6zk", "-mfpu=vfp", "-mfloat-abi=hard", "-marm", "-mcpu=arm1176jzf-s", "-mtune=arm1176jzf-s"); end case; end Builder; package Compiler is for Default_Switches ("Ada") use ("-O2", "-ffunction-sections", "-fdata-sections"); end Compiler; for Library_Kind use "static"; for Library_Name use "gnat-4.6"; for Library_Dir use "rts/boards/" & Arch & "/adalib"; end gnat;
现在使用以下命令进行编译:
gprbuild -XBoard=pc -Pgnat.gpr
在 rts/boards/i386/adainclude/ 中,RTS 源文件应与自定义的 last_chance_hander 和系统文件一起进行符号链接。在 rts/boards/i386/adalib/ 中,应有 libgnat-4.6.a 文件以及与源文件匹配的 *.ali 文件,这些是 GNAT 所必需的。
注意:请注意,上述库可能需要更改其名称,因为某些操作系统构建 libgnat 时使用的版本号可能与此处使用的不同。系统 libnat 版本可能是 libgnat-4.4.a ,而 GNAT 会期望找到该名称,因此请相应地更改 GPR 文件中的名称。
startup.s
这是主要的系统引导代码。此版本特定于 PC,因此请将其放在 src/pc 目录中。
注意:此源文件使用 GAS 语法编写。
.global startup # Make the startup entry point symbol visible to the linker # Set up the Multiboot header (see GRUB docs for details) .set ALIGN, 1<<0 # Align loaded modules on page boundaries .set MEMINFO, 1<<1 # Provide memory map .set FLAGS, ALIGN | MEMINFO # This is the Multiboot 'flag' field .set MAGIC, 0x1BADB002 # 'magic number' lets your bootloader find the header .set CHECKSUM, -(MAGIC + FLAGS) # Checksum required header: # Must be in the first 8kb of the kernel file .align 4, 0x90 # Pad the location counter (in the current subsection) to a 4-byte # storage boundary. The way alignment is specified can vary with # host system architecture. .long MAGIC .long FLAGS .long CHECKSUM # Reserve initial kernel stack space .set STACKSIZE, 0x4000 # 0x4000 being 16k. .lcomm stack, STACKSIZE # Reserve 16k stack on a32-bit boundary .comm mbd, 4 # Declare common symbol mbd, allocate it 4-bytes of # uninitialized memory. .comm magic, 4 # Declare common symbol magic, allocate it 4-bytes of # uninitialized memory. startup: movl $(stack + STACKSIZE), %esp # Set up the stack # The following saves the contents of the registers as they will likely be # overwritten because main is not our actual entry point, Bare_Bones is. We # will use these 2 symbols inside Bare_Bones. movl %eax, magic # EAX indicates to the OS that it was loaded by a Multiboot-compliant boot # loader movl %ebx, mbd # EBX must contain the physical address of the Multiboot information # structure call main # Call main (created by gnatbind) cli # Disable interrupts. then intentionally hang the system. # CLI only affects the interrupt flag for the processor on which it is # executed. hang: hlt # Because the HLT instruction halts until an interrupt occurs, the # combination of a CLI followed by a HLT is used to intentionally hang # the computer if the kernel returns. # HLT is in a loop just in case a single HLT instruction fails to execute # for some reason, (such as in the case of an NMI). jmp hang
multiboot.ads
我不会展示此程序包的源代码,因为我已将其改写得更符合 Ada 风格,而且它相当大,所以我将链接到当前版本, multiboot.ads 和 multiboot.adb.
Console
免责声明: 我很久以前编写了此程序包,并使用我当前的 Ada 编程风格对其进行了重新格式化。我没有深入检查代码,因此它可能不是控制台的最佳实现。
以下 2 个文件使你可以访问 80x25 字符的 VGA 控制台。由于它们特定于 PC,因此放在 src/pc 目录中。
console.ads
with System; package Console is pragma Preelaborate (Console); type Background_Colour is (Black, Blue, Green, Cyan, Red, Magenta, Brown, Light_Grey); for Background_Colour use (Black => 16#0#, Blue => 16#1#, Green => 16#2#, Cyan => 16#3#, Red => 16#4#, Magenta => 16#5#, Brown => 16#6#, Light_Grey => 16#7#); for Background_Colour'Size use 4; type Foreground_Colour is (Black, Blue, Green, Cyan, Red, Magenta, Brown, Light_Grey, Dark_Grey, Light_Blue, Light_Green, Light_Cyan, Light_Red, Light_Magenta, Yellow, White); for Foreground_Colour use (Black => 16#0#, Blue => 16#1#, Green => 16#2#, Cyan => 16#3#, Red => 16#4#, Magenta => 16#5#, Brown => 16#6#, Light_Grey => 16#7#, Dark_Grey => 16#8#, Light_Blue => 16#9#, Light_Green => 16#A#, Light_Cyan => 16#B#, Light_Red => 16#C#, Light_Magenta => 16#D#, Yellow => 16#E#, White => 16#F#); for Foreground_Colour'Size use 4; type Cell_Colour is record Foreground : Foreground_Colour; Background : Background_Colour; end record; for Cell_Colour use record Foreground at 0 range 0 .. 3; Background at 0 range 4 .. 7; end record; for Cell_Colour'Size use 8; type Cell is record Char : Character; Colour : Cell_Colour; end record; for Cell'Size use 16; Screen_Width : constant Natural := 80; Screen_Height : constant Natural := 25; subtype Screen_Width_Range is Natural range 1 .. Screen_Width; subtype Screen_Height_Range is Natural range 1 .. Screen_Height; type Row is array (Screen_Width_Range) of Cell; type Screen is array (Screen_Height_Range) of Row; Video_Memory : Screen; for Video_Memory'Address use System'To_Address (16#000B_8000#); pragma Import (Ada, Video_Memory); procedure Put (Char : in Character; X : in Screen_Width_Range; Y : in Screen_Height_Range; Foreground : in Foreground_Colour := White; Background : in Background_Colour := Black); procedure Put (Str : in String; X : in Screen_Width_Range; Y : in Screen_Height_Range; Foreground : in Foreground_Colour := White; Background : in Background_Colour := Black); procedure Clear (Background : in Background_Colour := Black); end Console;
console.adb
package body Console is procedure Put (Char : in Character; X : in Screen_Width_Range; Y : in Screen_Height_Range; Foreground : in Foreground_Colour := White; Background : in Background_Colour := Black) is begin Video_Memory (Y)(X).Char := Char; Video_Memory (Y)(X).Colour.Foreground := Foreground; Video_Memory (Y)(X).Colour.Background := Background; end Put; procedure Put (Str : in String; X : in Screen_Width_Range; Y : in Screen_Height_Range; Foreground : in Foreground_Colour := White; Background : in Background_Colour := Black) is begin for Index in Str'First .. Str'Last loop Put (Str (Index), X + Screen_Width_Range (Index) - 1, Y, Foreground, Background); end loop; end Put; procedure Clear (Background : in Background_Colour := Black) is begin for X in Screen_Width_Range'First .. Screen_Width_Range'Last loop for Y in Screen_Height_Range'First .. Screen_Height_Range'Last loop Put (' ', X, Y, Background => Background); end loop; end loop; end Clear; end Console;
bare_bones.adb
这是平台无关的,因此放在 src 目录中。
with Console; use Console; procedure Bare_Bones is begin Clear; Put ("Hello, bare bones in Ada.", Screen_Width_Range'First, Screen_Height_Range'First); end Bare_Bones; pragma No_Return (Bare_Bones);
linker.ld
这是特定于 PC 的脚本,因此放在 src/pc 目录中。
OUTPUT_FORMAT(elf32-i386)
/* Tell the linker which startup code to use, we do this as there is no way to do this (well not easily) from the GNAT tools. */
STARTUP(startup.o)
ENTRY (startup)
SECTIONS
{
. = 0x00100000;
.text :{
code = .; _code = .; __code = .;
*(.text)
*(.rodata)
}
.rodata ALIGN (0x1000) : {
*(.rodata)
}
.data ALIGN (0x1000) : {
data = .; _data = .; __data = .;
*(.data)
}
.bss : {
sbss = .;
bss = .; _bss = .; __bss = .;
*(COMMON)
*(.bss)
ebss = .;
}
end = .; _end = .; __end = .;
}
makefile
将此文件放在根目录中。
ARCH = i386 RTS_DIR = `pwd`/rts/boards/$(ARCH) ifeq ($(ARCH),i386) GPRBUILD = gprbuild AS = as ASFLAGS = --32 -march=i386 OBJS = obj/startup.o obj/multiboot.o obj/console.o BOARD = pc .PHONY: obj/multiboot.o obj/console.o endif all: bare_bones bare_bones: $(OBJS) src/bare_bones.adb $(GPRBUILD) --RTS=$(RTS_DIR) -XBoard=$(BOARD) -Pbare_bones.gpr obj/startup.o: src/$(BOARD)/startup.s $(AS) $(ASFLAGS) src/$(BOARD)/startup.s -o obj/startup.o .PHONY: clean clean: -rm obj/* *~ bare_bones
bare_bones.gpr
将此文件放在根目录中。
project Bare_Bones is type Arch_Name is ("i386", "arm"); type Board_Name is ("pc", "rpi"); Arch : Arch_Name := "i386"; Board : Board_Name := external ("Board"); -- TODO: Add in a case statement that adds an arch dir to source. case Board is when "pc" => for Source_Dirs use ("src", "src/pc"); when "rpi" => for Source_Dirs use ("src", "src/rpi"); end case; for Object_Dir use "obj"; for Exec_Dir use "."; for Main use ("bare_bones.adb"); package Builder is Basic_Switches := ("-gnat2005", "-g", "-x", "-a", "-gnatg", "-gnatec=../gnat.adc", "-gnaty-I", "-gnaty+d"); case Board is when "pc" => for Default_Switches ("Ada") use Basic_Switches & ("-m32", "-march=i386"); when "rpi" => for Default_Switches ("Ada") use Basic_Switches & ("-march=armv6zk", "-mfpu=vfp", "-mfloat-abi=hard", "-marm", "-mcpu=arm1176jzf-s", "-mtune=arm1176jzf-s"); end case; end Builder; package Compiler is case Board is when "pc" => for Default_Switches ("Ada") use ("-O0", "-g", "-ggdb", "-ffunction-sections", "-fdata-sections"); when "rpi" => for Default_Switches ("Ada") use ("-O0", "-g", "-ggdb", "-ffunction-sections", "-fdata-sections"); end case; end Compiler; -- To reduce size of final binary. package Linker is for Default_Switches ("Ada") use ("-Wl,--gc-sections", "-static", "-nostartfiles", "-nodefaultlibs", "-T../src/" & Board & "/linker.ld", "-v"); end Linker; end Bare_Bones;
Raspberry Pi
启动过程
如 [3]中所述,RPi 启动过程如下:
- 上电启动位于 SoC 上的阶段 1 引导加载程序,它将阶段 2 引导加载程序(bootcode.bin)加载到 L2 缓存中(从而将其打开)。
- bootcode.bin 启用 SDRAM 并加载阶段 3 引导加载程序(loader.bin)。
- loader.bin 加载并执行 VideoCore 固件(start.elf)。
- start.elf 加载 config.txt、cmdline.txt 和 kernel.img。
config.txt 文件可以包含一行 "kernel=<name>",你可以在其中为内核映像指定任意名称。
理想情况下,在开发中我们会使用模拟器或某种网络引导功能,这样就不必反复将 SD 卡从 Pi 换到 PC 或反之,这很快就会变得乏味。
U-Boot
看来你需要对板卡进行串口访问才能做到这一点,所以我暂时不会尝试。
按照 FreeBSD 移植页面上开始的信息,我们可以为 RPi 构建 u-boot。
$ git clone git://github.com/gonzoua/u-boot-pi.git $ cd u-boot-pi $ make rpi_b_config
测试
在进入下一阶段之前,请确保你已构建上述 RTS,否则你将无法编译内核。
$ make qemu
在 QEMU 窗口中,它应该会清屏,光标不会移动,因此它将位于屏幕中央,左上角将显示消息 "Hello, bare bones in Ada."
源代码访问
我在 GitHub 上创建了一个 Git 仓库,其中包含上述源代码,因此如果你不想手动操作,就不必自己动手。
事实上,自从我开始这个项目以来已经有很多变化,从 GitHub 获取源代码是更好的主意,因为它会更新。我会保留上述文档,这样你就可以看到它是如何演变的,以及它是如何工作的,也许比现在更清楚一些。
后续步骤
进一步开发本文概述的裸机内核的一个有用的下一步是实现使用标量类型上的 'Image 属性的能力。这有助于以字符串形式打印整数,这对内核调试极为有用。关于如何实现这一点的简单指南详见 此处。
来源与翻译说明
本文根据原文快照翻译,保留原有代码、数值、技术限定及历史背景。原文中的命令与运行结果不代表本站已实际执行验证。
原文:Ada Bare Bones;离线修订号:30645。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论