Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions

Brief overview

What is the C++ exception mechanism?

C++ exceptions look simple at the language level, but the runtime behavior is much more involved. A single throw raises several questions:

  • How does the runtime find the matching catch, especially across deep call stacks?
  • Since throw changes control flow, are stack objects inside the try block still destroyed correctly?
  • If the call chain mixes different languages, such as C -> C++ -> C -> C++, can exception handling still work when plain C does not support exceptions?
  • What kinds of exceptions cannot be caught by ordinary catch blocks?
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!

The rest of the article answers these questions by following the runtime source path.

Design idea

Exception handling exists in many high-level languages. It can stop the current function immediately and hand control to a function that can actually handle the error.

Bjarne Stroustrup explained the basic motivation in The C++ Programming Language: a library author can detect a runtime error, but usually does not know how to handle it because that depends on the application. The application author knows how to handle it, but does not know when it will occur. Exceptions solve exactly that problem by separating error detection from error handling.

The core idea is therefore not just “throwing an exception”, but finding the right handling path while cleaning up the execution context along the way.

Which implementation mechanisms exist?

There have been several C++ exception implementations over time.

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: Which implementation mechanisms exist? (figure 1)
  • SJLJ is older and simple, but not very efficient.
  • EHABI is mainly used on ARM32 and is tightly coupled to that architecture.
  • DWARF CFI is the most widely used mechanism today. It offers a good balance of performance and capability, and is the focus of this article.
  • Compact Unwind is an Apple-specific optimization. It only supports simple stack unwinding; for complex cases, the system falls back to DWARF CFI.

Layered model

The Itanium C++ ABI splits exception handling into two layers:

Level 1, the foundational ABI, is the cross-platform unwind library. Its APIs are usually Unwind*, and common implementations include libgcc and libunwind.

  • It captures and restores execution context and supports stack unwinding.
  • It exposes call stack information during exception handling and debugging.

Level 2, the C++ ABI, provides the C++ standard library ABI support, especially for exceptions and RTTI. Its APIs usually start with __cxa_*, and common implementations include libsupc++ and libc++abi.

  • It implements key pieces such as __cxa_throw, __cxa_rethrow, and __gxx_personality_v0.
  • It also provides dynamic type information support, such as typeinfo and dynamic_cast.

The Itanium C++ ABI is usually discussed in four areas. This article focuses on the exception-handling part.

Exception overview

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: Exception overview (figure 2)

The figure summarizes the full flow: __cxa_throw, _Unwind_RaiseException, unwind_phase1, unwind_phase2, landingpad, and the supporting metadata such as eh_frame, unw_proc_info_t, CIE, FDE, exception table, and call site table.

We can split the mechanism into three stages:

  1. Throw the exception.
  2. Unwind the stack.
  3. Catch and handle the exception.

The source code in the article is trimmed for focus, and the discussion mainly targets ARM64.

Throwing an exception

__cxa_allocate_exception

When user code executes throw, control first reaches __cxa_allocate_exception. This function allocates a piece of memory that contains an exception header, used by the C++ ABI, followed by the actual user-thrown object.

1
2
3
4
5
6
7
8
9
10
void *__cxa_allocate_exception(size_t thrown_size) throw() {
size_t actual_size = cxa_exception_size_from_exception_thrown_size(thrown_size);
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));
::memset(static_cast<void*>(exception_header), 0, actual_size);
return thrown_object_from_cxa_exception(exception_header);
}

This looks like a simple allocation, but the constraints are subtle. Allocating on the stack is a bad fit because the stack is precisely what will be unwound. Allocating on the heap can also fail because an exception may need to be thrown under memory pressure. Static allocation is not enough either because the operation must be thread-safe. Most implementations therefore allocate from thread-local storage, and use an emergency storage area when ordinary allocation fails.

__cxa_throw

After the memory is ready, execution enters __cxa_throw. It initializes the __cxa_exception structure, pushes the exception into the thread-local exception-management stack __cxa_eh_globals, and finally calls _Unwind_RaiseException.

