Java Primer:用 Java 编写操作系统的演示教程

来源:OSDev Wiki· 阅读原文 ↗
文章封面
难度级别
Difficulty 3.png
高级

这是一个演示教程,展示如何使用 Java 编写操作系统。不过这里描述的方法相当通用——你可以对其他字节码语言(如 .NET)使用类似的方法。此外,本文还包含一个简单的编译器,可以作为任何自定义语言的灵感来源。

作为演示,这里给出的方法极其简单,只做了让捆绑的 Java 代码运行所必需的工作。它无法处理人们期望 Java 能做到的大多数事情。它不以任何形式进行垃圾回收,更不用说支持字符串了。这里提供的代码是刻意限制的,所以你可以稍微玩一下以获得感觉,但不可能扩展此代码来支持该语言的更多关键组件。

把它看作一个一次性原型——它是故意以这种方式编写的,迫使你从头重写一个新的。

支持非原生语言

由于你能从现有编译器借鉴的东西少得多,你实际上要负责整个工具链。大致步骤如下:

  • 定义你的原生 ABI
Java 和 .NET 以字节码形式出现,这些字节码是为与典型基于寄存器的硬件根本不同的机器设计的。你需要理解你平台的汇编,并且必须考虑语言结构应如何转换为原生结构。此示例做的事情之一是遵循 stdcall 约定,因为它比大多数编译器默认的 cdecl 更接近虚拟 Java 机器。
  • 创建字节码到原生代码的编译器
Java 以字节码形式出现,我们需要一种将其转换为原生代码的方法。由于我们同时在编写操作系统,一切都必须提前编译,不能依赖一个期望操作系统已存在的现有运行时。因此,我们编写自己的编译器。作为编译器的一部分,我们包含 org.objectweb.asm,它可以读取 .class 文件,省去我们编写大量代码的工作。
  • 编译编译器
编译器当然也是用 Java 编写的。我们不需要额外的语言来增加后面的引导问题。当然,这个编译器过于简单,永远无法编译它自己。
  • 将托管操作系统编译为字节码
Javac 是用 Java 编写的,所以这显然是后续移植的最佳选择。
  • 将字节码编译为原生汇编
现在我们有了编译器,就可以在所有操作系统类上运行它来生成原生代码。
  • 为必须是非原生的部分创建运行时
Java 是内存安全的,这阻止它实现很多东西。一组最小的启动代码用原生汇编完成。所有与架构相关的东西都必须用汇编完成。你之后需要的一些部分,如内存管理和异常处理,可能也更容易有纯原生部分。
  • 汇编操作系统和运行时
现在我们一切都以机器语言形式存在。我们仍然复用可以复用的部分,在此示例中我们使用 yasm。你以后可以自由地用 Java 编写汇编器。
  • 打包最终的内核二进制文件
这是使用 binutils 完成的。注意链中没有一个 C 编译器,而且,你可以用你的语言构建自己的链接器——它实际上不需要做那么多。


编译器

在字节码语言中,代码运行前有几个步骤。通常你有“那个”编译器,它将你的源文件转换为某种可移植的二进制文件,你还有一个解释器,它读取这些二进制文件并从中执行指令。现代解释器将字节码转换为原生代码,以避免 if(instruction = ...) 这需要几个周期,而你实际想执行的指令否则只需花费你一条 CPU 指令。

在操作系统的情况下,我们需要更进一步。我们可以运行解释器,但那很慢。我们可以在启动时编译为原生代码,但那需要和我们实际想运行的一样多的操作系统。相反,合适的解决方案是提前编译为原生代码,这样我们就可以从一开始直接运行代码。

一门语言的全部内容仍然要处理很多,但对我们的示例来说,只处理整数就足够了。没错,还没有对象!

Java 字节码使用栈进行操作,以及一个局部变量列表。这些不必在同一位置,但由于 x86 只有一个硬件栈,我们将它同时用作局部栈、调用栈和操作栈。使用了一些技巧使这个编译器更容易,反过来,使与 C 的接口变得困难。Java 术语中的局部变量包括函数参数,因此局部变量会围绕返回地址分开。由于调用者不知道所需的存储——它甚至不能免费获得参数数量——被调用函数应该修复这一点。我们也不能把东西放在栈顶之上,因为那以后在中断时会是个大问题。基本上我们把所有参数复制到返回地址的另一边,然后为局部变量腾出一些空间,使它们可以通过 EBP - 4 * slot_number 索引,例如 0 和 1 会是参数,2+ 会是真正的局部变量。

