Go Bare Bones:用 Go 语言编写极简操作系统

来源:OSDev Wiki· 阅读原文 ↗
文章封面

Proceed with caution!

本页面或章节宣传了 不良或过时的做法。请谨慎参考,并通过 保持信息更新,帮助完善本 wiki。

等等!你是否已经阅读了 入门指南、初学者常见错误,以及一些相关的 操作系统理论?

难度级别
Difficulty 2.png
中等

在本教程中,你将学习如何开始使用 Go 语言编写你自己的操作系统。它将展示如何创建一个极简系统以在屏幕上显示文本。它绝不是你应该如何组织或构建项目的范例。

前言

强烈建议在学习本教程之前先阅读 Bare Bones ,因为本教程基于它。另外请记住,Go 语言本身并非为操作系统开发而设计。因此,你在每一步都要与这门语言作斗争。

本教程假设你使用的是类 Unix 操作系统,例如 Linux。

关于支持 Go 操作系统开发的完整生产级框架,请参见 TamaGo 项目。

构建交叉编译器

主条目: GCC 交叉编译器

你首先应该做的是搭建一个支持 Go 的 GCC 交叉编译器。为此,请阅读并严格遵循 GCC 交叉编译器,但有一处例外。在配置 GCC 构建时,我们需要启用 Go 以获得 i686-elf-gccgo 编译器。

因此,不使用:

../gcc-x.y.z/configure --target=$TARGET --prefix="$PREFIX" --disable-nls --enable-languages=c,c++ --without-headers

我们使用:

../gcc-x.y.z/configure --target=$TARGET --prefix="$PREFIX" --disable-nls --enable-languages=c,c++,go --without-headers

概述

到目前为止,你应该已经搭建好了支持 Go 的 i686-elf 交叉编译器(如上所述)。本教程提供了一个为 x86 创建操作系统的极简方案。它并非作为项目结构的推荐骨架,而是作为一个极简内核的示例,使用另一个包在屏幕上显示文本。在这个简单示例中,我们只需要四个输入文件:

  • boot.s - 设置处理器环境的内核入口点
  • kernel.go - 你的实际内核例程
  • terminal.go - 用于向屏幕打印文本的包
  • linker.ld - 用于链接上述文件

引导汇编

我们现在将创建名为 boot.s 的文件,并简要讨论其内容。

# Declare constants used for creating a multiboot header.
.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 bootloader find the header
.set CHECKSUM, -(MAGIC + FLAGS) # checksum of above, to prove we are multiboot

# Declare a header as in the Multiboot Standard.
.section .multiboot
.align 4
.long MAGIC
.long FLAGS
.long CHECKSUM

# Currently the stack pointer register (esp) points at anything and using it may
# cause massive harm. Instead, we'll provide our own stack.
.section .bootstrap_stack, "aw", @nobits
stack_bottom:
.skip 16384 # 16 KiB
stack_top:

# The linker script specifies _start as the entry point to the kernel and the
# bootloader will jump to this position once the kernel has been loaded. It
# doesn't make sense to return from this function as the bootloader is gone.
.section .text
.global _start
.type _start, @function
_start:
	# To set up a stack, we simply set the esp register to point to the top of
	# our stack (as it grows downwards).
	movl $stack_top, %esp

	# We are now ready to actually execute Go code. Functions that start with a
	# capital letter are exported as "go.<package>.<function>".
	call go.kernel.Main

	# In case the function returns, we'll want to put the computer into an
	# infinite loop.
	cli
	hlt
.Lhang:
	jmp .Lhang

# Set the size of the _start symbol to the current location '.' minus its start.
# This is useful when debugging or when you implement call tracing.
.size _start, . - _start

# The Go runtime is a big problem when wanting to write a kernel in Go.
# Although not impossible, it's certainly not trivial. At the very least
# you'd need to implement parts of libc that it uses. Porting the runtime
# goes way beyond the scope of this barebone. 
#
# Beware that there are almost no language features you can use at this point.
# The linker will fail with missing symbols when you try to use them.
#
# You have to implement those missing symbols yourself to get things working.
# Sometimes you can get away with declaring them as an empty function. 
# But this won't always work.
#
# After you get this bare bone working, the first priority should be to write
# your own memory allocator. A simple sbrk implementation should suffice for
# symbols like __go_new.
#
# For now we just implement the symbols below as empty functions to get this
# barebone up and running.
#

.global __go_register_gc_roots
.type __go_register_gc_roots, @function
__go_register_gc_roots:
	ret
.size __go_register_gc_roots, . - __go_register_gc_roots

.global __go_runtime_error
.type __go_runtime_error, @function
__go_runtime_error:
	ret
.size __go_runtime_error, . - __go_runtime_error

然后你可以使用以下命令汇编 boot.s:

i686-elf-as boot.s -o boot.o

用 Go 编写 Terminal 包

请阅读 向屏幕打印 以了解这段代码的作用。

现在我们创建文件 terminal.go。它是我们的内核将依赖的 "terminal" 包,用于向屏幕打印文本。

package terminal

import "unsafe"

/*
 * Map the text mode video memory into a multi-dimensional array that can be safely
 * used from Go.
 */

func get_vidMem(addr uint32) *[25][80][2]byte {
	buff := (*[25][80][2]byte)(unsafe.Pointer(uintptr(addr)))
	return buff	
}

/*
 * This isn't a tutorial on the language itself so the rest should make sense to you.
 */