1
2
3
4
5
6
7
8
9
10
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;
__cxa_exception* exception_header =
__cxa_init_primary_exception(thrown_object, tinfo, dest);
exception_header->referenceCount = 1;
_Unwind_RaiseException(&exception_header->unwindHeader);
failed_throw(exception_header);
}

The layout of __cxa_exception, _Unwind_Exception, and the actual thrown object matters because the runtime frequently converts between those pointers. For example, from an _Unwind_Exception *, libc++abi can recover the surrounding __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;
uintptr_t private_2;
};

The thread-local __cxa_eh_globals stores the top exception and the number of uncaught exceptions:

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

Every new exception links its header to the current top exception through nextException, then updates caughtExceptions. Exception handling therefore behaves like a stack: the newest exception is handled first. __cxa_begin_catch decreases the uncaught count and pushes the current cxa_exception; __cxa_end_catch pops it back out.

Stack unwinding

_Unwind_RaiseException

_Unwind_RaiseException is the entry point into libunwind. It uses the classic two-phase unwinding model: unwind_phase1 and unwind_phase2.

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

exception_object->private_1 = 0;
exception_object->private_2 = 0;

_Unwind_Reason_Code phase1 = unwind_phase1(&uc, &cursor, exception_object);
if (phase1 != _URC_NO_REASON) return phase1;

return unwind_phase2(&uc, &cursor, exception_object);
}

unwind_phase1, the search phase, walks the stack looking for an exception handler. If no handler is found, libunwind returns _URC_END_OF_STACK; the caller decides how to terminate.

unwind_phase2, the cleanup phase, walks frames again, runs cleanups, destroys out-of-scope objects, and eventually transfers control to the handler frame. If phase 1 fails, phase 2 never runs, which means stack objects do not get destructed by the exception path.

unwind_phase1

The core loop in phase 1 repeatedly steps to the next frame, fetches frame metadata, and asks the frame’s personality routine whether this frame wants to stop the unwind.

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
static _Unwind_Reason_Code
unwind_phase1(unw_context_t *uc, unw_cursor_t *cursor,
_Unwind_Exception *exception_object) {
__unw_init_local(cursor, uc);

while (true) {
int stepResult = __unw_step(cursor);
if (stepResult == 0) return _URC_END_OF_STACK;
if (stepResult < 0) return _URC_FATAL_PHASE1_ERROR;

unw_proc_info_t frameInfo;
unw_word_t sp;
if (__unw_get_proc_info(cursor, &frameInfo) != UNW_ESUCCESS)
return _URC_FATAL_PHASE1_ERROR;

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));

if (personalityResult == _URC_HANDLER_FOUND) {
__unw_get_reg(cursor, UNW_REG_SP, &sp);
exception_object->private_2 = (uintptr_t)sp;
return _URC_NO_REASON;
}
if (personalityResult != _URC_CONTINUE_UNWIND)
return _URC_FATAL_PHASE1_ERROR;
}
}
}

The search itself also performs type matching through RTTI, so a call chain with many catch clauses can make phase 1 more expensive.

unwind_phase2

Phase 2 looks very similar, but its purpose is different. It walks the stack again and tells each personality routine that cleanup is now happening. When the stack pointer equals the value saved in exception_object->private_2, the current frame is the handler frame found during phase 1.

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
static _Unwind_Reason_Code
unwind_phase2(unw_context_t *uc, unw_cursor_t *cursor,
_Unwind_Exception *exception_object) {
__unw_init_local(cursor, uc);
unsigned framesWalked = 1;

while (true) {
int stepResult = __unw_step_stage2(cursor);
if (stepResult == 0) return _URC_END_OF_STACK;
if (stepResult < 0) return _URC_FATAL_PHASE2_ERROR;

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 (frameInfo.handler != 0) {
_Unwind_Personality_Fn p = get_handler_function(&frameInfo);
_Unwind_Action action = _UA_CLEANUP_PHASE;
if (sp == exception_object->private_2)
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));

if (personalityResult == _URC_CONTINUE_UNWIND)
continue;
if (personalityResult == _URC_INSTALL_CONTEXT) {
__unw_phase2_resume(cursor, framesWalked);
return _URC_FATAL_PHASE2_ERROR;
}
return _URC_FATAL_PHASE2_ERROR;
}
}
}

