10

不想做任何这样的事情,但出于好奇,我想知道是否可以在 C 中实现“整个操作系统”(不一定像 Linux 或 Microsoft Windows 那样大,但更像是类似 DOS 的小型操作系统)和/或 C++ 不使用或使用很少的程序集。

通过实现一个操作系统,我的意思是从头开始制作一个操作系统,启动引导加载程序和内核,再到 C 或 C++ 中的图形驱动程序(以及可选的 GUI)。我已经看到通过编译器访问低级功能在 C++ 中完成了一些低级的事情。这可以为整个操作系统完成吗?

我不是在问这是否是一个好主意,我只是在问它是否有可能?

4

3 回答 3

11

OSDev wiki 的强制性链接,它描述了创建操作系统所需的大部分步骤,如 x86/x64 中所述。

要回答您的问题,创建引导加载程序并启动保护模式而不诉诸于至少一些程序集将是非常困难/不愉快的,尽管它可以保持在最低限度(特别是如果您没有真正计算像使用这样的东西__asm__ ( "lidt %0\n" : : "m" (*idt) );作为“组装”)。

一个很大的障碍(同样在 x86 上)是处理器以 16 位实模式启动,因此您需要一些 16 位代码。根据这个讨论,您可以让 GCC 生成 16 位代码,但您仍然需要一些方法来设置内存、从某些存储介质加载代码等等,所有这些都需要以标准 C 的方式与硬件进行接口。没有(中断、IO 端口等)的概念。

对于仅通过内存映射 IO 与硬件通信的体系结构,您可能会在纯 C 中编写除 C 启动代码(设置堆栈、初始化变量等)之外的所有内容,尽管中断例程的特定要求/异常或系统调用门等可能难以实现(因为您必须访问特殊的 CPU 寄存器)。

于 2011-07-21T14:49:44.827 回答
4

我假设你有一个 x86 的操作系统。在这种情况下,您至少需要几页汇编程序来设置保护模式和类似的东西,除此之外,还有很多关于分页、调用门、响铃、异常等所有东西的知识。如果你要使用一种系统调用形式,您还需要几行汇编代码来在内核模式和用户空间模式之间切换。

除了这些之外,操作系统的其余部分可以很容易地用 C 编程。对于 C++,你需要一个运行时环境来支持虚拟成员和异常之类的东西,但据我所知,它们都可以用 C 编程。

Just take a look at Linux kernel source, the most important assembler code (for x86) can be found in arch/x86/boot, but you'll notice that even in that directory most files are written in C. Furthermore you'll find a few assembly lines in the arch/x86/kernel directory for handling system calls and stuff like that.

Outside the arch directory there is hardly any assembler used (because assembler is machine specific, that machine specific code belongs in the arch directory). Even graphic drivers don't use assembler (e.g. nvidia driver in drivers/gpu/drm/nouveau).

于 2011-07-21T15:16:16.253 回答
0

A boot loader? You might want to skip that bit. For instance, Linux is quite often started by non-Linux boot loaders such as UBoot. After all, once the system is running, the OS will be present but not the boot loader, that's just there to get the OS proper into memory.

And once you've selected a decent existing bootloader, the remainder is pretty much all straightforward. Well, you have to deal with memory and files yourself; you can't rely on fopen obviously. But even a C++ compiler has little problem generating code that can run without OS support.

于 2011-07-22T08:39:46.670 回答