const (
	Black        = 0
	Blue         = 1
	Green        = 2
	Cyan         = 3
	Red          = 4
	Magenta      = 5
	Brown        = 6
	LightGrey    = 7
	DarkGrey     = 8
	LightBlue    = 9
	LightGreen   = 10
	LightCyan    = 11
	LightRed     = 12
	LightMagenta = 13
	LightBrown   = 14
	White        = 15
)

var Column, Row int
var Color byte
var vidMem *[25][80][2]byte

func Init() {
	vidMem = get_vidMem(0xB8000)
	Color = MakeColor(LightGrey, Black)
	Column = 0
	Row = 0
}

func MakeColor(fg, bg byte) byte {
	return fg | bg<<4
}

func ScrollUp() {
	for x := 1; x < 25; x++ {
		vidMem[x-1] = vidMem[x]
	}
	Row = 24
}

func Clear() {
	for r := 0; r < 25; r++ {
		for c := 0; c < 80; c++ {
			vidMem[r][c][0] = 32
			vidMem[r][c][1] = Color
		}
	}
}

func Poke(c rune) {
	if c == '\n' {
		Column = 0
		Row++
		if Row > 24 {
			ScrollUp()
		}
	} else {
		vidMem[Row][Column][0] = byte(c)
		vidMem[Row][Column][1] = Color
		Column++
		if Column > 79 {
			Column = 0
			Row++
			if Row > 24 {
				ScrollUp()
			}
		}
	}
}

func Print(s string) {
	for c := 0; c < len(s); c++ {
		Poke(rune(s[c]))
	}
}

使用以下命令编译:

i686-elf-gccgo -static -Werror -nostdlib -nostartfiles -nodefaultlibs -c terminal.go -o terminal.go.o

导入的包是如何被找到的

当你使用 gccgo 导入一个包时,它会在以下文件中查找导入数据,并使用找到的第一个。

  • .gox
  • .so
  • .a
  • .o

.gox 文件仅包含导入数据。如果你想从我们的 terminal.go.o 目标文件中提取它,我们使用:

i686-elf-objcopy -j .go_export terminal.go.o terminal.gox

用 Go 编写内核

现在我们创建文件 kernel.go,其中包含 Main() 函数,该函数由我们上面已经创建并编译的引导汇编调用。它将导入我们也已创建并编译的 terminal 包。然后我们使用该包向屏幕打印文本。

package kernel

import "terminal"

func Main() {
	terminal.Init()                      // Initialize terminal
	terminal.Color = terminal.MakeColor( // Set color to..
		terminal.White, // White text...
		terminal.Blue)  // on a blue background
	terminal.Clear() // Clear screen

	// Center the text a little
	terminal.Row = 11
	terminal.Column = 30

	// Print our Hello, World!
	terminal.Print("Hello, Kernel World!\n")
}

使用以下命令编译:

i686-elf-gccgo -static -Werror -nostdlib -nostartfiles -nodefaultlibs -c kernel.go -o kernel.go.o

链接内核

现在我们创建文件 linker.ld,它将作为指令用于把我们的目标文件链接成最终的内核程序,供引导加载程序使用。

/* The bootloader will look at this image and start execution at the symbol
   designated as the entry point. */
ENTRY(_start)

/* Tell where the various sections of the object files will be put in the final
   kernel image. */
SECTIONS
{
	/* Begin putting sections at 1 MiB, a conventional place for kernels to be
	   loaded at by the bootloader. */
	. = 1M;

	/* First put the multiboot header, as it is required to be put very early
	   early in the image or the bootloader won't recognize the file format.
	   Next we'll put the .text section. */
	.text BLOCK(4K) : ALIGN(4K)
	{
		*(.multiboot)
		*(.text)
	}

	/* Read-only data. */
	.rodata BLOCK(4K) : ALIGN(4K)
	{
		*(.rodata)
	}

	/* Read-write data (initialized) */
	.data BLOCK(4K) : ALIGN(4K)
	{
		*(.data)
	}

	/* Read-write data (uninitialized) and stack */
	.bss BLOCK(4K) : ALIGN(4K)
	{
		*(COMMON)
		*(.bss)
		*(.bootstrap_stack)
	}

	/* The compiler may produce other sections, by default it will put them in
	   a segment with the same name. Simply add stuff here as needed. */
}

你可以使用以下命令链接你的内核:

i686-elf-gcc -T linker.ld -o myos.bin -ffreestanding -O2 -nostdlib boot.o terminal.go.o kernel.go.o -lgcc

文件 myos.bin 现在就是你的内核。注意我们链接了 libgcc,它实现了你的交叉编译器所依赖的各种例程。省略它会在将来给你带来问题。

测试你的操作系统(QEMU)

虚拟机对于开发操作系统非常有用,因为它们允许你快速测试代码,并在执行期间访问源代码。否则,你将陷入无休止的重启循环,只会让你烦恼。它们启动非常快,尤其是与我们这样的小型操作系统结合时。

QEMU 支持直接引导 multiboot 内核,而无需使用可引导介质:

qemu-system-i386 -kernel myos.bin

外部链接

来源与翻译说明

本文根据原文快照翻译,保留原有代码、数值、技术限定及历史背景。原文中的命令与运行结果不代表本站已实际执行验证。

原文:Go Bare Bones;离线修订号:30607。对应原文版本

原作者:OSDev Wiki 社区贡献者。原文及引用资料的版权与许可声明继续适用:版权声明 许可说明

评论

暂无评论