In short, phase 2:

  1. Calls __unw_step_stage2 to move to the previous frame.
  2. Reads the current stack pointer and frame metadata.
  3. Invokes the personality routine with _UA_CLEANUP_PHASE.
  4. If the personality routine returns _URC_INSTALL_CONTEXT, libunwind resumes execution at the generated landing pad.

Others

__unw_step

Both phases rely on __unw_step or __unw_step_stage2 to move one frame upward. A single step needs to solve two problems:

  1. Restore callee-saved registers.
  2. Correctly set pc, lr, fp, and 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);
}

On DWARF CFI, the actual logic eventually reaches stepWithDwarfFDE, and then DwarfInstructions::stepWithDwarf. That function decodes CIE and FDE, interprets DWARF instructions, calculates the CFA, restores registers from the previous frame, and sets IP to the return address.

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);
}
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
// 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;
}

The CFA, Canonical Frame Address, is the caller’s stack pointer value when entering the current function. In practice, libunwind calculates the CFA, reads saved registers from locations relative to it, sets the previous IP, and then replaces the in-memory register snapshot. These are not hardware registers yet; they are a saved register state that will later be loaded into real registers when resuming.

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

__unw_get_proc_info fetches unw_proc_info_t for the current frame. This structure contains the function range, LSDA address, personality routine pointer, compact unwind format, and the DWARF unwind-info address.

1
2
3
4
5
6
7
8
9
10
11
12
struct unw_proc_info_t {
unw_word_t start_ip;
unw_word_t end_ip;
unw_word_t lsda;
unw_word_t handler;
unw_word_t gp;
unw_word_t flags;
uint32_t format;
uint32_t unwind_info_size;
unw_word_t unwind_info;
unw_word_t extra;
};

The information is obtained from CIE and 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
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)) {
_info.start_ip = fdeInfo.pcStart;
_info.end_ip = fdeInfo.pcEnd;
_info.lsda = fdeInfo.lsda;
_info.handler = cieInfo.personality;
_info.unwind_info = fdeInfo.fdeStart;
return true;
}
return false;
}

Catching and handling exceptions

Personality routine

During both phases, libunwind obtains the personality routine with get_handler_function:

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

The personality routine is a callback. This is the key reason libunwind can remain language-independent: C++, Objective-C, SJLJ, Windows SEH, and other systems can provide different personalities.

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;

Common examples:

  • __gxx_personality_v0: C++
  • __gxx_personality_sj0: SJLJ
  • __gcc_personality_v0: C with -fexceptions and cleanup attributes
  • __CxxFrameHandler3: Windows MSVC
  • __gxx_personality_seh0: MinGW-w64 SEH exceptions
  • __objc_personality_v0: Objective-C on macOS

For libc++abi, the personality routine is __gxx_personality_v0. It receives the exception context, the exception object, and the current frame’s exception table information.

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
_Unwind_Reason_Code __gxx_personality_v0(
int version, _Unwind_Action actions, uint64_t exceptionClass,
_Unwind_Exception* unwind_exception, _Unwind_Context* context) {
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) {
__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;
set_registers(unwind_exception, context, results);
return _URC_INSTALL_CONTEXT;
}

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) {
if (native_exception) {
__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;
}

set_registers(unwind_exception, context, results);
return _URC_INSTALL_CONTEXT;
}

During the search phase, it scans LSDA to find exception-handling information for the current frame. If no match is found, it returns _URC_CONTINUE_UNWIND; if a handler is found, it caches the result inside __cxa_exception for phase 2.

During the cleanup phase, there are two paths. If phase 1 already cached a handler result, the personality routine can reuse it directly. Otherwise, it scans LSDA again and updates the context from the new result.

When a landing pad is selected, set_registers sets the exception object into argument register 0, the type index into argument register 1, and the instruction pointer to the landing-pad address.

1
2
3
4
5
6
7
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);
}

