C++ 内核开发:运行时支持、全局对象、new/delete、RTTI、异常与标准库移植

来源:OSDev Wiki· 阅读原文 ↗
文章封面
关于让一个基础的 C++ 内核运行起来的快速教程,请参阅 Bare Bones

内核可以用 C++ 编程,它与用 C 编写内核非常相似,只是有几个陷阱你必须考虑(运行时支持、构造函数……)。本页不会列出这种方法的任何(优)缺点,而是说明你需要做什么来让一切启动起来。

C++ 提供的许多特性可以即开即用;它们不需要额外的支持或代码就能正确使用(例如模板、类、继承、虚函数)。然而 C++ 的其他部分确实需要运行时支持,本文将对此进行讨论。

简介

如果你已经按照 Bare Bones 文章中的说明创建了一个 C++ 内核,那么许多 C++ 特性已经可用并且开箱即用。然而,你的内核还不满足 ABI,而且即使你只使用 C 和 C++ 的交集,也不能保证编译器不会生成有问题的代码。特别是,你可能需要初始化更多的 CPU 状态来启用浮点寄存器和指令,因为编译器完全有理由认为浮点寄存器和指令默认是可用的。

然而,编译器会假设所有 C++ 运行时支持默认都是可用的,但你并没有将 libsupc++ 链接到你的 C++ 内核中,而它实现了必要的运行时支持。这就是为什么你要向交叉编译器传递 -fno-rtti 和 -fno-exceptions,以使这些运行时特性不可用。更进一步,你应该将 libsupc++ 链接到你的内核中,但目前据知对于刚开始进行操作系统开发的人来说它并不容易获取,而且 GCC 构建过程默认不会为裸 -elf 平台正确地交叉编译它。

你还需要按照 Calling Global Constructors 中的说明调用全局构造函数,以满足 ABI 关于正确调用程序初始化任务的要求。

纯虚函数

如果你想使用纯虚函数,你的编译器需要一个单一的支持函数。它只在无法进行纯虚函数调用时被调用(例如,如果你覆盖了某个对象的虚函数表)。但尽管如此,如果你使用纯虚函数却没有提供这个支持例程,你的链接器仍会抱怨存在未解析的符号。

在 GCC 中启用纯虚函数相当简单。你所要做的就是把下面的函数添加到你的某个 C++ 源文件中(并确保它被链接进去)。没有必要先声明这个函数,仅定义对 GCC 来说就足够了。这个函数本身甚至不需要做任何事情(在大多数实现中它也确实什么都不做),它只需要“存在”以备不时之需。

下面你会找到 GCC 中的实现示例。

extern "C" void __cxa_pure_virtual()
{
    // Do nothing or print an error message.
}

或者,如果你碰巧使用 Visual Studio:

int __cdecl _purecall()
{
    // Do nothing or print an error message.
}

如果在运行时,你的内核检测到无法进行对纯虚函数的调用,它会调用上述函数。这些函数实际上永远不应该被调用,因为如果没有 hack,或者通过内核的未定义行为,是不可能实例化一个没有定义所有纯虚函数的类的。

全局对象

This page is under construction! 本页或本节仍在编写中,因此可能不完整。其内容可能在不久的将来发生变化。

TODO:请将此信息与较新的 Calling_Global_Constructors 文章统一。

全局对象必须在被使用之前调用其构造函数。通常,它们由启动代码调用(而你刚刚禁用了它)。所以,为了能够使用它们,你必须为它们编写自己的启动代码。所有对象都有构造函数和析构函数。当一个可执行文件被加载到内存中并且程序直接跳转到入口点时,全局对象的构造函数还没有被调用。一个解决方案是手动执行此操作。你可以在你的 C++ 入口点被调用时首先放入这段代码:

	object1.object1();
	object2.object2();
	object3.object3();
	// ...

全局或静态对象必须由环境构造后才能供 C++ 使用。如果全局/静态对象在其构造函数中需要 new 和 delete,则应格外小心。在这种情况下,最好只在你的内核堆准备好使用(并且你可以访问动态内存分配)之后才构造这些对象。不这样做可能导致对象尝试通过无法工作的 new 运算符来分配内存。这还简化了在 __cxa_atexit 中存储析构函数,因为你不必使用静态且固定大小的结构。

GCC

注意:这似乎是 Itanium 平台特有的。对于 IA-32/x86/i386 和 amd64/x86_64,请改为查看 Calling_Global_Constructors。