由于在调用者一侧获取参数数量是复杂的事情,我们使用 RET imm 进行被调用者清理,而不是常规的 RET。局部变量也是个复杂的问题,所以我们只保留 8 个的空间,因为你本来就不应该复制这段代码。

// File: compiler/nl/combuster/minijava/Compiler.java
package nl.combuster.minijava;

import org.objectweb.asm.*;
import org.objectweb.asm.tree.*;
import java.util.*;
import java.io.*;

public class Compiler
{
    public static byte[] readEntireFile(String filename)
    {
        File file = new File(filename);
        try 
        {
            FileInputStream input = new FileInputStream(file);
            byte bytes[] = new byte[(int)file.length()];
            input.read(bytes);
            return bytes;
        }
        catch (IOException e)
        {
            throw new RuntimeException("Unable to read file " + file, e);
        }
    }

    public static void writeOutput(String filename, List<String> lines)
    {
        try 
        {
            BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filename)));
            for (String string : lines)
            {
                writer.write(string);
                writer.newLine();
            }
            writer.close();
        }
        catch (IOException e)
        {
            throw new RuntimeException("Unable to write output file " + filename, e);
        }
    }

    public static String decorate(String classname, String method, String signature)
    {
        // make all these assembly-friendly names. Note that the 
        // constructor is for instance called <init>
        return classname.replace("/","_") + "__" + method.replace("<","_").replace(">","_");
    }
    
    public static void jumpgroup(List<String> output, String jumpcode, LabelNode dest)
    {
    	output.add("pop edx");
    	output.add("pop ecx");
    	output.add("cmp ecx, edx");
    	output.add(jumpcode + " .l" + dest.getLabel());
    }

    public static void main(String args[])
    {
        if (args.length != 2) throw new RuntimeException("Usage: compiler input-file output-file");

        ClassNode node = new ClassNode();
        ClassReader reader = new ClassReader(readEntireFile(args[0]));
        reader.accept(node, 0);

        List<String> outputdata = new LinkedList<String>();

        outputdata.add("section .text");

        for (MethodNode method : node.methods)
        {
            method.visitCode();
            String methodname = decorate(node.name, method.name, method.signature);

            if ((method.access & Opcodes.ACC_NATIVE) != 0) continue;

            // prologue
            System.out.println("; attributes: " + method.attrs);
            outputdata.add("global " + methodname);
            outputdata.add(methodname + ":");
            outputdata.add("push ebp");
            outputdata.add("mov ebp, esp");

            int locals = (method.localVariables == null) ? 0 : method.localVariables.size();
            outputdata.add("; locals: + " + locals);
			int arguments = (method.parameters == null) ? 0 : method.parameters.size();
            if ((method.access & Opcodes.ACC_STATIC) == 0) arguments++; // hidden "this"
            outputdata.add("; params: + " + arguments);
            // copy params so that they correspond with java indexing and join with the local numbering
			for (int i = 0; i < arguments; i++)
            {
                outputdata.add("push dword [ebp + " + (8 + 4 * i) + "]");
            }
            // do some frame checking for many variables, locals is not of much use...
            outputdata.add("sub esp, 32");

            Iterator<AbstractInsnNode> iterator = method.instructions.iterator();
            while (iterator.hasNext())
            {     
                AbstractInsnNode insn = iterator.next();
                int opcode = insn.getOpcode() & 0xff;
                outputdata.add("    ; " + opcode + " = " + insn.getClass().getSimpleName());
                //outputdata.add("mov byte [" + (0xb8000 + 156) + "], '0' + " + (opcode % 10));
                //outputdata.add("mov byte [" + (0xb8000 + 154) + "], '0' + " + (opcode / 10)%10);
                //outputdata.add("mov byte [" + (0xb8000 + 152) + "], '0' + " + (opcode / 100));
                
                if (insn instanceof LabelNode)
                {
                    LabelNode labelinsn = (LabelNode)insn;
                    outputdata.add(".l" + labelinsn.getLabel());
                }
                else if (insn instanceof LineNumberNode)
                {
                    // ignore these
                }
                else if (insn instanceof VarInsnNode)
                {
                    // copy a variable
                    VarInsnNode varinsn = (VarInsnNode) insn;
                    switch(varinsn.getOpcode())
                    {
                        case Opcodes.ILOAD:
                        case Opcodes.ALOAD:
                            // todo: verify offset
                            outputdata.add("push dword [ebp - " + (4 + 4 * varinsn.var) + "]");
                            break;
                            
                        case Opcodes.ISTORE:
                        case Opcodes.ASTORE:
                            outputdata.add("pop dword [ebp - " + (4 + 4 * varinsn.var) + "]");
                            break;

                        default:
                            outputdata.add("Can't deal with varinsnnode: " + varinsn.getOpcode());
                    }
                }
                else if (insn instanceof MethodInsnNode)
                {
                    MethodInsnNode methodinsn = (MethodInsnNode) insn;
                    String calledmethod = decorate(methodinsn.owner, methodinsn.name, methodinsn.desc);
                    outputdata.add("extern " + calledmethod);
                    outputdata.add("call " + calledmethod);
                    if (!methodinsn.desc.endsWith("V"))
                    {
                        // not a void return value
                        outputdata.add("push eax");
                    }
                    /*switch (methodinsn.getOpcode())
                    {
                        default:
                            outputdata.add("Can't deal with methodcall: " + methodinsn.getOpcode());
                    }*/
                }
                else if (insn instanceof IntInsnNode)
                {
                	IntInsnNode intinsn = (IntInsnNode)insn;
                    switch(intinsn.getOpcode())
                    {
                        case Opcodes.BIPUSH:
                            outputdata.add("push " + intinsn.operand);
                            break;

                        default:
                            outputdata.add("Can't deal with intinsnnode: " + intinsn.getOpcode());
                    }
                	
                }
                else if (insn instanceof JumpInsnNode)
                {
                	JumpInsnNode jmpinsn = (JumpInsnNode)insn;
                	
                    switch(jmpinsn.getOpcode())
                    {
                    	case Opcodes.IF_ICMPEQ:		jumpgroup(outputdata, "je", jmpinsn.label); 	break; // 159
                    	case Opcodes.IF_ICMPNE:		jumpgroup(outputdata, "jne", jmpinsn.label); 	break; // 160                    	
                    	case Opcodes.IF_ICMPLT:		jumpgroup(outputdata, "jb", jmpinsn.label); 	break; // 161
                    	case Opcodes.IF_ICMPGE:		jumpgroup(outputdata, "jae", jmpinsn.label); 	break; // 162
                    	case Opcodes.IF_ICMPGT:		jumpgroup(outputdata, "ja", jmpinsn.label); 	break; // 163
                    	case Opcodes.IF_ICMPLE:		jumpgroup(outputdata, "jbe", jmpinsn.label);	break; // 164
                    
                        case Opcodes.GOTO: // 167
                            outputdata.add("jmp .l" + jmpinsn.label.getLabel());
                            break;

                        default:
                            outputdata.add("Can't deal with jumpinsnnode: " + jmpinsn.getOpcode());
                    }
                }   
                else if (insn instanceof LdcInsnNode)
                {
                	LdcInsnNode ldcinsn = (LdcInsnNode) insn;
                	if (ldcinsn.cst instanceof Integer)
                	{
                		outputdata.add("push " + ldcinsn.cst.toString());
                	}
                	else
                	{
	                	outputdata.add("Can't deal with data in ldcinsnnode (" + ldcinsn.getOpcode() +"): " + ldcinsn.cst.getClass().getSimpleName());
                	}
                }             
                else if (insn instanceof IincInsnNode)
                {
                	IincInsnNode incinsn = (IincInsnNode) insn;
                	switch (incinsn.getOpcode())
                	{	
                	    case Opcodes.IINC:
                	    	outputdata.add("add dword [ebp - " + (4 + 4 * incinsn.var) + "], " + incinsn.incr);
                	    	break;
                		default:
                			outputdata.add("Can't deal with iincinsnnode: " + incinsn.getOpcode());                			
                	}
                	
                }
                else if (insn.getOpcode() >= Opcodes.ICONST_M1 && insn.getOpcode() <= Opcodes.ICONST_5) // 2...8
                {
                    outputdata.add("push " + (insn.getOpcode() - Opcodes.ICONST_M1 - 1));
                }
                else if (insn.getOpcode() == Opcodes.IADD) // 96
                {
                	outputdata.add("pop edx");
                	outputdata.add("add [esp], edx");
                }
                else if (insn.getOpcode() == Opcodes.IMUL) // 104
                {
                	outputdata.add("pop eax");
                	outputdata.add("pop ecx");
                	outputdata.add("imul ecx"); // eax:edx = eax * ecx
                	outputdata.add("push eax");
                }                
                else if (insn.getOpcode() == Opcodes.I2B) // 145
                {
                	outputdata.add("and dword [esp], 0xff");
                }
                else if (insn.getOpcode() == Opcodes.RETURN)	// 177
                {
                	outputdata.add("xor eax, eax");
                }
                else if (insn instanceof FrameNode)
                {
                    outputdata.add("; framenode");
                }
                else
                {
                    outputdata.add("Can't deal with " + insn.getClass().getSimpleName() + ", fix it (" + insn.getOpcode() + ")");
                }
            }

            // epilogue, stdcall to save complexity on decoding methodinsns
            outputdata.add("leave");
            outputdata.add("ret " + arguments);
        }

        writeOutput(args[1], outputdata);
    }
}