After __gxx_personality_v0 returns _URC_INSTALL_CONTEXT, unwind_phase2 calls __unw_phase2_resume. On ARM64 this eventually loads the prepared register snapshot and jumps to the landing pad.

1
2
3
4
5
6
7
8
9
DEFINE_LIBUNWIND_FUNCTION(__libunwind_Registers_arm64_jumpto)
ldp x2, x3, [x0, #0x010]
ldp x4, x5, [x0, #0x020]
ldp x28,x29, [x0, #0x0E0]
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
ret x30

At the jump moment, a typical stack looks like this:

1
2
3
4
5
6
7
8
frame #0: libunwind.1.dylib`__libunwind_Registers_arm64_jumpto
frame #1: libunwind.1.dylib`libunwind::Registers_arm64::returnto
frame #2: libunwind.1.dylib`libunwind::UnwindCursor<...>::jumpto
frame #3: libunwind.1.dylib`__unw_resume
frame #4: libunwind.1.dylib`__unw_resume_with_frames_walked
frame #5: libunwind.1.dylib`unwind_phase2
frame #6: libunwind.1.dylib`_Unwind_RaiseException
frame #7: libc++abi.dylib`__cxa_throw

Landing pad

Every time unwind_phase2 steps through a frame, it may jump into a landing pad. There are three common landing-pad patterns:

  • cleanup clause: calls destructors for out-of-scope variables, then calls _Unwind_Resume to return to unwind_phase2.
  • catch clause: calls destructors, enters __cxa_begin_catch, runs the catch handler, and then calls __cxa_end_catch.
  • rethrow: calls __cxa_end_catch, destroys objects inside the catch clause, then calls _Unwind_Resume to continue unwinding.

The rethrow case is easy to misunderstand. It means the previous exception has already been caught and is being thrown again while still inside the current frame. Before the new unwind proceeds, the runtime must clean up the current catch block correctly.

CFI, CIE, and FDE

CFI, Call Frame Information, is the DWARF data and instruction set that describes how to restore a stack frame to its caller. It records how the return address and caller registers are saved, allowing the unwinder to walk the stack.

CFI has two important structures: CIE and FDE.

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: CFI, CIE, and FDE (figure 3)
  • CIE stores shared entry information, including personality routine and augmentation data. A CIE can be shared by multiple functions.
  • FDE stores unwind information for one function. The most important part is its CFI instruction sequence, which tells the unwinder how to recover register values at each address inside that function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct CIE_Info {
pint_t cieStart;
pint_t cieLength;
pint_t cieInstructions;
uint8_t pointerEncoding;
uint8_t lsdaEncoding;
uint8_t personalityEncoding;
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
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];
};

Some common CFI directives look like this:

1
2
3
4
5
6
7
.cfi_startproc
.cfi_def_cfa w29, 16
.cfi_offset w30, -8
.cfi_offset w29, -16
.cfi_endproc
.cfi_personality 155, ___gxx_personality_v0
.cfi_lsda 16, Lexception0

LSDA

Earlier we said that the personality routine scans eh_frame to obtain LSDA. LSDA, Language Specific Data Area, is the per-function language-specific exception table. It records:

  • Which instruction ranges may throw.
  • Which landing pad should handle a range.
  • Which typeinfo pointer should be used for matching.

The instruction range decides whether the current throw belongs to this frame. The typeinfo match decides whether the frame’s catch can handle this exception. If both match, control can transfer to the landing pad.

LSDA structure

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: LSDA structure (figure 4) Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: LSDA structure (figure 5)

LSDA mainly contains four parts:

  1. Header
  2. Call Site Table
  3. Action Table
  4. Type Table

The Action Table has three kinds of actionType:

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: LSDA structure (figure 6)

The Type Table is split into two regions. Entries above the dividing line are exception types, stored in reverse order. Entries below it are exception-specification indexes, which were removed in C++17.

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: LSDA structure (figure 7)

Real LSDA in assembly looks like this:

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: LSDA structure (figure 8)

LSDA parsing

The core parser is scan_eh_tab. Its job is to parse LSDA, iterate the Call Site Table, obtain the Action Table index, read ttypeIndex from the Action Table, and then use ttypeIndex to find a typeinfo entry in the Type Table. Finally it checks whether the thrown type matches the catch type.

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
static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
bool native_exception,
_Unwind_Exception *unwind_exception,
_Unwind_Context *context) {
const uint8_t *lsda =
(const uint8_t *)_Unwind_GetLanguageSpecificData(context);
if (lsda == 0) {
results.reason = _URC_CONTINUE_UNWIND;
return;
}

uintptr_t ip = _Unwind_GetIP(context) - 1;
uintptr_t funcStart = _Unwind_GetRegionStart(context);
uintptr_t ipOffset = ip - funcStart;

uint8_t lpStartEncoding = *lsda++;
const uint8_t* lpStart = lpStartEncoding == DW_EH_PE_omit
? (const uint8_t*)funcStart
: (const uint8_t*)readEncodedPointer(&lsda, lpStartEncoding, 0);

uint8_t ttypeEncoding = *lsda++;
const uint8_t* classInfo = NULL;
if (ttypeEncoding != DW_EH_PE_omit) {
uintptr_t classInfoOffset = readULEB128(&lsda);
classInfo = lsda + classInfoOffset;
}

uint8_t callSiteEncoding = *lsda++;
uint32_t callSiteTableLength = readULEB128(&lsda);
const uint8_t* callSiteTableStart = lsda;
const uint8_t* callSiteTableEnd =
callSiteTableStart + callSiteTableLength;
const uint8_t* actionTableStart = callSiteTableEnd;

for (const uint8_t* callSitePtr = callSiteTableStart;
callSitePtr < callSiteTableEnd;) {
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))) {
if (landingPad == 0) {
results.reason = _URC_CONTINUE_UNWIND;
return;
}
results.landingPad = (uintptr_t)lpStart + landingPad;
if (actionEntry == 0) {
results.reason = (actions & _UA_SEARCH_PHASE)
? _URC_CONTINUE_UNWIND
: _URC_HANDLER_FOUND;
return;
}

const uint8_t* action = actionTableStart + (actionEntry - 1);
while (true) {
int64_t ttypeIndex = readSLEB128(&action);
// Use ttypeIndex to fetch catch type and call can_catch.
}
}
}
}