根据 Itanium C++ Application Binary Interface(g++ 遵循它而 VC++ 不遵循),函数 __cxa_atexit 用于注册一个析构函数,当共享库需要被卸载时应调用它。它应该将一个函数指针(最多带 1 个伴随参数)以及要销毁的对象或共享资源的句柄插入到一个表中。

在 __cxa_atexit 的示例实现中,__atexit_funcs[ATEXIT_MAX_FUNCS] 数组充当该表。这就是为什么 __cxa_atexit 函数被定义为:

int __cxa_atexit(void (*destructor) (void *), void *arg, void *__dso_handle);

这样 destructor 函数指针是析构函数的句柄,而 arg 是它可能接受的单个参数。最后,__dso_handle 是 DSO(动态共享对象)的句柄。

总结一下,为了在你的 C++ 文件中使用全局对象,你需要定义两个函数和一个符号:

void *__dso_handle;

int __cxa_atexit(void (*destructor) (void *), void *arg, void *dso);
void __cxa_finalize(void *f);

在你调用了对象的构造函数之后,GCC 会自动调用该函数

int __cxa_atexit(void (*destructor) (void *), void *arg, void *dso);

这个函数应该保存所有三个参数,如果成功则返回零,失败则返回非零。当你的内核退出时,你应该调用 __cxa_finalize(0)。根据 ABI 规范,用 0 作为参数调用它(而不是一个函数的地址(该函数将被调用并从列表中移除))会导致列表中的 所有 析构函数被调用并从列表中移除。

由于你将在内核退出后立即从你的汇编源代码中调用这个函数,你可以使用以下代码:

; This is NASM source, mind you.
sub esp, 4
mov [esp], dword 0x0

call __cxa_finalize

add esp, 4

以下是经过测试、可运行、注释完整的源代码,它比之前在这里找到的源代码提供了更详细的解释。它还强调了可以实现哪些改进以及可以在哪里插入这些改进。要使用它,只需在你的 C++ 内核源代码的 一个 文件中包含 icxxabi.h(最好是你的内核主语句开始的那个文件)。

文件:icxxabi.h

#ifndef _ICXXABI_H
	#define _ICXXABI_H

	#define ATEXIT_MAX_FUNCS	128
	
	#ifdef __cplusplus
	extern "C" {
	#endif
	
typedef unsigned uarch_t;

struct atexit_func_entry_t
{
	/*
	* Each member is at least 4 bytes large. Such that each entry is 12bytes.
	* 128 * 12 = 1.5KB exact.
	**/
	void (*destructor_func)(void *);
	void *obj_ptr;
	void *dso_handle;
};

int __cxa_atexit(void (*f)(void *), void *objptr, void *dso);
void __cxa_finalize(void *f);

	#ifdef __cplusplus
	};
	#endif

#endif


文件:icxxabi.cpp