是的,这就是一个神奇的 256 行代码的编译器。结果是 Intel 语法汇编,因为已经存在处理对象格式的不错的汇编工具。当然你以后也可以自己写。

HAL 和运行时

几乎没有任何编程语言具有标准构造来处理处理器能做的所有事情,尤其是那些被设计为可移植且内存安全的语言。因此,我们必须在语言之外添加对此的支持。幸运的是,Java 确实带有一个专门设计用来将语言包装到平台特定细节的构造:native

// File: os/nl/combuster/minijavaos/Hal.java
package nl.combuster.minijavaos;

public class Hal
{
    public static native void poke(int address, byte data);
}

在某个时刻操作系统需要不安全地访问内存,这就是我们将使用的方法。native 关键字也意味着在 Java 中没有实现,它将来自别处。

还有更多事情可能在纯 Java 中难以完成:此示例完全省略了内存管理,但仍有一个怪癖:每个对象都继承自 java.lang.Object。更复杂的是,编译器不允许我们用 Java 编写 java.lang 类。在这种情况下,这是一个特别的鸡生蛋问题:我们甚至如何编译一个扩展自身的类?我们在某种程度上被迫特殊对待 java.lang.Object,基本上使用它的构造函数作为构造函数链的终止符。在稍后阶段,我们甚至可能想在那里做更多事情,但现在我们不需要。第一段原生支持代码处理这些问题:

; File: os/hal.asm
section .text

global java_lang_Object___init_
global nl_combuster_minijavaos_Hal__poke

java_lang_Object___init_:
	ret

nl_combuster_minijavaos_Hal__poke:
	mov eax, [esp+8]
	mov dl, [esp+4]
	mov [eax], dl
	ret 2

一个原始的内核

“Hello world!” 是一个被高估的东西。是吗?字符串在 Java 中是完整的对象,而安全传递对象是编译器本身跳过的事情之一。相反,我们可以数数来展示我们实际拥有的东西确实有效:

package nl.combuster.minijavaos;

public class Kernel
{
    public Kernel(int arg1)
    {
    }

    public static void kmain()
    {            
    	
        for (int i = 0; i < 10; i++)
        {
            Hal.poke(0xB8000 + 2 * i,     (byte) ('0' + i));
            Hal.poke(0xB8000 + 2 * i + 1, (byte) 0x1F); 
        }                
    }
}

这不过是一些简单的 VGA 代码,但它演示了我们可以调用 Java 代码,做一些计算,然后调用我们的硬件抽象层来完成 Java 刚刚做不到的小部分。

把所有东西包装在一起

我们需要做的最后一件事是把所有部分粘合在一起,并在其上贴一个引导加载程序。Bare Bones 对这个过程有更详细的描述。你可能已经注意到上面源文件中的完整文件名,基本上我们有两个相当紧密交织的项目,位于 compiler 和 os 子文件夹中,它们同时充当 Java 源根。添加了一个 build 文件夹,这样你可以简单地删除该文件夹重新开始,而不必担心在真正的源文件之间找到所有中间文件。特别是,没有它我们将无法分辨哪个 .asm 文件是原始的,哪个是编译器输出的!

Multiboot

我们使用 GRUB 作为引导加载程序,所以机制是相同的。唯一的真正区别是我们必须处理名称修饰,并且无法调用名为 kmain 的东西。

; File: os/multiboot.asm

