从源码看 C++ 异常

简述

什么是 C++ 异常机制?

如代码所示,你是否比较好奇:

  • 当 try 代码块中触发了 throw,它是如何寻找到对应的 catch 代码块的,尤其是调用层级很深的情况?
  • 由于 throw 改变了代码流程,try 块中的对象 r 是否能得到正常释放?
  • 如果方法调用层级包含了不同的语言,例如 C -> C++ -> C -> C++,但 C 语言并不支持异常处理,那么上面的代码是否还能正常执行?
  • 你在平时的开发过程中是否遇到过无法 catch 的情况?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct RAII {
~RAII() { printf("RAII object has been destroyed\n"); }
};

void catchit() {
try {
RAII r;
throw Exception();
} catch(Exception&) {
printf("Caught an Exception!\n");
}
}

// output
RAII object has been destroyed
Caught an Exception!

本文将从源码角度来逐步阐述这些问题。

C++ 异常机制的设计理念

异常处理是许多高级语言都具有的特性,它可以直接中断当前函数并将控制权转交给能够处理异常的函数。C++ 之父 Bjarne Stroustrup 在《The C++ Programming Language》中讲到:一个库的作者可以检测出发生了运行时错误,但一般不知道怎样去处理它们(因为和用户具体的应用有关);另一方面,库的用户知道怎样处理这些错误,但却无法检查它们何时发生。提供异常的基本目的就是为了处理上面的问题,其基本思想是:让一个函数在发现了自己无法处理的错误时抛出(throw)一个异常,然后它的(直接或者间接)调用者能够处理这个问题,核心就是将问题检测和问题处理相分离。所以,异常处理的核心不在异常,而在处理。不管抛出的是什么异常,它只是一个信息承载的方式,异常处理最关键的是如何把这个异常传递给能够处理它的人。还有最重要的一点,在这个过程中把现场“清理干净”。

有哪些 C++ 异常实现机制?

到目前为止,有多种 C++ 异常实现机制。

从源码看 C++ 异常:有哪些 C++ 异常实现机制?(图 1)
  • SJLJ 主要用于较老的系统或者嵌入式系统,其优点是实现简单,但效率较低;
  • EHABI 则主要用于 ARM32 架构,其特点是与 ARM32 架构紧密结合,性能较好。
  • DWARF CFI 则是目前应用最广泛的机制,其效率和功能都比较均衡(本文重点)
  • 除此之外,Compact Unwind(表格比较老,无该项)是苹果平台的专属优化,只能做简单的栈展开,不能处理异常匹配、清理代码等复杂场景,遇到复杂情况时,系统会自动回退到功能完整的 DWARF CFI

C++ 异常机制分层

Itanium C++ ABI:异常处理分为一级基础 ABI 和二级 C++ ABI。

一级基础 ABI 用于堆栈展开、异常处理和回调的库,提供了一种跨平台的 API 来处理堆栈展开,其 API 形式为 Unwind*。常见实现有 libgcc 和 libunwind。

  • 允许捕获和恢复程序执行上下文,并支持函数调用栈的展开。
  • 在异常处理和调试过程中,能够访问调用栈信息。

二级 C++ ABI 主要负责为 C++ 标准库提供应用二进制接口(ABI)支持,特别是在异常处理和运行时类型识别 (RTTI) 方面。其 API 形式是 __cxa_*,常见的实现方式有:libsupc++ 和 libc++abi。

  • 实现了 C++ 异常处理中的关键功能,如 __cxa_throw、__cxa_rethrow、__gxx_personality_v0 等。
  • 提供动态类型信息的支持,例如 typeinfo 和 dynamic_cast。

关于 C++ Itanium ABI,主要分为四大板块(本文讨论的就是板块三) 内存布局(Data Layout) 调用约定(Calling Convention) 异常处理机制(Exception Handling) 定义输入到链接器的对象文件的格式(Linkage & Object Files)

异常机制概览

从源码看 C++ 异常:异常机制概览(图 2)

该图简要地描述了 C++ 异常机制的处理流程,例如 __cxa_throw、_Unwind_RaiseException、unwind_phase1、unwind_phase2、landingpad 等,以及所依赖的各种数据信息,例如 eh_frame、unw_proc_info_t、CIE、FDE、exception table、call site table、action table 等。接下来将从抛出异常、栈回溯、捕获异常 3 个阶段详细阐述 C++ 异常的实现机制,期间会对这里的各种概念进行阐述。

  1. 为了突出重点,本文的很多参考源码(来自 llvm-project)都有一定程度的代码删减
  2. 和平台相关的,本文主要针对 ARM64 架构,例如一些汇编代码

抛出异常

__cxa_allocate_exception

当用户代码使用 throw 抛出一个异常时,代码首先流转到 __cxa_allocate_exception。该方法负责申请一块内存,该空间会包含一个 exception header,用来存储一些 C++ ABI 需要的信息,偏移后的空间用来存储用户数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
void *__cxa_allocate_exception(size_t thrown_size) throw() {
size_t actual_size = cxa_exception_size_from_exception_thrown_size(thrown_size);
// Allocate extra space before the __cxa_exception header to ensure the
// start of the thrown object is sufficiently aligned.
size_t header_offset = get_cxa_exception_offset();
char *raw_buffer = (char *)__aligned_malloc_with_fallback(header_offset + actual_size);
if (NULL == raw_buffer) std::terminate();
__cxa_exception *exception_header = static_cast<__cxa_exception *>((void *)(raw_buffer + header_offset));
// We warn on memset to a non-trivially castable type. We might want to
// change that diagnostic to not fire on a trivially obvious zero fill.
::memset(static_cast<void*>(exception_header), 0, actual_size);
return thrown_object_from_cxa_exception(exception_header);
}

这里看起来是一个简单的内存分配,但其中的机制远比想象的复杂:当一个异常被抛出时,会对栈进行一些操作,所以在栈上进行分配可能不是个好主意。同时,在堆上分配内存可能也不是个好主意,因为可能需要在内存耗尽的情况下抛出异常。静态分配也不是一个好主意,因为我们需要这个操作是线程安全的(否则,如果两个线程同时抛出异常,那就麻烦了)。考虑到这些限制,大多数实现似乎都是在本地线程存储(堆)上分配内存,但如果内存耗尽,就会使用紧急存储(可能是静态的)

__cxa_throw

当完成异常内存申请后,代码流转到 __cxa_throw,它首先完成 __cxa_exception 结构体的初始化,然后将异常压入异常管理栈 __cxa_eh_globals 中,最后调用 _Unwind_RaiseException。

1
2
3
4
5
6
7
8
9
10
11
void
__cxa_throw(void *thrown_object, std::type_info *tinfo, void (_LIBCXXABI_DTOR_FUNC *dest)(void *)) {
__cxa_eh_globals* globals = __cxa_get_globals();
globals->uncaughtExceptions += 1; // Not atomically, since globals are thread-local
__cxa_exception* exception_header = __cxa_init_primary_exception(thrown_object, tinfo, dest);
exception_header->referenceCount = 1; // This is a newly allocated exception, no need for thread safety.
_Unwind_RaiseException(&exception_header->unwindHeader);
// This only happens when there is no handler, or some unexpected unwinding
// error happens.
failed_throw(exception_header);
}

这里需要注意下 __cxa_exception、_Unwind_Exception 和 exception_obj 的内存分布,后文中将会看到一些指针转换的操作,例如:__cxa_exception* exception_header = (__cxa_exception*)(unwind_exception + 1) - 1,将一个 unwind_exception 类型的指针转换为一个 __cxa_exception 类型的指针。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct __cxa_exception { 
std::type_info * exceptionType;
void (*exceptionDestructor) (void *);
unexpected_handler unexpectedHandler;
terminate_handler terminateHandler;
__cxa_exception * nextException;
int handlerCount;
int handlerSwitchValue;
const char * actionRecord;
const char * languageSpecificData;
void * catchTemp;
void * adjustedPtr;
_Unwind_Exception unwindHeader;
};
1
2
3
4
5
6
struct _Unwind_Exception {
_Unwind_Exception_Class exception_class;
void (*exception_cleanup)(_Unwind_Reason_Code reason, _Unwind_Exception *exc);
uintptr_t private_1; // non-zero means forced unwind
uintptr_t private_2; // holds sp that phase1 found for phase2 to use
};

此外这里还有个异常管理栈 __cxa_eh_globals。