The parsing flow is:

  1. Get the LSDA pointer with _Unwind_GetLanguageSpecificData(context).
  2. Parse the LSDA header: lpStartEncoding, ttypeEncoding, callSiteEncoding, and classInfoOffset.
  3. Parse the Call Site Table. Each entry records start, length, landingPad, and actionEntry.
  4. Parse the linked list of action entries. Each entry contains ttypeIndex and the offset to the next action.
  5. Use the Type Table to get typeinfo, then call catchType->can_catch(excpType, adjustedPtr).

RTTI

RTTI is the last critical piece. Exception matching depends on runtime type comparison.

Defects of type_info

std::type_info is the standard RTTI interface. It can represent the dynamic type of an object and expose basic information such as the type name, but by itself it does not describe type relationships. It cannot answer questions such as:

  1. Whether two classes form an inheritance relationship.
  2. Whether that inheritance is public or virtual.
  3. How to adjust a base-class subobject pointer so it points to the derived object.
1
2
3
4
class type_info {
private:
const char *__type_name;
};

So each ABI extends RTTI beyond the standard surface.

Possible std::type_info subtypes include:

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

For class types, libc++abi mainly uses:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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];
};

Their meanings are:

  • __class_type_info: a class with no base class.
  • __si_class_type_info: a class with exactly one direct, public, non-virtual base class.
  • __vmi_class_type_info: all other class cases, including multiple inheritance and virtual inheritance.

These three class type-info structures share can_catch, so the interesting logic starts in __class_type_info::can_catch.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool __class_type_info::can_catch(const __shim_type_info* thrown_type,
void*& adjustedPtr) const {
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;

__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

The first check is direct type equality:

1
2
3
4
5
static inline bool is_equal(const std::type_info* x,
const std::type_info* y,
bool use_strcmp) {
return x == y || strcmp(x->name(), y->name()) == 0;
};

std::type_info::operator== is backed by ABI-specific implementations:

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

There are three possible __impl variants:

  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;
}
};