; Declare constants used for creating a multiboot header.
MBALIGN     equ  1<<0                   ; align loaded modules on page boundaries
MEMINFO     equ  1<<1                   ; provide memory map
FLAGS       equ  MBALIGN | MEMINFO      ; this is the Multiboot 'flag' field
MAGIC       equ  0x1BADB002             ; 'magic number' lets bootloader find the header
CHECKSUM    equ -(MAGIC + FLAGS)        ; checksum of above, to prove we are multiboot
 
; Declare a header as in the Multiboot Standard.
section .multiboot
align 4
	dd MAGIC
	dd FLAGS
	dd CHECKSUM
 
; We'll need a stack
section .bootstrap_stack, nobits
align 4
stack_bottom:
resb 16384
stack_top:
 
; Kernel entry point
section .text
global _start
_start:
	mov esp, stack_top

	extern nl_combuster_minijavaos_Kernel__kmain
	call nl_combuster_minijavaos_Kernel__kmain
 
	cli
.hang:
	;hlt
	jmp .hang

链接器脚本

链接也使用与 Bare Bones 相同的脚本

/* File: os/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. */
}

GRUB

一些 GRUB legacy 的配置文件。用 CD 做这件事是最简单的方式,真的:

# 
# File: os/grub.cfg
#
default 0
timeout 30

# For booting GNU/Linux
title Java OS 
root (cd)
kernel (cd)/kernel

构建说明

为了简化事情,这里是将所有步骤粘合在一起的 Makefile。这个更详细一些,因为它涵盖了几乎所有需要的中间步骤。编译编译器,制作可执行的 jar 文件,将 java 文件编译为 class 文件,再到汇编文件,再到对象文件,再到 ELF 二进制文件。在过程中途包含运行时,然后用 GRUB 构建 CD 镜像。

在本例中,假定 GRUB 已预安装在 /boot 中,在安装了 GRUB 的 Linux 系统上它默认位于该目录。我们还需要 mkisofs 以及 GCC 交叉编译器 中的 binutils 步骤。当然,在某个时候你也可以决定用 Java 来编写这些工具。

COMPILER_J=$(shell find -L compiler -iname '*.java')
COMPILER_C=$(addprefix build/,$(patsubst %.java,%.class,$(COMPILER_J)))

OS_J:=$(shell find -L os -iname '*.java')
OS_C:=$(addprefix build/,$(patsubst %.java,%.class,$(OS_J)))
OS_A:=$(patsubst %.class,%.asm,$(OS_C)) 
RT_A:=$(shell find -L os -iname '*.asm')
OS_O:=$(patsubst %.asm,%.o,$(OS_A))
RT_O:=$(addprefix build/,$(patsubst %.asm,%.o,$(RT_A)))

default: build/compiler.jar build/kernel build/image.iso
	echo done compiling

.PHONY: default

build/.dir: 
	mkdir -p build/compiler
	mkdir -p build/os
	touch build/.dir

build/compiler.jar: $(COMPILER_C) compiler/compiler.manifest
	jar cvfm $@ compiler/compiler.manifest -C build/compiler .

build/compiler/%.class: compiler/%.java build/.dir
	javac -d build/compiler -sourcepath compiler $<

build/os/%.class: os/%.java build/.dir
	javac -d build/os -sourcepath os $<

%.asm:%.class build/compiler.jar
	java -jar build/compiler.jar $< $@

%.o:%.asm
	yasm -f elf -o $@ $<

build/os/%.o: os/%.asm build/.dir
	yasm -f elf -o $@ $<

build/kernel: $(OS_O) $(RT_O)
	i586-elf-ld -o $@ -T os/linker.ld $(OS_O) $(RT_O)

build/image.iso: build/kernel os/grub.cfg Makefile
	-rm -rf build/iso
	mkdir -p build/iso/boot/grub
	cp build/kernel build/iso/
	cp os/grub.cfg build/iso/boot/grub/menu.lst
	cp /boot/grub/stage2_eltorito build/iso/boot/grub/
	mkisofs -R -b boot/grub/stage2_eltorito -no-emul-boot -boot-load-size 4 -boot-info-table -o $@ build/iso

如果你留意了,就会注意到 JAR 步骤需要一个位于 compiler/compiler.manifest 的清单文件。它实际上只是将其标记为可运行,以便我们可以方便地使用它:

Main-Class: nl.combuster.minijava.Compiler

最后,一个库 是我们的编译器用来完成大部分魔法的库。你只需将源代码复制到 compiler 文件夹中,构建脚本就会自动拾取它。

来源与翻译说明

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

原文:Java Primer;离线修订号:28229。

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

评论

暂无评论