1
2
3
4
struct __cxa_eh_globals {
__cxa_exception * caughtExceptions;
unsigned int uncaughtExceptions;
};

__cxa_eh_globals 里面保存了栈顶的 exception,以及未处理的 exception 数量。每次有新的 exception 时,当前 exception 的 header 中的 nextException 会指向当前的 caughtException,然后更新 __cxa_eh_globals 里面的 exception header 为这个新的 exception header。

异常处理过程优先处理最新的 exception,处理完后会处理之前一个旧的 exception,按照处理顺序来说也就是下一个。简单总结下,begin_catch 的时候减少计数并且把 cxa_exception 放到栈上,而在 end_catch 的时候将对象从 globals 中取出,而在 catch 以及 throw 的过程中通过增减 uncaughtExceptions 来管理当前未处理异常对象的数量。

栈回溯

_Unwind_RaiseException

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
_LIBUNWIND_EXPORT _Unwind_Reason_Code
_Unwind_RaiseException(_Unwind_Exception *exception_object) {
unw_context_t uc;
unw_cursor_t cursor;
__unw_getcontext(&uc);

// Mark that this is a non-forced unwind, so _Unwind_Resume() can do the right thing.
exception_object->private_1 = 0;
exception_object->private_2 = 0;

// phase 1: the search phase
_Unwind_Reason_Code phase1 = unwind_phase1(&uc, &cursor, exception_object);
if (phase1 != _URC_NO_REASON) return phase1;

// phase 2: the clean up phase
return unwind_phase2(&uc, &cursor, exception_object);
}

如代码所示,_Unwind_RaiseException 采用了经典的两段式回溯:unwind_phase1 与 unwind_phase2。

**unwind_phase1(Search)**会遍历整个栈以查找 Exception Handler。如果没有找到 Exception Handler,则应当终止程序。不过 libunwind 本身不会直接调用 std::terminate(),而是返回 _URC_END_OF_STACK 并由调用者决定如何终止程序。

**unwind_phase2(Clean)**会逐帧回溯并清理栈,直到最后的 Exception Handler。从代码中也可以看到,如果unwind_phase1 阶段没有找到 Exception Handler,那么根本就不会进入到第二阶段,也就是不会进行栈回溯,栈上对象的析构函数不会被执行。

unwind_phase1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
static _Unwind_Reason_Code
unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor, _Unwind_Exception *exception_object) {
__unw_init_local(cursor, uc);

// Walk each frame looking for a place to stop.
while (true) {
// Ask libunwind to get next frame (skip over first which is
// _Unwind_RaiseException).
int stepResult = __unw_step(cursor);
if (stepResult == 0) {
return _URC_END_OF_STACK;
} else if (stepResult < 0) {
return _URC_FATAL_PHASE1_ERROR;
}

// See if frame has code to run (has personality routine).
unw_proc_info_t frameInfo;
unw_word_t sp;
if (__unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
return _URC_FATAL_PHASE1_ERROR;
}

// If there is a personality routine, ask it if it will want to stop at
// this frame.
if (frameInfo.handler != 0) {
_Unwind_Personality_Fn p = get_handler_function(&frameInfo);
_Unwind_Reason_Code personalityResult =
(*p)(1, _UA_SEARCH_PHASE, exception_object->exception_class,
exception_object, (struct _Unwind_Context *)(cursor));
switch (personalityResult) {
case _URC_HANDLER_FOUND:
// found a catch clause or locals that need destructing in this frame
// stop search and remember stack pointer at the frame
__unw_get_reg(cursor, UNW_REG_SP, &sp);
exception_object->private_2 = (uintptr_t)sp;
return _URC_NO_REASON;

case _URC_CONTINUE_UNWIND:
// continue unwinding
break;

default:
return _URC_FATAL_PHASE1_ERROR;
}
}
}
return _URC_NO_REASON;
}

在 unwind_phase1 中,代码会不断循环查找 Exception Handler,直到找到 Exception Handler 或者到达栈底:

  1. 使用 __unw_step 函数,使 cursor 指向下一个栈帧;
  2. 使用 __unw_get_proc_info 函数,检查当前栈帧是否有需要执行的代码;
    • 如果找到了要执行的代码,则检查是否要停在当前栈帧(可能找到了 Exception Handler);
    • 如果找到了 Exception Handler,标记当前栈帧并返回;
    • 否则继续循环。
  3. 如果没有找到要执行的代码,则继续循环。

在检查 catch 块是否与当前异常对象所匹配时,会对比 RTTI 信息等,所以如果回滚过程中找到了很多 catch,会对 unwind_phase1 的性能有较大的影响。

unwind_phase2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
static _Unwind_Reason_Code
unwind_phase2(unw_context_t *uc, unw_cursor_t *cursor,
_Unwind_Exception *exception_object) {
__unw_init_local(cursor, uc);

// uc is initialized by __unw_getcontext in the parent frame. The first stack
// frame walked is unwind_phase2.
unsigned framesWalked = 1;

// Walk each frame until we reach where search phase said to stop.
while (true) {

// Ask libunwind to get next frame (skip over first which is
// _Unwind_RaiseException).
int stepResult = __unw_step_stage2(cursor);
if (stepResult == 0) {
return _URC_END_OF_STACK;
} else if (stepResult < 0) {
return _URC_FATAL_PHASE2_ERROR;
}

// Get info about this frame.
unw_word_t sp;
unw_proc_info_t frameInfo;
__unw_get_reg(cursor, UNW_REG_SP, &sp);
if (__unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS) {
return _URC_FATAL_PHASE2_ERROR;
}

++framesWalked;
// If there is a personality routine, tell it we are unwinding.
if (frameInfo.handler != 0) {
_Unwind_Personality_Fn p = get_handler_function(&frameInfo);
_Unwind_Action action = _UA_CLEANUP_PHASE;
if (sp == exception_object->private_2) {
// Tell personality this was the frame it marked in phase 1.
action = (_Unwind_Action)(_UA_CLEANUP_PHASE | _UA_HANDLER_FRAME);
}
_Unwind_Reason_Code personalityResult =
(*p)(1, action, exception_object->exception_class, exception_object,
(struct _Unwind_Context *)(cursor));
switch (personalityResult) {
case _URC_CONTINUE_UNWIND:
// Continue unwinding
break;
case _URC_INSTALL_CONTEXT:
// Personality routine says to transfer control to landing pad.
// We may get control back if landing pad calls _Unwind_Resume().
__unw_phase2_resume(cursor, framesWalked);
// __unw_phase2_resume() only returns if there was an error.
return _URC_FATAL_PHASE2_ERROR;
default:
// Personality routine returned an unknown result code.
return _URC_FATAL_PHASE2_ERROR;
}
}
}

// Clean up phase did not resume at the frame that the search phase
// said it would...
return _URC_FATAL_PHASE2_ERROR;
}

unwind_phase2 与 unwind_phase1 的代码非常类似,也是在循环中回溯栈,只不过它所做的事情要多一点:

  1. 使用 __unw_step_stage2 函数,使 cursor 指向下一个栈帧;

  2. 使用 __unw_get_reg 获取当前栈帧的 sp 寄存器;

  3. 使用 __unw_get_proc_info 函数,获取当前栈帧的信息;

  4. 如果当前栈帧有要执行的代码,则告诉它目前正在进行 _UA_CLEANUP_PHASE | _UA_HANDLER_FRAME。

    • 如果这段代码执行后应当继续回溯,则继续循环;

    • 如果这段代码执行后回溯到此为止,则尝试 resume 控制权

Others

__unw_step 退栈

unwind_phase1 和 unwind_phase2 都调用到了 __unw_step 或者 __unw_step_stage2 进行 1 次或者多次栈回退。栈回退操作,就需要改变当前的 PC 指针。__unw_step 函数会改变备份在 cursor 中的寄存器信息,完成一层退栈操作。发生退栈操作时,需要解决两个问题:

  1. 恢复 callee saved register

  2. 正确设置四个重要寄存器 pc、lr、fp、sp

1
2
3
4
5
6
7
8
9
int __unw_step(unw_cursor_t *cursor) {
AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
return co->step();
}