#include "./icxxabi.h"

	#ifdef __cplusplus
	extern "C" {
	#endif

atexit_func_entry_t __atexit_funcs[ATEXIT_MAX_FUNCS];
uarch_t __atexit_func_count = 0;

void *__dso_handle = 0; //Attention! Optimally, you should remove the '= 0' part and define this in your asm script.

int __cxa_atexit(void (*f)(void *), void *objptr, void *dso)
{
	if (__atexit_func_count >= ATEXIT_MAX_FUNCS) {return -1;};
	__atexit_funcs[__atexit_func_count].destructor_func = f;
	__atexit_funcs[__atexit_func_count].obj_ptr = objptr;
	__atexit_funcs[__atexit_func_count].dso_handle = dso;
	__atexit_func_count++;
	return 0; /*I would prefer if functions returned 1 on success, but the ABI says...*/
};

void __cxa_finalize(void *f)
{
	uarch_t i = __atexit_func_count;
	if (!f)
	{
		/*
		* According to the Itanium C++ ABI, if __cxa_finalize is called without a
		* function ptr, then it means that we should destroy EVERYTHING MUAHAHAHA!!
		*
		* TODO:
		* Note well, however, that deleting a function from here that contains a __dso_handle
		* means that one link to a shared object file has been terminated. In other words,
		* We should monitor this list (optional, of course), since it tells us how many links to 
		* an object file exist at runtime in a particular application. This can be used to tell 
		* when a shared object is no longer in use. It is one of many methods, however.
		**/
		//You may insert a prinf() here to tell you whether or not the function gets called. Testing
		//is CRITICAL!
		while (i--)
		{
			if (__atexit_funcs[i].destructor_func)
			{
				/* ^^^ That if statement is a safeguard...
				* To make sure we don't call any entries that have already been called and unset at runtime.
				* Those will contain a value of 0, and calling a function with value 0
				* will cause undefined behaviour. Remember that linear address 0, 
				* in a non-virtual address space (physical) contains the IVT and BDA.
				*
				* In a virtual environment, the kernel will receive a page fault, and then probably
				* map in some trash, or a blank page, or something stupid like that.
				* This will result in the processor executing trash, and...we don't want that.
				**/
				(*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr);
			};
		};
		return;
	};

	while (i--)
	{
		/*
		* The ABI states that multiple calls to the __cxa_finalize(destructor_func_ptr) function
		* should not destroy objects multiple times. Only one call is needed to eliminate multiple
		* entries with the same address.
		*
		* FIXME:
		* This presents the obvious problem: all destructors must be stored in the order they
		* were placed in the list. I.e: the last initialized object's destructor must be first
		* in the list of destructors to be called. But removing a destructor from the list at runtime
		* creates holes in the table with unfilled entries.
		* Remember that the insertion algorithm in __cxa_atexit simply inserts the next destructor
		* at the end of the table. So, we have holes with our current algorithm
		* This function should be modified to move all the destructors above the one currently
		* being called and removed one place down in the list, so as to cover up the hole.
		* Otherwise, whenever a destructor is called and removed, an entire space in the table is wasted.
		**/
		if (__atexit_funcs[i].destructor_func == f)
		{
			/* 
			* Note that in the next line, not every destructor function is a class destructor.
			* It is perfectly legal to register a non class destructor function as a simple cleanup
			* function to be called on program termination, in which case, it would not NEED an
			* object This pointer. A smart programmer may even take advantage of this and register
			* a C function in the table with the address of some structure containing data about
			* what to clean up on exit.
			* In the case of a function that takes no arguments, it will simply be ignore within the
			* function itself. No worries.
			**/
			(*__atexit_funcs[i].destructor_func)(__atexit_funcs[i].obj_ptr);
			__atexit_funcs[i].destructor_func = 0;
			
			/*
			* Notice that we didn't decrement __atexit_func_count: this is because this algorithm
			* requires patching to deal with the FIXME outlined above.
			**/
		};
	};
};

	#ifdef __cplusplus
	};
	#endif

Visual C++

主条目: Visual Studio

运行构造函数和析构函数在 MSDN 帮助和 C 运行时库源代码中都有介绍。更多信息请参阅 MSDN 上的 #pragma init_seg。

基本上发生的事情是,根据 init_seg 的值,函数指针被放入 .CRT$XIC, $XIL, $XIU 中。然后链接器将所有内容合并到 .CRT 节中,按照 $ 之后字母的顺序。然后,XIA(xi_a)和 XIZ(xi_z)之间的指针如果非零就会被调用。.CRT 节与 .data 节合并,以避免一个完全独立的节。

C++ 支持的一个问题是糟糕的名称修饰,在 map 文件中根本无法阅读。应该设置一个构建脚本,将 map 文件通过 undname.exe 工具处理,使得像 ??2@YAPAXI@Z(operator new - 我想是……)以及其他符号都是可读的。

下面你会找到一些示例代码。如果你想初始化任何静态对象,只需调用 runInit();如果要运行静态对象的析构函数,则调用 runTerm()。

typedef void (*_PVFV)(void);
typedef int  (*_PIFV)(void);
typedef void (*_PVFI)(int);

#pragma data_seg(".CRT$XIA")
__declspec(allocate(".CRT$XIA")) _PIFV __xi_a[] = {0};
#pragma data_seg(".CRT$XIZ")
__declspec(allocate(".CRT$XIZ")) _PIFV __xi_z[] = {0};
#pragma data_seg(".CRT$XCA")
__declspec(allocate(".CRT$XCA")) _PVFV __xc_a[] = {0};
#pragma data_seg(".CRT$XCZ")
__declspec(allocate(".CRT$XCZ")) _PVFV __xc_z[] = {0};
#pragma data_seg(".CRT$XPA")
__declspec(allocate(".CRT$XPA")) _PVFV __xp_a[] = {0};
#pragma data_seg(".CRT$XPZ")
__declspec(allocate(".CRT$XPZ")) _PVFV __xp_z[] = {0};
#pragma data_seg(".CRT$XTA")
__declspec(allocate(".CRT$XTA")) _PVFV __xt_a[] = {0};
#pragma data_seg(".CRT$XTZ")
__declspec(allocate(".CRT$XTZ")) _PVFV __xt_z[] = {0};
#pragma data_seg()
#pragma comment(linker, "/merge:.CRT=.data")