Under compilers that follow the Itanium ABI, there is usually only one RTTI copy for a given type, so comparing the type-name address is enough. There is no need for string comparison, which improves performance and keeps the logic simple.

  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;
}
};

For various reasons, the linker may fail to merge all RTTI copies for a type (llvm.org/PR37398). In that case, two type_info values are considered equal if their addresses are equal or their name strings are equal.

  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;
}
}

The Apple ARM64 design avoids weak-symbol problems. Hidden typeinfo can still be deduplicated within a linked image, while separate images can keep separate RTTI copies without being unexpectedly redirected.

bullet2: __dynamic_cast_info

If the types are not directly equal, the runtime must check inheritance. It uses dynamic_cast-style metadata and __dynamic_cast_info to verify whether thrown_type publicly and unambiguously derives from the catch type.

1
2
3
4
5
6
7
__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);

The traversal differs for ordinary classes, single inheritance, multiple inheritance, and virtual inheritance:

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
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 {
for (auto p = __base_info; p < __base_info + __base_count; ++p) {
p->has_unambiguous_public_base(info, adjustedPtr, path_below);
if (info->search_done) break;
}
}
}

This is closely tied to the C++ object model:

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: bullet2: __dynamic_cast_info (figure 9)

For a better intuition, the inheritance-layout diagrams from Deep Dive into C++ Polymorphism 2: Inheritance are useful:

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: bullet2: __dynamic_cast_info (figure 10) Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: bullet2: __dynamic_cast_info (figure 11) Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: bullet2: __dynamic_cast_info (figure 12)

Summary

This article followed the C++ exception path from the source-code level: throwing, two-phase unwinding, frame stepping, personality routines, LSDA parsing, landing-pad selection, and RTTI-based type matching. The key takeaway is that throw is not a direct jump to catch. It is a cooperation between compiler-generated metadata and runtime stack-unwinding logic.

QA

A tricky C++ exception debugging case

From real-world debugging posts, type_info mismatch is one of the most common causes of failed catches. The root cause is often duplicated RTTI.

Case 1: Shocking! The try-catch statement stopped working?

The failure came from an Objective-C component that used exceptions while RTTI was disabled. To preserve exception type information, the compiler emitted another copy of type_info. Because the component was linked statically, that copy ended up in the main binary. The main binary and libc++ then contained identically named but distinct type_info objects, and can_catch failed to match them.

In iOS projects, CocoaPods usually builds components as separate targets. If any target disables RTTI, it may affect exception handling in the host app. If RTTI is disabled, exception handling should usually be disabled too, namely -fno-rtti together with -fno-exceptions.

Case 2: A satisfying debugging story about C++ standard-library exceptions

On Android, ANDROID_STL defaults to c++_static in CMake. The C++ standard library is then linked into the application’s .so, leaving the relevant type_info symbols local to that image, and can_catch may fail across library boundaries. Switching to c++_shared, or exporting typeinfo and vtable symbols so that they resolve through libc++.so or libstdc++.so, can solve the issue.

Is two-phase unwinding necessary?

Not strictly. The Itanium C++ ABI Exception Handling document explains that the two-phase model is not required for C++ semantics, but it provides benefits. In particular, phase 1 allows an exception system to dismiss or handle an exception before the stack has actually been unwound. C++ does not support resumptive exception handling, but other languages do, and the two-phase design lets C++ coexist with those languages on the same stack.

Is there a lower-cost way to understand exceptions?

I strongly recommend the C++ Exceptions under the hood series. It builds a minimal MyCxxABI on top of libunwind, which is a great way to debug and understand the mechanism. The original code is old and may not compile directly now, so I also kept a local reference package here:

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

Foreign Exception vs Native Exception

Can code compiled by clang++ catch an exception thrown by code compiled by g++?

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