int __unw_step_stage2(unw_cursor_t *cursor) {
AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
return co->step(true);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// A = libunwind::LocalAddressSpace, R = libunwind::Registers_arm64
template <typename A, typename R> int UnwindCursor<A, R>::step(bool stage2) {
(void)stage2;
// Bottom of stack is defined when unwind info cannot be found.
if (_unwindInfoMissing)
return UNW_STEP_END;

// Use unwinding info to modify register set as if function returned.
int result;
#if defined(_LIBUNWIND_SUPPORT_COMPACT_UNWIND)
result = this->stepWithCompactEncoding(stage2);
#elif defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)
result = this->stepWithDwarfFDE(stage2);
#endif

// update info based on new PC
if (result == UNW_STEP_SUCCESS) {
this->setInfoBasedOnIPRegister(true);
if (_unwindInfoMissing)
return UNW_STEP_END;
}

return result;
}

__unw_step 这个函数的实际逻辑最后定位到了 libunwind 的 stepWithDwarfFDE。

  • 首先会从栈帧上拿到保存的 ip(instruction pointer,即函数的返回地址);

  • 然后调用 DwarfInstructions::stepWithDwarf。

1
2
3
4
5
6
int stepWithDwarfFDE(bool stage2) {
typename R::link_reg_t pc = this->getReg(UNW_REG_IP);
return DwarfInstructions<A, R>::stepWithDwarf(
_addressSpace, pc, (pint_t)_info.unwind_info, _registers,
_isSignalFrame, stage2);
}

来到了 DwarfInstructions::stepWithDwarf 方法,该方法会解码 CIE 和 FDE 信息,并依赖这些信息还原 x19 - x28,d8 - d15 这些 callee saved register(关于 CIE 和 FDE 这个后文会有描述)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// DwarfInstructions.hpp in libunwind
template <typename A, typename R>
int DwarfInstructions<A, R>::stepWithDwarf(
A &addressSpace, typename R::link_hardened_reg_arg_t pc, pint_t fdeStart,
R &registers, bool &isSignalFrame, bool stage2) {
FDE_Info fdeInfo;
CIE_Info cieInfo;
if (CFI_Parser<A>::decodeFDE(addressSpace, fdeStart, &fdeInfo,
&cieInfo) == NULL) {
PrologInfo prolog;
if (CFI_Parser<A>::template parseFDEInstructions<R>(
addressSpace, fdeInfo, cieInfo, pc, R::getArch(), &prolog)) {
// get pointer to cfa (architecture specific)
pint_t cfa = getCFA(addressSpace, prolog, registers);

(void)stage2;
// __unw_step_stage2 is not used for cross unwinding, so we use
// __aarch64__ rather than LIBUNWIND_TARGET_AARCH64 to make sure we are
// building for AArch64 natively.

// restore registers that DWARF says were saved
R newRegisters = registers;

// Typically, the CFA is the stack pointer at the call site in
// the previous frame. However, there are scenarios in which this is not
// true. For example, if we switched to a new stack. In that case, the
// value of the previous SP might be indicated by a CFI directive.
//
// We set the SP here to the CFA, allowing for it to be overridden
// by a CFI directive later on.
newRegisters.setSP(cfa);

typename R::reg_t returnAddress = 0;
constexpr int lastReg = R::lastDwarfRegNum();
for (int i = 0; i <= lastReg; ++i) {
if (prolog.savedRegisters[i].location != CFI_Parser<A>::kRegisterUnused) {
if (registers.validFloatRegister(i))
newRegisters.setFloatRegister(i, getSavedFloatRegister(addressSpace, registers, cfa, prolog.savedRegisters[i]));
else if (i == (int)cieInfo.returnAddressRegister)
returnAddress = getSavedRegister(addressSpace, registers, cfa, prolog.savedRegisters[i]);
else if (registers.validRegister(i))
newRegisters.setRegister(i, getSavedRegister(addressSpace, registers, cfa, prolog.savedRegisters[i]));
else
return UNW_EBADREG;
} else if (i == (int)cieInfo.returnAddressRegister) {
// Leaf function keeps the return address in register and there is no
// explicit instructions how to restore it.
returnAddress = registers.getRegister(cieInfo.returnAddressRegister);
}
}

isSignalFrame = cieInfo.isSignalFrame;

// Return address is address after call site instruction, so setting IP to
// that does simulates a return.
newRegisters.setIP(returnAddress);

// Simulate the step by replacing the register set with the new ones.
registers = newRegisters;

return UNW_STEP_SUCCESS;
}
}
return UNW_EBADFRAME;
}

CFI_Parser<A>::decodeFDE 负责解码 FDE(Frame Description Entry),CFI_Parser<A>::parseFDEInstructions 负责解释执行 FDE 中的 DWARF 字节码,得到指定 PC 位置对应栈上保存的值的位置偏移量表。

  • 拿到栈底基准地址 CFA
  • 根据位置偏移量表获取到栈上保存的寄存器的所有值,恢复到拷贝的寄存器状态中
  • 设置 IP 为 returnAddress(跳到上一层函数)
  • 切换寄存器状态 register 为 newRegisters

其中 CFA (Canonical Frame Address) 指的是上一级调用函数的栈指针(SP)在进入当前函数时的值。简单说,它是当前函数的调用者的栈顶位置

需要留意的是:这里的寄存器并不是真正意义上的寄存器,而是一块内存,等真正需要的时候将这块内存里面的值加载到真正的寄存器中进行跳转

1
2
3
4
5
6
7
8
9
10
11
12
class _LIBUNWIND_HIDDEN Registers_arm64 {
// ...
struct GPRs {
uint64_t __x[29] = {}; // x0-x28
uint64_t __fp = 0; // Frame pointer x29
uint64_t __lr = 0; // Link register x30
uint64_t __sp = 0; // Stack pointer x31
uint64_t __pc = 0; // Program counter
uint64_t __ra_sign_state = 0; // RA sign state register
};
GPRs _registers = {};
};

__unw_get_proc_info 获取栈帧信息

unwind_phase1 和 unwind_phase2 都调用到 __unw_get_proc_info 函数,获取当前栈帧的信息 unw_proc_info_t。unw_proc_info_t 结构体包含函数的起始与结束地址、LSDA、personality routine 函数指针(用于寻找异常对应的 landing pad),还有包含了如何恢复 callee saved register 的信息。

1
2
3
4
5
6
7
8
9
10
11
12
struct unw_proc_info_t {
unw_word_t __ptrauth_unwind_upi_startip start_ip; /* start address of function */
unw_word_t __ptrauth_unwind_upi_endip end_ip; /* address after end of function */
unw_word_t __ptrauth_unwind_upi_lsda lsda; /* address of language specific data area, or zero if not used */
unw_word_t __ptrauth_unwind_upi_handler_intptr handler;
unw_word_t gp; /* not used */
unw_word_t __ptrauth_unwind_upi_flags flags; /* not used */
uint32_t format; /* compact unwind encoding, or zero if none */
uint32_t unwind_info_size; /* size of DWARF unwind info, or zero if none */
unw_word_t __ptrauth_unwind_upi_info unwind_info; /* address of DWARF unwind info, or zero */
unw_word_t __ptrauth_unwind_upi_extra extra; /* mach_header of mach-o image containing func */
};

那么这些信息是从哪里获取到的呢?追踪一下代码,可以看到 __unw_get_proc_info 信息需要依赖 CIE 和 FDE 获取。

1
2
3
4
5
6
_LIBUNWIND_HIDDEN int __unw_get_proc_info(unw_cursor_t *cursor, unw_proc_info_t *info) {
AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
co->getInfo(info);
if (info->end_ip == 0) return UNW_ENOINFO;
return UNW_ESUCCESS;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
template <typename A, typename R>
bool UnwindCursor<A, R>::getInfoFromFdeCie(
const typename CFI_Parser<A>::FDE_Info &fdeInfo,
const typename CFI_Parser<A>::CIE_Info &cieInfo,
typename R::link_hardened_reg_arg_t pc, uintptr_t dso_base) {
typename CFI_Parser<A>::PrologInfo prolog;
if (CFI_Parser<A>::template parseFDEInstructions<R>(
_addressSpace, fdeInfo, cieInfo, pc, R::getArch(), &prolog)) {
// Save off parsed FDE info
_info.start_ip = fdeInfo.pcStart;
_info.end_ip = fdeInfo.pcEnd;
_info.lsda = fdeInfo.lsda;
_info.handler = cieInfo.personality;
// Some frameless functions need SP altered when resuming in function, so
// propagate spExtraArgSize.
_info.gp = prolog.spExtraArgSize;
_info.flags = 0;
_info.format = dwarfEncoding();
_info.unwind_info = fdeInfo.fdeStart;
_info.unwind_info_size = static_cast<uint32_t>(fdeInfo.fdeLength);
_info.extra = static_cast<unw_word_t>(dso_base);
return true;
}
return false;
}

捕获和处理异常

Personality Routine

在 unwind_phase1 和 unwind_phase2 过程中,libc++ 使用 get_handler_function 方法获取 personality routine:

1
2
3
4
5
6
7
8
9
static _Unwind_Personality_Fn get_handler_function(unw_proc_info_t *frameInfo) {
uintptr_t __unwind_ptrauth_restricted_intptr(ptrauth_key_function_pointer,
0,
ptrauth_function_pointer_type_discriminator(_Unwind_Personality_Fn))
reauthenticatedIntegerHandler = frameInfo->handler;
_Unwind_Personality_Fn handler;
memmove(&handler, (void *)&reauthenticatedIntegerHandler, sizeof(_Unwind_Personality_Fn));
return handler;
}

其中 Personality Routine 的声明如下。libunwind 使用函数指针的回调函数来具体实现栈清理等功能,这保证了它能够做到语言无关。

1
2
3
4
5
typedef _Unwind_Reason_Code (*_Unwind_Personality_Fn)(int, _Unwind_Action,
_Unwind_Exception_Class,
_Unwind_Exception *,
struct _Unwind_Context *);
typedef _Unwind_Personality_Fn __personality_routine;

由于在处理异常时,不同编程语言会存在不同的处理行为,例如:

  • __gxx_personality_v0: C++
  • __gxx_personality_sj0: sjlj
  • __gcc_personality_v0: C -fexceptions for attribute((cleanup(...)))
  • __CxxFrameHandler3: Windows MSVC
  • __gxx_personality_seh0: MinGW-w64 -fseh-exceptions
  • __objc_personality_v0: ObjC in the macOS environment

其中 libc++ 的 Personality Routine 是 __gxx_personality_v0,它会接收异常的上下文,一个异常结构体包含有异常对象的类型和值,以及指向当前函数的异常表(exception table)的引用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// cxa_personality.cpp in libcxxabi
_Unwind_Reason_Code __gxx_personality_v0
(int version, _Unwind_Action actions, uint64_t exceptionClass,
_Unwind_Exception* unwind_exception, _Unwind_Context* context)
{
if (version != 1 || unwind_exception == 0 || context == 0)
return _URC_FATAL_PHASE1_ERROR;

bool native_exception = (exceptionClass & get_vendor_and_language) ==
(kOurExceptionClass & get_vendor_and_language);
scan_results results;
if (actions == (_UA_CLEANUP_PHASE | _UA_HANDLER_FRAME) && native_exception) {
// Reload the results from the phase 1 cache.
__cxa_exception* exception_header = (__cxa_exception*)(unwind_exception + 1) - 1;
results.ttypeIndex = exception_header->handlerSwitchValue;
results.actionRecord = exception_header->actionRecord;
results.languageSpecificData = exception_header->languageSpecificData;
results.landingPad = reinterpret_cast<uintptr_t>(exception_header->catchTemp);
results.adjustedPtr = exception_header->adjustedPtr;

// Jump to the handler.
set_registers(unwind_exception, context, results);
// Cache base for calculating the address of ttype in
// __cxa_call_unexpected.
if (results.ttypeIndex < 0) {
exception_header->catchTemp = 0;
}
return _URC_INSTALL_CONTEXT;
}

// In other cases we need to scan LSDA.
scan_eh_tab(results, actions, native_exception, unwind_exception, context);
if (results.reason == _URC_CONTINUE_UNWIND ||
results.reason == _URC_FATAL_PHASE1_ERROR)
return results.reason;

if (actions & _UA_SEARCH_PHASE)
{
// Phase 1 search: All we're looking for in phase 1 is a handler that
// halts unwinding
assert(results.reason == _URC_HANDLER_FOUND);
if (native_exception) {
// For a native exception, cache the LSDA result.
__cxa_exception* exc = (__cxa_exception*)(unwind_exception + 1) - 1;
exc->handlerSwitchValue = static_cast<int>(results.ttypeIndex);
exc->actionRecord = results.actionRecord;
exc->languageSpecificData = results.languageSpecificData;
exc->catchTemp = reinterpret_cast<void*>(results.landingPad);
exc->adjustedPtr = results.adjustedPtr;
}
return _URC_HANDLER_FOUND;
}

assert(actions & _UA_CLEANUP_PHASE);
assert(results.reason == _URC_HANDLER_FOUND);
set_registers(unwind_exception, context, results);
// Cache base for calculating the address of ttype in __cxa_call_unexpected.
if (results.ttypeIndex < 0) {
__cxa_exception* exception_header = (__cxa_exception*)(unwind_exception + 1) - 1;
exception_header->catchTemp = 0;
}
return _URC_INSTALL_CONTEXT;
}

Search 阶段主要用于寻找对应栈的异常处理信息,因此在此之前需要先扫描 eh_frame 来获取 LSDA。

  • 如果找不到对应处理信息,那么会返回 continue unwind,在 libunwind 中继续 step 到下一个栈,直到找到对应的栈帧或者 scan 出错为止。
  • 如果找到异常处理信息,那么会保存在 __cxa_exception 中,供 unwind_phase2 读取使用。

Cleanup 阶段有 2 种情况:

  • 一类是在 unwind_phase1 中已经找好对应的异常处理信息,可以直接读取信息并且设置 context 的寄存器,此时读取的就是 unwind_phase1 中保存的结果,通过 set_registers 设置对应的值;
  • 另一类则是没有可用处理信息的情况,会再次 scan_eh_tab,使用搜索到的结果更新 context。

当 __gxx_personality_v0 方法找到对应的 landingpad 时,会通过 set_registers 设置好寄存器 R0 为 unwind_exception,R1 为 ttypeIndex,IP 设置为 landingPad 的入口地址,并返回 _URC_INSTALL_CONTEXT。

1
2
3
4
5
6
7
// cxa_personality.cpp
static void set_registers(_Unwind_Exception* unwind_exception, _Unwind_Context* context,
const scan_results& results) {
_Unwind_SetGR(context, __builtin_eh_return_data_regno(0), unwind_exception);
_Unwind_SetGR(context, __builtin_eh_return_data_regno(1), results.ttypeIndex);
_Unwind_SetIP(context, results.landingPad);
}

当 __gxx_personality_v0 返回时,unwind_phase2 方法会调用 __unw_phase2_resume 进行跳转。__unw_phase2_resume 会一路调用 __unw_resume 方法,最后调用到 Registers_arm64 的 jumpto 方法,该方法就是将前面准备的寄存器值从内存加载到真正的寄存器中进行跳转,至此代码将真正跳转到 landing pad。

__unw_resume 的跳转逻辑如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// extern "C" void __libunwind_Registers_arm64_jumpto(Registers_arm64 *, unsigned);
//
// On entry:
// thread_state pointer is in x0
// walked_frames counter is in x1
//
DEFINE_LIBUNWIND_FUNCTION(__libunwind_Registers_arm64_jumpto)

// skip restore of x0,x1 for now
ldp x2, x3, [x0, #0x010]
ldp x4, x5, [x0, #0x020]
ldp x6, x7, [x0, #0x030]
ldp x8, x9, [x0, #0x040]
ldp x10,x11, [x0, #0x050]
ldp x12,x13, [x0, #0x060]
ldp x14,x15, [x0, #0x070]
// x16 and x17 were clobbered by the call into the unwinder, so no point in
// restoring them.
ldp x18,x19, [x0, #0x090]
ldp x20,x21, [x0, #0x0A0]
ldp x22,x23, [x0, #0x0B0]
ldp x24,x25, [x0, #0x0C0]
ldp x26,x27, [x0, #0x0D0]
ldp x28,x29, [x0, #0x0E0]

ldp d0, d1, [x0, #0x110]
ldp d2, d3, [x0, #0x120]
ldp d4, d5, [x0, #0x130]
ldp d6, d7, [x0, #0x140]
ldp d8, d9, [x0, #0x150]
ldp d10,d11, [x0, #0x160]
ldp d12,d13, [x0, #0x170]
ldp d14,d15, [x0, #0x180]
ldp d16,d17, [x0, #0x190]
ldp d18,d19, [x0, #0x1A0]
ldp d20,d21, [x0, #0x1B0]
ldp d22,d23, [x0, #0x1C0]
ldp d24,d25, [x0, #0x1D0]
ldp d26,d27, [x0, #0x1E0]
ldp d28,d29, [x0, #0x1F0]
ldr d30, [x0, #0x200]
ldr d31, [x0, #0x208]
// Finally, restore sp. This must be done after the last read from the
// context struct, because it is allocated on the stack, and an exception
// could clobber the de-allocated portion of the stack after sp has been
// restored.

ldr x16, [x0, #0x0F8] // load sp into scratch
ldr lr, [x0, #0x100] // restore pc into lr
ldp x0, x1, [x0, #0x000] // restore x0,x1
mov sp,x16 // restore sp
ret x30 // jump to pc


可以看下跳转时刻的堆栈信息:

1
2
3
4
5
6
7
8
frame #0: libunwind.1.dylib`__libunwind_Registers_arm64_jumpto at UnwindRegistersRestore.S:646
frame #1: libunwind.1.dylib`libunwind::Registers_arm64::returnto at Registers.hpp:2291:3
frame #2: libunwind.1.dylib`libunwind::UnwindCursor<libunwind::LocalAddressSpace, libunwind::Registers_arm64>::jumpto at UnwindCursor.hpp:1474:14
frame #3: libunwind.1.dylib`__unw_resume at libunwind.cpp:375:7
frame #4: libunwind.1.dylib`__unw_resume_with_frames_walked at libunwind.cpp:363:10
frame #5: libunwind.1.dylib`unwind_phase2 at UnwindLevel1.c:328:9
frame #6: libunwind.1.dylib`_Unwind_RaiseException at UnwindLevel1.c:480:10
frame #7: libc++abi.dylib`__cxa_throw at cxa_exception.cpp:295:5

Landing Pad

unwind_phase2 每次退栈过程中,都可能会涉及到一次 landingpad 的跳转,landingpad 有 3 种类型:

  • cleanup clause:调用 destructors of out-of-scope variables,然后调用 _Unwind_Resume 跳转到 unwind_phase2;
  • catch clause:调用 destructors of out-of-scope variables,跳转到 __cxa_begin_catch 调用,然后是 catch handler 块,最后是 __cxa_end_catch 调用;
  • rethrow:调用 __cxa_end_catch,执行 destructors of out-of-scope variables in the catch clause,然后调用 _Unwind_Resume 跳转到 unwind_phase2。

注意:这里关于 rethrow 有一些疑惑性:它代表着上次的异常已经被捕获处理,并且在处理的过程中再次抛出。从 API 的调用链来看,它会在当前帧栈再次调用 _Unwind_RaiseException 进行栈展开处理,那么当前帧栈尚且没有处理完毕,所以必须确保在开始新的展开之前,做好当前 catch 块的清理:先调用 __cxa_end_catch,再调用 destructors。

CFI & CIE & FDE

CFI(Call Frame Information)是 DWARF 标准中定义的一组数据结构和指令,用于描述程序执行过程中如何从一个函数的栈帧(stack frame)恢复到其调用者的栈帧。CFI 通过描述调用栈帧的布局,特别是返回地址和调用者寄存器值是如何保存的,来实现栈的“展开”(unwinding)。

CFI 内部有 2 个重要的结构体:CIE 和 FDE。

从源码看 C++ 异常:CFI & CIE & FDE(图 3)
  • CIE 中记录的是一些公用的入口信息,包括异常的 handler、数据增强信息等。每个函数都会对应一个 CIE,一个 CIE 可以供多个函数共用,如果两个函数拥有相同的初始化指令序列,那么它们通常指向同一个 CIE。

  • FDE 中记录了此函数栈回溯相关的信息,最主要的是记录了一系列指令序列(CFI, Call Frame Information),此指令序列可用来确定此函数执行到其每个地址时其各个寄存器的值应该如何获取/计算,每个函数都有且仅有一个 FDE 结构体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct CIE_Info {
pint_t cieStart;
pint_t cieLength;
pint_t cieInstructions;
uint8_t pointerEncoding;
uint8_t lsdaEncoding;
uint8_t personalityEncoding;
uint8_t personalityOffsetInCIE;
personality_t personality;
uint32_t codeAlignFactor;
int dataAlignFactor;
bool isSignalFrame;
bool fdesHaveAugmentationData;
uint8_t returnAddressRegister;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct FDE_Info {
pint_t fdeStart;
pint_t fdeLength;
pint_t fdeInstructions;
pint_t pcStart;
pint_t pcEnd;
pint_t lsda;
};

struct PrologInfo {
uint32_t cfaRegister;
int32_t cfaRegisterOffset; // CFA = (cfaRegister)+cfaRegisterOffset
int64_t cfaExpression; // CFA = expression
uint32_t spExtraArgSize;
RegisterLocation savedRegisters[kMaxRegisterNumber + 1];
};

这是一些常见的 CFI 指令:

1
2
3
4
5
6
7
.cfi_startproc                                ; 开始函数
.cfi_def_cfa w29, 16 ; 定义规范帧地址(CFA)
.cfi_offset w30, -8 ; LR保存在CFA-8
.cfi_offset w29, -16 ; FP保存在CFA-16
.cfi_endproc ; 结束函数
.cfi_personality 155, ___gxx_personality_v0 ; personality 指定
.cfi_lsda 16, Lexception0 ; 指向 LSDA 数据的标签

LSDA (Language Specific Data Area)

在 Personality Routine 环节提到:“为了寻找对应帧栈的异常处理信息,需要先扫描 eh_frame 来获取 LSDA”。那么什么是 LSDA 呢?LSDA 是每个函数的“语言特定扩展表”,其中包含:

  • 哪些指令范围可能抛出异常;
  • 对应的 landing pad 地址;
  • 匹配类型信息(typeinfo 指针)。

指令范围可以用来判断该异常是否在该帧栈的管理范畴内,typeinfo 匹配决定该异常是否在自己的 catch 范围内,如果前两者都满足的话,可以跳转到对应的 landing pad 地址。

LSDA 结构

从源码看 C++ 异常:LSDA 结构(图 4) 从源码看 C++ 异常:LSDA 结构(图 5)

如图,LSDA 结构主要包括 4 部分信息:

  1. Header

  2. Call Site Table

  3. Action Table actionType 有 3 种情况:

    从源码看 C++ 异常:LSDA 结构(图 6)
  4. Type Table

    1. 关于 Type Table,需要注意的是该表格一分为二:
    2. 横线以上的对应异常类型,倒序排列;
    3. 横线以下的正序部分是异常规格索引,已经在 C++17 被移除。
    从源码看 C++ 异常:LSDA 结构(图 7)

最后可以从汇编代码中感受下真实的 LSDA 信息:

从源码看 C++ 异常:LSDA 结构(图 8)

LSDA 解析

整个流程中少不了的是 scan_eh_tab 这个过程,而这个函数主要的用途就是去解析 LSDA 的结构信息。解析的核心逻辑,就是遍历 Call Site Table,获取到 Action Table Index,然后在 Action Table 中获取到 ttypeIndex,然后根据 ttypeIndex 在 type_info Table 中开始搜索和匹配异常对象和 catch 对象是否匹配。如果匹配则返回,如果不匹配,循环遍历 Action Table 中的 action 链表,直到处理完。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
bool native_exception,
_Unwind_Exception *unwind_exception,
_Unwind_Context *context) {
// Initialize results to found nothing but an error
results.ttypeIndex = 0;
results.actionRecord = 0;
results.languageSpecificData = 0;
results.landingPad = 0;
results.adjustedPtr = 0;
results.reason = _URC_FATAL_PHASE1_ERROR;
// Check for consistent actions
// ...

// Start scan by getting exception table address.
const uint8_t *lsda = (const uint8_t *)_Unwind_GetLanguageSpecificData(context);
if (lsda == 0) {
// There is no exception table
results.reason = _URC_CONTINUE_UNWIND;
return;
}
results.languageSpecificData = lsda;
uintptr_t base = 0;
// Get the current instruction pointer and offset it before next
// instruction in the current frame which threw the exception.
uintptr_t ip = _Unwind_GetIP(context) - 1;
// Get beginning current frame's code (as defined by the
// emitted dwarf code)
uintptr_t funcStart = _Unwind_GetRegionStart(context);
uintptr_t ipOffset = ip - funcStart;

const uint8_t* classInfo = NULL;
// Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
// dwarf emission
// Parse LSDA header.
uint8_t lpStartEncoding = *lsda++;
const uint8_t* lpStart = lpStartEncoding == DW_EH_PE_omit
? (const uint8_t*)funcStart
: (const uint8_t*)readEncodedPointer(&lsda, lpStartEncoding, base);
uint8_t ttypeEncoding = *lsda++;
if (ttypeEncoding != DW_EH_PE_omit) {
// Calculate type info locations in emitted dwarf code which
// were flagged by type info arguments to llvm.eh.selector
// intrinsic
uintptr_t classInfoOffset = readULEB128(&lsda);
classInfo = lsda + classInfoOffset;
}
// Walk call-site table looking for range that
// includes current PC.
uint8_t callSiteEncoding = *lsda++;

uint32_t callSiteTableLength = static_cast<uint32_t>(readULEB128(&lsda));
const uint8_t* callSiteTableStart = lsda;
const uint8_t* callSiteTableEnd = callSiteTableStart + callSiteTableLength;
const uint8_t* actionTableStart = callSiteTableEnd;
const uint8_t* callSitePtr = callSiteTableStart;
while (callSitePtr < callSiteTableEnd) {
// There is one entry per call site.

// The call sites are non-overlapping in [start, start+length)
// The call sites are ordered in increasing value of start
uintptr_t start = readEncodedPointer(&callSitePtr, callSiteEncoding);
uintptr_t length = readEncodedPointer(&callSitePtr, callSiteEncoding);
landing_pad_t landingPad = readEncodedPointer(&callSitePtr, callSiteEncoding);
uintptr_t actionEntry = readULEB128(&callSitePtr);
if ((start <= ipOffset) && (ipOffset < (start + length))) {
// Found the call site containing ip.
if (landingPad == 0) { // No handler here
results.reason = _URC_CONTINUE_UNWIND;
return;
}
landingPad = (uintptr_t)lpStart + landingPad;
results.landingPad = landingPad;
if (actionEntry == 0) { // Found a cleanup
results.reason = (actions & _UA_SEARCH_PHASE) ? _URC_CONTINUE_UNWIND : _URC_HANDLER_FOUND;
return;
}
// Convert 1-based byte offset into
const uint8_t* action = actionTableStart + (actionEntry - 1);
bool hasCleanup = false;
// Scan action entries until you find a matching handler, cleanup, or the end of action list
while (true) {
const uint8_t* actionRecord = action;
int64_t ttypeIndex = readSLEB128(&action);
if (ttypeIndex > 0) {
// Found a catch, does it actually catch?
// First check for catch (...)
const __shim_type_info* catchType = get_shim_type_info(static_cast<uint64_t>(ttypeIndex),
classInfo, ttypeEncoding,
native_exception, unwind_exception,
base);
if (catchType == 0) {
// Found catch (...) catches everything, including
// foreign exceptions. This is search phase, cleanup
// phase with foreign exception, or forced unwinding.
assert(actions & (_UA_SEARCH_PHASE | _UA_HANDLER_FRAME | _UA_FORCE_UNWIND));
results.ttypeIndex = ttypeIndex;
results.actionRecord = actionRecord;
results.adjustedPtr = get_thrown_object_ptr(unwind_exception);
results.reason = _URC_HANDLER_FOUND;
return;
}
// Else this is a catch (T) clause and will never
// catch a foreign exception
else if (native_exception) {
__cxa_exception* exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
void* adjustedPtr = get_thrown_object_ptr(unwind_exception);
const __shim_type_info* excpType = static_cast<const __shim_type_info*>(exception_header->exceptionType);
if (catchType->can_catch(excpType, adjustedPtr)) {
// Found a matching handler. This is either search
// phase or forced unwinding.
assert(actions & (_UA_SEARCH_PHASE | _UA_FORCE_UNWIND));
results.ttypeIndex = ttypeIndex;
results.actionRecord = actionRecord;
results.adjustedPtr = adjustedPtr;
results.reason = _URC_HANDLER_FOUND;
return;
}
}
// Scan next action ...
}
else if (ttypeIndex < 0) {
// Found an exception specification.
if (actions & _UA_FORCE_UNWIND) {
// Skip if forced unwinding.
} else if (native_exception) {
// Does the exception spec catch this native exception?
__cxa_exception* exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
void* adjustedPtr = get_thrown_object_ptr(unwind_exception);
const __shim_type_info* excpType = static_cast<const __shim_type_info*>(exception_header->exceptionType);
if (exception_spec_can_catch(ttypeIndex, classInfo,
ttypeEncoding, excpType,
adjustedPtr,
unwind_exception, base)) {
// Native exception caught by exception specification.
assert(actions & _UA_SEARCH_PHASE);
results.ttypeIndex = ttypeIndex;
results.actionRecord = actionRecord;
results.adjustedPtr = adjustedPtr;
results.reason = _URC_HANDLER_FOUND;
return;
}
} else {
// foreign exception caught by exception spec
results.ttypeIndex = ttypeIndex;
results.actionRecord = actionRecord;
results.adjustedPtr = get_thrown_object_ptr(unwind_exception);
results.reason = _URC_HANDLER_FOUND;
return;
}
// Scan next action ...
} else {
hasCleanup = true;
}
const uint8_t* temp = action;
int64_t actionOffset = readSLEB128(&temp);
if (actionOffset == 0) {
// End of action list. If this is phase 2 and we have found
// a cleanup (ttypeIndex=0), return _URC_HANDLER_FOUND;
// otherwise return _URC_CONTINUE_UNWIND.
results.reason = hasCleanup && actions & _UA_CLEANUP_PHASE
? _URC_HANDLER_FOUND
: _URC_CONTINUE_UNWIND;
return;
}
// Go to next action
action += actionOffset;
} // there is no break out of this loop, only return
}
// ...
} // there might be some tricky cases which break out of this loop

// It is possible that no eh table entry specify how to handle
// this exception. By spec, terminate it immediately.
call_terminate(native_exception, unwind_exception);
}
  1. 获取 LSDA 指针:
    • lsda = _Unwind_GetLanguageSpecificData(context);
  2. 解析 LSDA 头部:
    • lpStartEncoding:landing pad 起始编码方式;
    • ttypeEncoding:类型信息编码方式;
    • callSiteEncoding:调用点表编码方式;
    • classInfoOffset:类信息表偏移量。
  3. 解析 callSiteTable:每个 try 块对应一个表项,包含:
    • start:try 块起始地址;
    • length:try 块长度;
    • landingPad:landing pad 地址;
    • actionEntry:action 表项偏移量。
  4. 解析 actionEntry 链表:每个 actionEntry 包含:
    • ttypeIndex:类型索引(SLEB128 格式);
    • actionOffset:下一 action 项偏移量,链表结构。
  5. 类型匹配检查:
    • 对每个 ttypeIndex,通过 typetable 表找到对应的 typeinfo;
    • 检查 catchType->can_catch(excpType, adjustedPtr)。

RTTI

type_info 的缺陷

前文中 can_catch 需要对类型进行动态比对。为了实现运行时类型检查,C++ 标准提供了一套名为 RTTI 的接口,这套接口的核心是 std::type_info 类,它用于在运行时表示某个类型的相关信息。但这套接口提供的功能过于简单,它只支持查询一个多态对象的动态类型以及类型的基本属性(例如类型的名称等),并不支持动态查询不同的类型之间的关系(例如查询两个 std::type_info 所表示的类型是否构成继承关系等)

1
2
3
4
class type_info {
private:
const char *__type_name;
};

因此,各个 ABI 都需要对 RTTI 定义的功能进一步扩充以满足以下三点:

  1. 需要能够动态查询两个类型是否构成继承关系;
  2. 在两个类型构成继承关系的基础上,需要能够进一步查询这两个类型构成何种继承关系:是否为公开继承、是否为虚继承等;
  3. 在两个类型构成继承关系的基础上,需要能够进一步查询如何对基类子对象指针施加一定的偏移才能使其指向子类对象指针。

class 相关的 type_info

std::type_info 可能的子类型有:(参考这里)

1
2
3
4
5
6
7
8
9
10
abi::__fundamental_type_info
abi::__array_type_info
abi::__function_type_info
abi::__enum_type_info
abi::__class_type_info
abi::__si_class_type_info
abi::__vmi_class_type_info
abi::__pbase_type_info
abi::__pointer_type_info
abi::__pointer_to_member_type_info

限于篇幅,这里重点说明 class 相关的 type_info。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class __shim_type_info : public std::type_info {
public:
virtual bool can_catch(const __shim_type_info *thrown_type, void *&adjustedPtr) const = 0;
// ...
};

struct __class_type_info : __shim_type_info {};

struct __si_class_type_info : __class_type_info {
const __class_type_info *__base_type;
};
struct __vmi_class_type_info : __class_type_info {
unsigned int __flags;
unsigned int __base_count;
__base_class_type_info __base_info[1];
};

它们各自描述不同情况的类类型:

  • __class_type_info 用于描述没有任何基类的类类型;
  • __si_class_type_info 用于描述那些有且只有一个直接公开非虚基类的类类型,其中的 __base_type 成员即指向描述基类的 __class_type_info 对象;
  • __vmi_class_type_info 用于描述不满足上述两种情况的其他所有的类类型。
    • 其中的 __flags 成员是一组标志位,描述这种情况下类类型的某些属性;
    • __base_count 表示类类型有多少个直接基类;
    • __base_info 是一个实际长度为 __base_count 的数组,数组中的每个元素是一个 __base_class_type_info 对象用于描述一个基类,其中 __base_class_type_info 如下:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      struct __base_class_type_info {
      public:
      const __class_type_info* __base_type;
      long __offset_flags;

      enum __offset_flags_masks {
      __virtual_mask = 0x1,
      __public_mask = 0x2, // base is public
      __offset_shift = 8
      };
      };

以上 3 种类类型 can_catch 是共享的,__si_class_type_info 和 __vmi_class_type_info 并没有重写该方法,所以这里直接分析 __class_type_info 的 can_catch 方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool __class_type_info::can_catch(const __shim_type_info* thrown_type, void*& adjustedPtr) const {
// bullet 1
if (is_equal(this, thrown_type, false)) return true;
const __class_type_info* thrown_class_type = dynamic_cast<const __class_type_info*>(thrown_type);
if (thrown_class_type == 0) return false;

// bullet 2
__dynamic_cast_info info = {thrown_class_type, 0, this, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, true, nullptr};
info.number_of_dst_type = 1;
thrown_class_type->has_unambiguous_public_base(&info, adjustedPtr, public_path);
if (info.path_dst_ptr_to_static_ptr == public_path) {
adjustedPtr = const_cast<void*>(info.dst_ptr_leading_to_static_ptr);
return true;
}
return false;
}
bullet1: is_equal
1
2
3
4
static inline bool is_equal(const std::type_info* x, const std::type_info* y, bool use_strcmp) {    
// Still allow pointer equality to short circuit.
return x == y || strcmp(x->name(), y->name()) == 0;
};

std::type_info 重载了 == 方法:

1
2
3
4
5
class type_info {
bool operator==(const type_info& __arg) const {
return __impl::__eq(__type_name, __arg.__type_name);
}
}

其中 __impl 有 3 种类型:

  1. __unique_impl::__eq
1
2
3
4
5
struct __unique_impl : __string_impl_base {
static bool __eq(__type_name_t __lhs, __type_name_t __rhs) _NOEXCEPT {
return __lhs == __rhs;
}
};

在遵循 Itanium ABI 的编译器中,对于给定类型的 RTTI,只有一个唯一的副本存在,因此可以通过比较类型名称的地址来判断 type_info 是否相等,无需使用字符串,可以提高性能并简化代码

  1. __non_unique_impl::__eq
1
2
3
4
5
struct __non_unique_impl : __string_impl_base {
static bool __eq(__type_name_t __lhs, __type_name_t __rhs) _NOEXCEPT {
return __lhs == __rhs || __builtin_strcmp(__lhs, __rhs) == 0;
}
};

由于各种原因,链接器可能没有合并所有类型的 RTTI(llvm.org/PR37398)。在这种情况下,如果两个 type_info 的地址相等或者它们的名称字符串相等,这两个 type_info 被认为是相等的。

  1. __non_unique_arm_rtti_bit_impl::__eq
1
2
3
4
5
6
7
8
9
10
11
struct __non_unique_arm_rtti_bit_impl {
static bool __eq(__type_name_t __lhs, __type_name_t __rhs) _NOEXCEPT {
if (__lhs == __rhs)
return true;
if (__is_type_name_unique(__lhs) || __is_type_name_unique(__rhs))
// Either both are unique and have a different address, or one of them
// is unique and the other one isn't. In both cases they are unequal.
return false;
return __builtin_strcmp(__type_name_to_string(__lhs), __type_name_to_string(__rhs)) == 0;
}
}

这种方式是 Apple ARM64 的特定实现,给定类型的 RTTI 可能存在多个副本。在构造 type_info 时,编译器将类型名称的指针存储在 uintptr_t 类型中,指针的最高位表示 non_unique,默认为 0(false)。如果最高位被设置为 1,表示 type_info 在程序中不是唯一的。如果最高位没有被设置,表示 type_info 是唯一的。这个设计的目的是为了避免使用 weak 符号。它将原本会被作为弱符号生成的默认可见性的 type_info,转而使用隐藏可见性的 type_info,并把 non_unique bit 位设置为 1,表示非唯一。这样做的好处是,在链接镜像内,hidden 可见性的 type_info 仍然可以认为是唯一的,可以继续通过 linker 进行去重,而在不同的镜像间,会被视为不同的类型,避免了 weak 符号被重定向,导致 RTTI 类型信息混乱。

bullet2: __dynamic_cast_info

涉及到继承关系,需要使用 dynamic_cast 和 __dynamic_cast_info 构建动态转换信息,检查 thrown_type 是否以公共方式继承自 this(catchType)。

1
2
3
__dynamic_cast_info info = {thrown_class_type, 0, this, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, true, nullptr};
info.number_of_dst_type = 1;
thrown_class_type->has_unambiguous_public_base(&info, adjustedPtr, public_path);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void __class_type_info::has_unambiguous_public_base(__dynamic_cast_info* info,
void* adjustedPtr,
int path_below) const {
if (is_equal(this, info->static_type, false))
process_found_base_class(info, adjustedPtr, path_below);
}

void __si_class_type_info::has_unambiguous_public_base(__dynamic_cast_info* info,
void* adjustedPtr,
int path_below) const {
if (is_equal(this, info->static_type, false))
process_found_base_class(info, adjustedPtr, path_below);
else
__base_type->has_unambiguous_public_base(info, adjustedPtr, path_below);
}

void __vmi_class_type_info::has_unambiguous_public_base(__dynamic_cast_info* info,
void* adjustedPtr,
int path_below) const {
if (is_equal(this, info->static_type, false))
process_found_base_class(info, adjustedPtr, path_below);
else {
typedef const __base_class_type_info* Iter;
const Iter e = __base_info + __base_count;
Iter p = __base_info;
p->has_unambiguous_public_base(info, adjustedPtr, path_below);
if (++p < e) {
do {
p->has_unambiguous_public_base(info, adjustedPtr, path_below);
if (info->search_done) break;
} while (++p < e);
}
}
}

这部分逻辑和 C++ 继承方式密切相关,例如单继承、多继承、虚继承,逻辑比较复杂。

从源码看 C++ 异常:class 相关的 type_info(图 9)

感兴趣的同学可以先参考《深入探索 C++ 多态 ② - 继承关系》里的这 3 张图,了解下 C++ 对象的内存模型,然后可以在此基础上了解下 dynamic_cast 的工作过程。

从源码看 C++ 异常:class 相关的 type_info(图 10) 从源码看 C++ 异常:class 相关的 type_info(图 11) 从源码看 C++ 异常:class 相关的 type_info(图 12)

总结

本文主要结合源码分析了 C++ 的异常机制流程,包括抛出异常、两段式回溯、退栈、Personality Routine 通过 lsda 找到对应的 landing pad,异常类型匹配等逻辑,整体可以对 C++ 的异常机制有一个深入的理解,进而可以着手排查一下异常的相关问题。

QA:

C++ 异常疑难杂症排查案例

从网上的经验贴来看,type_info 类型匹配几乎是导致异常捕获失效的最大元凶了,其中根本原因则是由于各种原因,出现了多份 type_info,导致匹配失败。这里以 2 个案例说明:

案例一: 震惊!try catch 语句竟然失效了?

总结一下:由于某个 OC 组件该组件内使用了异常,但是禁用了 RTTI,为了能继续获取异常类型的 type_info 信息,编译器会重新生成一份。由于 OC 组件是静态库,最后该 type_info 信息会一起进入主二进制,这样就导致了主二进制和 libc++ 动态库同时拥有同名的 type_info 信息,进而导致 can_catch 匹配失败。

iOS 工程通常使用 CocoaPods 集成不同的组件,这些组件在编译时会作为一个独立的 target,任意一个 target 的编译选项禁用 RTTI 后都会影响到宿主 App 的异常处理流程,继而可能引发 try catch 失效,所以禁用 RTTI 的同时需要禁用 exception handling,即 -fno-rtti 和 -fno-exceptions 一起使用,这样单独的 target 不会影响到宿主 App 的 exception handling。

案例二: 一次酣畅淋漓的问题排查(C++ 标准库异常实现原理)

总结一下:ANDROID_STL 在 CMake 中默认是 c++_static 的,此时 C++ 标准库以静态库的方式链接到业务的 so 文件,因此 so 文件中相关的 type_info 是 local 的,进而导致 can_catch 匹配失败。此时将 c++_static 修改为 c++_shared 可以解决问题,或者手动把 typeinfo/vtable 的符号都导出为依赖 libc++.so 或者 libstdc++.so 也可以解决。

两段式回溯是必需的吗?

并非必需,《Itanium C++ ABI: Exception Handling》文档提到:

A two-phase exception-handling model is not strictly necessary to implement C++ language semantics, but it does provide some benefits. For example, the first phase allows an exception-handling mechanism to dismiss an exception before stack unwinding begins, which allows resumptive exception handling (correcting the exceptional condition and resuming execution at the point where it was raised). While C++ does not support resumptive exception handling, other languages do, and the two-phase model allows C++ to coexist with those languages on the stack.

翻译过来:两个阶段的异常处理模型对于 C++ 并不是严格必需的,但是它可以带来一些好处。比如,第一阶段允许异常处理机制在栈帧展开之前消除异常,这样可以进行恢复式异常处理(对异常情况进行修复,然后在抛出异常的地方继续执行),虽然 C++ 不支持恢复式的异常处理,但其它语言支持,两阶段模型允许 C++ 与那些语言在堆栈上共存。

有没有可以最小成本理解异常的实践方式?

强烈推荐 《C++ Exceptions under the hood》 系列,可以基于 libunwind 实现一个自己的最小集 MyCxxABI,方便调试和理解,不过由于年代久远代码失修,原代码会有编译不过的问题,不想麻烦可以参考这里:

[test.zip](从源码看 C++ 异常/test.zip)

Foreign Exception vs Native Exception

用 g++ 编译的代码抛出的异常,可以由 clang++ 编译的代码捕获吗?

[gcc_clang_abi_test.zip](从源码看 C++ 异常/gcc_clang_abi_test.zip)

尝试用 G++ 和 Clang++ 混合编译了 2 个 cpp 文件,测试结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
=== GCC 和 Clang 混合编译异常处理演示 ===
编译信息:
- main.cpp: 使用 Clang 17.0

[main] 调用 GCC 编译的函数...
[gcc] 调用 bar.cpp 中的函数...
[clang] 在 bar_function 中...
[clang] 调用 GCC 编译的函数(可能抛出异常)...
[gcc] 在 gcc_throw_func 中,准备抛出异常...
[clang] 捕获了 runtime_error: 这是从 GCC 编译的代码抛出的异常!
[gcc] 捕获到异常: clang: 重新抛出的逻辑错误
[main] 最终捕获: clang: 重新抛出的逻辑错误

=== 程序正常结束 ===

为什么 C++ 的析构函数禁止抛出异常?

可能会导致双重异常:

抛出第一个异常 –> 开始栈展开 –> 析构 obj –> obj 析构抛出第二个异常 –> 现在有两个活跃异常 → 无法处理。

所以析构函数禁止抛出异常。如果析构函数发生异常,不要让异常逃离析构函数,析构函数应该捕捉任何异常,不传播或结束程序。

OC 的异常处理机制也是一样的吗?

OC 的异常处理实际和 C++ 一样,OC 很多异常处理方法只是对 C++ 异常处理方法的封装,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// runtime/objc-exception.mm

void objc_exception_throw(id obj)
{
struct objc_exception *exc = (struct objc_exception *)
__cxa_allocate_exception(sizeof(struct objc_exception));

obj = (*exception_preprocessor)(obj);
[obj retain];

exc->obj = obj;
exc->tinfo.vtable = objc_ehtype_vtable+2;
exc->tinfo.name = object_getClassName(obj);
exc->tinfo.cls_unremapped = obj ? obj->getIsa() : Nil;

__cxa_throw(exc, &exc->tinfo, &_objc_exception_destructor);
__builtin_trap();
}

_Unwind_Reason_Code
__objc_personality_v0(int version,
_Unwind_Action actions,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject,
struct _Unwind_Context *context)
{
bool unwinding = ((actions & _UA_CLEANUP_PHASE) || (actions & _UA_FORCE_UNWIND));

// If we're executing the unwind, call this frame's alt handlers, if any.
if (unwinding) {
call_alt_handlers(context);
}

// Let C++ handle the unwind itself.
return __gxx_personality_v0(version, actions, exceptionClass,
exceptionObject, context);
}

Swift 的异常机制又是怎样的呢?

Swift 的错误处理模型是基于 try、catch 以及 throws 和 throw 关键字的。throws 声明一个函数可以抛出错误,而 throw 则是在实际运行时抛出错误。throws 关键字本质上是通过引入异常控制流来实现的。当一个 throws 函数被调用时,Swift 在内部生成一段额外的代码,用于检测函数是否抛出了错误。如果没有错误发生,函数会像普通函数一样返回结果;如果发生了错误,则会跳转到调用方的 catch 块进行处理。

这意味着 throws 和普通函数的调用在编译器层面有着不同的处理方式。在编译生成的中间代码中,throws 函数的返回值不是直接返回,而是封装在一个类似于 Result 类型的结构中,附带一个可能的错误对象。只有在 do-catch 块中,错误对象才会被解封和处理。

Swift 的错误是值,不是控制流中断,并不涉及栈回溯的行为,这与 C++ 的异常有本质区别,它和 OC 的 NSError 机制更像。在纯 Swift 项目中应该避免依赖 OC 异常,在混合项目中应该小心处理。

Java 的异常机制类似吗?

相同点:二者都有 try-catch 块,都支持异常传播,都进行栈展开,而且都是两段式栈回溯。

不同点:

从源码看 C++ 异常:Java 的异常机制类似吗?(图 13)

对待 C++ 异常的态度?

  • Google 编码规范说不使用异常,但它也说了主要是历史原因,老代码太多。

Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions. Things would probably be different if we had to do it all over again from scratch. Google C++ Style Guide

  • Qt 也不使用异常,原因主要是历史原因和二进制尺寸。

Qt itself will not throw exceptions. Instead, error codes are used. In addition, some classes have user visible error messages, for example QIODevice::errorString() or QSqlQuery::lastError(). This has historical and practical reasons . Turning on exceptions can increase library size by over 20%. Exception Safety | Qt 6.6

  • 现代语言的反思:回归“错误即值”

近年来如 Go 和 Rust 等语言开始回归“返回值”模式(如 Rust 的 Result<T, E>), 将错误视作数据(值),鼓励通过组合子(如 map, and_then)处理错误,使程序结构更加预测和类型安全

参考文档

  1. Itanium C++ ABI
  2. C++ 异常机制实现原理和源码分析
  3. Itanium C++ ABI: Exception Handling
  4. LLVM Exception Handling
  5. C++ 异常处理机制
  6. C++ 异常处理
  7. C++ exception handling ABI
  8. libc++abi Specification
  9. 利用 C 语言中的 setjmp 和 longjmp,来实现异常捕获和协程
  10. dynamic_cast 的实现方法分析以及性能优化
  11. 彻底理解 C++ ABI
  12. 震惊!try catch 语句竟然失效了?
  13. C++ Exceptions under the hood
  14. Stack unwinding
  15. Exploiting the Hard-Working DWARF
  16. Linux .eh_frame section 以及 libunwind
  17. CFI directives
  18. [libc++abi] Improve performance of __dynamic_cast
  19. C++ 对象模型实践探索
  20. 深入探索 C++ 多态 ② - 继承关系
  21. what-is-the-vtt-for-a-class
-------------本文结束 感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!

本文标题:从源码看 C++ 异常

文章作者:lingyun

发布时间:2026年03月07日 - 23:03

最后更新:2026年10月08日 - 00:10

原始链接:https://tsuijunxi.github.io/2026/03/07/%E4%BB%8E%E6%BA%90%E7%A0%81%E7%9C%8B%20C++%20%E5%BC%82%E5%B8%B8/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。