static _PVFV onexitarray[32];
static _PVFV *onexitbegin, *onexitend;

int __cdecl _purecall()
{
        // print error message
}

int __cdecl atexit(_PVFV fn)
{
        if (32*4 < ((int)onexitend-(int)onexitbegin)+4)
                return 1;
        else
                *(onexitend++) = fn;
        return 0;
}

EXTERN int runInit()
{
        // init the __xi_a to __xi_z:  __initex(__xi_a, __xi_z);
        // init __xc_a to __xc_z
}

static void __init(_PVFV *pfbegin, _PVFV *pfend)
{
    while (pfbegin < pfend)
    {
        if (*pfbegin != 0)
            (**pfbegin)();
        ++pfbegin;
    }
}

static int __initex(_PIFV *pfbegin, _PIFV *pfend)
{
        int ret = 0;

        while (pfbegin < pfend && ret == 0)
        {
            if (*pfbegin != 0)
                ret = (**pfbegin)();
            ++pfbegin;
        }

        return ret;
}

EXTERN void runUninit()
{
        if (onexitbegin)
        {
                while (--onexitend >= onexitbegin)
                        if (*onexitend != 0)
                                (**onexitend)();
        }

        __init(__xp_a, __xp_z);
        __init(__xt_a, __xt_z);
}

EXTERN int onexitinit()
{
        onexitend = onexitbegin = onexitarray;
        *onexitbegin = 0;
        return 0;
}

#pragma data_seg(".CRT$XIB")      // run onexitinit automatically
__declspec(allocate(".CRT$XIB")) static _PIFV pinit = onexitinit;
#pragma data_seg()

局部静态变量(仅限 GCC)

当你声明一个局部静态变量时,GCC 会在该变量的构造函数调用周围放置一个保护。这确保同一时间只有一个线程可以调用构造函数来初始化它。

注意,这些只是为了让代码编译通过的存根,你应该自己实现它们。只需添加一个带有 test-and-set 原语的类似互斥锁的保护即可。

namespace __cxxabiv1 
{
	/* guard variables */

	/* The ABI requires a 64-bit type.  */
	__extension__ typedef int __guard __attribute__((mode(__DI__)));

	extern "C" int __cxa_guard_acquire (__guard *);
	extern "C" void __cxa_guard_release (__guard *);
	extern "C" void __cxa_guard_abort (__guard *);

	extern "C" int __cxa_guard_acquire (__guard *g) 
	{
		return !*(char *)(g);
	}

	extern "C" void __cxa_guard_release (__guard *g)
	{
		*(char *)g = 1;
	}

	extern "C" void __cxa_guard_abort (__guard *)
	{

	}
}

GCC 为调用局部静态变量的构造函数而生成的实际代码大致如下:

static <type> guard;

if (!guard.first_byte)
{
	if (__cxa_guard_acquire (&guard))
	{
		bool flag = false;

		try
		{
			// Do initialization.
			__cxa_guard_release (&guard);

			flag = true;
			// Register variable for destruction at end of program.
		}

		catch
		{
			if (!flag)
			{
				__cxa_guard_abort (&guard);
			}
		}
	}
}

运算符 'new' 和 'delete'

在你能正确使用 new 和 delete 之前,你必须实现某种内存管理。你还必须实现这两个运算符(包括它们的数组对应形式)。new 和 delete 分别分配和删除内存(很像 C 中的 malloc 和 free)。如果你想了解更多关于这个主题的内容,请查看 内存管理 文章。

每次你调用运算符 new、new[]、delete 或 delete[] 时,编译器都会插入对它们的调用。最简单的实现是将它们映射到你的内核的 malloc 和 free。例如:

#include <stddef.h>

void *operator new(size_t size)
{
    return malloc(size);
}

void *operator new[](size_t size)
{
    return malloc(size);
}

void operator delete(void *p)
{
    free(p);
}

void operator delete[](void *p)
{
    free(p);
}

你也可以让 new 使用 calloc(分配并清零)。这样,新分配的内存将始终被清零(因此不包含垃圾数据)。然而标准的 new 实现并不会清除返回的内存。