I tested two mixed-compiler C++ files. The result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
=== GCC and Clang mixed exception-handling demo ===
Build info:
- main.cpp: compiled with Clang 17.0

[main] calling a GCC-compiled function...
[gcc] calling the function in bar.cpp...
[clang] inside bar_function...
[clang] calling a GCC-compiled function that may throw...
[gcc] inside gcc_throw_func, about to throw...
[clang] caught runtime_error: this exception was thrown by GCC-compiled code!
[gcc] caught exception: clang: rethrown logic error
[main] finally caught: clang: rethrown logic error

=== program ended normally ===

Why are C++ destructors forbidden from throwing?

A throwing destructor can create a double-exception situation:

first exception is thrown -> stack unwinding starts -> obj destructor runs -> obj destructor throws a second exception -> now two active exceptions exist, and the runtime cannot proceed safely.

So destructors should not let exceptions escape. If cleanup may fail, catch the exception inside the destructor and either swallow it deliberately or terminate explicitly.

Does Objective-C exception handling work the same way?

Objective-C exception handling is very close to the C++ mechanism. Many Objective-C exception APIs wrap the same C++ exception machinery.

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
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 (unwinding) {
call_alt_handlers(context);
}

return __gxx_personality_v0(version, actions, exceptionClass,
exceptionObject, context);
}

What about Swift exceptions?

Swift’s error model is based on try, catch, throws, and throw. A throws function declares that it may return an error, and throw produces that error at runtime.

The important difference is that Swift errors are values, not stack-unwinding control-flow interruptions. Conceptually it is closer to Result<T, E> or Objective-C’s NSError pattern than to C++ exceptions. In pure Swift projects, relying on Objective-C exceptions should be avoided; in mixed projects, it should be handled with extra care.

Is Java exception handling similar?

At the language level, both Java and C++ have try-catch, exception propagation, and stack unwinding. But their implementation models are different. C++ heavily depends on ABI-level metadata, LSDA, RTTI, and compiler-generated landing pads. Java exceptions are managed by the VM, where the runtime owns the stack metadata and exception tables.

Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions: Is Java exception handling similar? (figure 13)

How should we treat C++ exceptions?

Different ecosystems have made different tradeoffs.

Google’s C++ style guide says not to use exceptions, but it also says the reason is largely historical: too much existing Google C++ code was not prepared for exception safety.

Qt also avoids exceptions. Its documentation mentions historical and practical reasons, including binary-size cost. Turning on exceptions can increase library size significantly.

Modern languages have also been rethinking error handling. Go and Rust both return to the idea of “errors as values”; Rust’s Result<T, E> makes error flow explicit and composable.

My personal view is that C++ exceptions are neither magic nor evil. They are a powerful ABI feature with real cost and real failure modes. In codebases that choose to use them, exception safety and RTTI consistency must be treated as part of the engineering contract.

References

  1. Itanium C++ ABI
  2. C++ exception implementation principle and source analysis
  3. Itanium C++ ABI: Exception Handling
  4. LLVM Exception Handling
  5. C++ exception handling mechanism
  6. C++ exception handling
  7. C++ exception handling ABI
  8. libc++abi Specification
  9. Implementing exception catching and coroutine behavior with setjmp and longjmp in C
  10. dynamic_cast implementation analysis and performance optimization
  11. Understanding the C++ ABI
  12. Shocking! The try-catch statement stopped working?
  13. C++ Exceptions under the hood
  14. Stack unwinding
  15. Exploiting the Hard-Working DWARF
  16. Linux .eh_frame section and libunwind
  17. CFI directives
  18. [libc++abi] Improve performance of __dynamic_cast
  19. C++ object model practice notes
  20. Deep Dive into C++ Polymorphism 2: Inheritance
  21. what-is-the-vtt-for-a-class
-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:Understanding C++ Exceptions from the Source: __cxa_throw, Stack Unwinding, and -fno-exceptions

Author:lingyun

Published:2026-03-07 23:06

Updated:2026-10-08 00:23

Original link:https://tsuijunxi.github.io/en/2026/03/07/understanding-cpp-exceptions-from-source/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.