一个你可以移植到你的操作系统的简单 malloc 实现是 liballoc。它只需要基本的 分页(即存储已使用和空闲页面的列表,并有一个函数来查找下一个空闲页面)即可工作。

Placement New

在 C++ 中(尤其是在结构体可能位于固定地址的操作系统代码中),在别处获得的内存中构造对象可能很有用。这通过一种称为 'placement new' 的技术来实现。例如,假设你想在地址 0x09FFF0000 创建一个 APIC 对象,那么下面这段代码将使用 placement new 来完成:

void *apic_address = reinterpret_cast<void *>(0x09FFF0000);
APIC *apic = new (apic_address) APIC;

为了使用 placement new,你需要在作用域中定义 new 和 delete 运算符的特殊重载。幸运的是,所需的定义很简单,可以内联在头文件中(C++ 标准将它们放在一个名为 new 的头文件中)。

inline void *operator new(size_t, void *p)     throw() { return p; }
inline void *operator new[](size_t, void *p)   throw() { return p; }
inline void  operator delete  (void *, void *) throw() { };
inline void  operator delete[](void *, void *) throw() { };

上面的实现对于分配内存可能不安全,因为你的内核没有将已分配的内存标记为已使用。placement new 几乎从不使用,如果你想从内存中的指定地址读取一个对象,通常更容易的做法是创建一个指向该地址的指针。

你永远不会显式调用 placement delete(它只是出于某些实现细节的原因才需要)。相反,你只需显式调用对象的析构函数。

apic->~APIC();

RTTI(运行时类型信息)

RTTI 用于 typeid 和 dynamic_cast。它也需要运行时支持。用 -fno-rtti 禁用它。内核无法访问运行时特性,这些特性很可能依赖于操作系统。注意,虚函数在没有 RTTI 的情况下也能工作。

异常

另一个需要运行时支持的特性。用 -fno-exceptions 禁用它。异常需要代码在栈展开的同时寻找合适的异常处理程序来处理异常。通常,这段代码会与你的 C++ 应用程序链接在一起,但在独立内核中,这段代码必须手动提供。

参见 C++ 异常支持。

标准库

注意,C++ 标准库(stdlib)与 C++ 标准模板库(STL)不同。STL 是在 1994 年设计的,并在很大程度上影响了 C++ 标准库,但它不是 ISO C++ 标准的一部分。然而,C++ 标准库是 C++ ISO 规范的一部分,也是你使用 std::vector、std::string 等时所使用的东西。要警惕误用 STL 这个术语,最好完全避免使用它。使用它的人几乎肯定指的是 C++ stdlib。

在移植 stdlib 实现之前,你无法使用 stdlib 函数或类。许多依赖 stdlib 的现有代码是依赖于操作系统的,所以如果你想使用它们,必须将 stdlib 实现移植到你的操作系统。

要在你的操作系统中获得 stdlib 访问权限,你可以执行以下任一操作:

  • 自己实现几个必需的类模板(std::string、std::list、std::cout 等)。
  • 将 stdlib 实现移植到你的操作系统(例如 STLport)。

许多 stdlib 类要求你的操作系统中已实现 new 和 delete。文件访问要求你的操作系统支持读取和写入的封装。控制台函数要求你的操作系统已经有可用的控制台 I/O。

移植 C++ stdlib(就像移植 C 标准库一样)并不会自动使你的操作系统能够从磁盘读取和写入或直接从键盘获取数据。这些只是你的操作系统函数的封装,必须由你的内核实现。

注意,通常不建议将整个 stdlib 移植到你的内核,尽管如果你愿意的话,移植几个类模板(如 std::vector 和 std::string)是合理的。至于你的用户应用程序:越多越好!:)

以下是最常用的 stdlib 实现列表:

使用 libgcc 和 libsupc++ 的完整 C++ 运行时支持

主条目: Libsupcxx#Full C++ Runtime Support Using libgcc And libsupc++

如果你想要异常、RTTI、new 和 delete 全部功能,你应该使用 libgcc 和 libsupc++。libgcc 包含展开器(用于异常),而 libsupc++ 包含 C++ 支持。

你可能会遇到 libsupc++ 的问题,但还有 替代库。

优化

有 关于优化你应该了解的事项,这些也会影响 C++,因为它是 C 语言的扩展。即使你近期不打算使用 C++ 编译器的优化器,也应该了解这些内容。

链接

Wiki

来源与翻译说明

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

原文:C++;离线修订号:30364。对应原文版本

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

评论

暂无评论