1 //===--------------------------- Unwind-seh.cpp ---------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Implements SEH-based Itanium C++ exceptions.
11 //===----------------------------------------------------------------------===//
15 #if defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)
28 #include "libunwind_ext.h"
29 #include "UnwindCursor.hpp"
31 using namespace libunwind;
33 #define STATUS_USER_DEFINED (1u << 29)
35 #define STATUS_GCC_MAGIC (('G' << 16) | ('C' << 8) | 'C')
37 #define MAKE_CUSTOM_STATUS(s, c) \
38 ((NTSTATUS)(((s) << 30) | STATUS_USER_DEFINED | (c)))
39 #define MAKE_GCC_EXCEPTION(c) \
40 MAKE_CUSTOM_STATUS(STATUS_SEVERITY_SUCCESS, STATUS_GCC_MAGIC | ((c) << 24))
42 /// SEH exception raised by libunwind when the program calls
43 /// \c _Unwind_RaiseException.
44 #define STATUS_GCC_THROW MAKE_GCC_EXCEPTION(0) // 0x20474343
45 /// SEH exception raised by libunwind to initiate phase 2 of exception
47 #define STATUS_GCC_UNWIND MAKE_GCC_EXCEPTION(1) // 0x21474343
49 /// Class of foreign exceptions based on unrecognized SEH exceptions.
50 static const uint64_t kSEHExceptionClass = 0x434C4E4753454800; // CLNGSEH\0
52 /// Exception cleanup routine used by \c _GCC_specific_handler to
53 /// free foreign exceptions.
54 static void seh_exc_cleanup(_Unwind_Reason_Code urc, _Unwind_Exception *exc) {
56 if (exc->exception_class != kSEHExceptionClass)
57 _LIBUNWIND_ABORT("SEH cleanup called on non-SEH exception");
61 static int __unw_init_seh(unw_cursor_t *cursor, CONTEXT *ctx);
62 static DISPATCHER_CONTEXT *__unw_seh_get_disp_ctx(unw_cursor_t *cursor);
63 static void __unw_seh_set_disp_ctx(unw_cursor_t *cursor,
64 DISPATCHER_CONTEXT *disp);
66 /// Common implementation of SEH-style handler functions used by Itanium-
67 /// style frames. Depending on how and why it was called, it may do one of:
68 /// a) Delegate to the given Itanium-style personality function; or
69 /// b) Initiate a collided unwind to halt unwinding.
70 _LIBUNWIND_EXPORT EXCEPTION_DISPOSITION
71 _GCC_specific_handler(PEXCEPTION_RECORD ms_exc, PVOID frame, PCONTEXT ms_ctx,
72 DISPATCHER_CONTEXT *disp, __personality_routine pers) {
74 _Unwind_Exception *exc;
75 _Unwind_Action action;
76 struct _Unwind_Context *ctx = nullptr;
77 _Unwind_Reason_Code urc;
78 uintptr_t retval, target;
81 _LIBUNWIND_TRACE_UNWINDING("_GCC_specific_handler(%#010lx(%lx), %p)",
82 ms_exc->ExceptionCode, ms_exc->ExceptionFlags,
84 if (ms_exc->ExceptionCode == STATUS_GCC_UNWIND) {
85 if (IS_TARGET_UNWIND(ms_exc->ExceptionFlags)) {
86 // Set up the upper return value (the lower one and the target PC
87 // were set in the call to RtlUnwindEx()) for the landing pad.
89 disp->ContextRecord->Rdx = ms_exc->ExceptionInformation[3];
90 #elif defined(__arm__)
91 disp->ContextRecord->R1 = ms_exc->ExceptionInformation[3];
92 #elif defined(__aarch64__)
93 disp->ContextRecord->X1 = ms_exc->ExceptionInformation[3];
96 // This is the collided unwind to the landing pad. Nothing to do.
97 return ExceptionContinueSearch;
100 if (ms_exc->ExceptionCode == STATUS_GCC_THROW) {
101 // This is (probably) a libunwind-controlled exception/unwind. Recover the
102 // parameters which we set below, and pass them to the personality function.
104 exc = (_Unwind_Exception *)ms_exc->ExceptionInformation[0];
105 if (!IS_UNWINDING(ms_exc->ExceptionFlags) && ms_exc->NumberParameters > 1) {
106 ctx = (struct _Unwind_Context *)ms_exc->ExceptionInformation[1];
107 action = (_Unwind_Action)ms_exc->ExceptionInformation[2];
110 // Foreign exception.
111 exc = (_Unwind_Exception *)malloc(sizeof(_Unwind_Exception));
112 exc->exception_class = kSEHExceptionClass;
113 exc->exception_cleanup = seh_exc_cleanup;
114 memset(exc->private_, 0, sizeof(exc->private_));
117 __unw_init_seh(&cursor, disp->ContextRecord);
118 __unw_seh_set_disp_ctx(&cursor, disp);
119 __unw_set_reg(&cursor, UNW_REG_IP, disp->ControlPc - 1);
120 ctx = (struct _Unwind_Context *)&cursor;
122 if (!IS_UNWINDING(ms_exc->ExceptionFlags)) {
123 if (ours && ms_exc->NumberParameters > 1)
124 action = (_Unwind_Action)(_UA_CLEANUP_PHASE | _UA_FORCE_UNWIND);
126 action = _UA_SEARCH_PHASE;
128 if (ours && ms_exc->ExceptionInformation[1] == (ULONG_PTR)frame)
129 action = (_Unwind_Action)(_UA_CLEANUP_PHASE | _UA_HANDLER_FRAME);
131 action = _UA_CLEANUP_PHASE;
135 _LIBUNWIND_TRACE_UNWINDING("_GCC_specific_handler() calling personality "
136 "function %p(1, %d, %llx, %p, %p)",
137 (void *)pers, action, exc->exception_class,
138 (void *)exc, (void *)ctx);
139 urc = pers(1, action, exc->exception_class, exc, ctx);
140 _LIBUNWIND_TRACE_UNWINDING("_GCC_specific_handler() personality returned %d", urc);
142 case _URC_CONTINUE_UNWIND:
143 // If we're in phase 2, and the personality routine said to continue
144 // at the target frame, we're in real trouble.
145 if (action & _UA_HANDLER_FRAME)
146 _LIBUNWIND_ABORT("Personality continued unwind at the target frame!");
147 return ExceptionContinueSearch;
148 case _URC_HANDLER_FOUND:
149 // If we were called by __libunwind_seh_personality(), indicate that
150 // a handler was found; otherwise, initiate phase 2 by unwinding.
151 if (ours && ms_exc->NumberParameters > 1)
152 return 4 /* ExecptionExecuteHandler in mingw */;
153 // This should never happen in phase 2.
154 if (IS_UNWINDING(ms_exc->ExceptionFlags))
155 _LIBUNWIND_ABORT("Personality indicated exception handler in phase 2!");
156 exc->private_[1] = (ULONG_PTR)frame;
158 ms_exc->NumberParameters = 4;
159 ms_exc->ExceptionInformation[1] = (ULONG_PTR)frame;
161 // FIXME: Indicate target frame in foreign case!
162 // phase 2: the clean up phase
163 RtlUnwindEx(frame, (PVOID)disp->ControlPc, ms_exc, exc, ms_ctx, disp->HistoryTable);
164 _LIBUNWIND_ABORT("RtlUnwindEx() failed");
165 case _URC_INSTALL_CONTEXT: {
166 // If we were called by __libunwind_seh_personality(), indicate that
167 // a handler was found; otherwise, it's time to initiate a collided
168 // unwind to the target.
169 if (ours && !IS_UNWINDING(ms_exc->ExceptionFlags) && ms_exc->NumberParameters > 1)
170 return 4 /* ExecptionExecuteHandler in mingw */;
171 // This should never happen in phase 1.
172 if (!IS_UNWINDING(ms_exc->ExceptionFlags))
173 _LIBUNWIND_ABORT("Personality installed context during phase 1!");
175 exc->private_[2] = disp->TargetIp;
176 __unw_get_reg(&cursor, UNW_X86_64_RAX, &retval);
177 __unw_get_reg(&cursor, UNW_X86_64_RDX, &exc->private_[3]);
178 #elif defined(__arm__)
179 exc->private_[2] = disp->TargetPc;
180 __unw_get_reg(&cursor, UNW_ARM_R0, &retval);
181 __unw_get_reg(&cursor, UNW_ARM_R1, &exc->private_[3]);
182 #elif defined(__aarch64__)
183 exc->private_[2] = disp->TargetPc;
184 __unw_get_reg(&cursor, UNW_ARM64_X0, &retval);
185 __unw_get_reg(&cursor, UNW_ARM64_X1, &exc->private_[3]);
187 __unw_get_reg(&cursor, UNW_REG_IP, &target);
188 ms_exc->ExceptionCode = STATUS_GCC_UNWIND;
190 ms_exc->ExceptionInformation[2] = disp->TargetIp;
191 #elif defined(__arm__) || defined(__aarch64__)
192 ms_exc->ExceptionInformation[2] = disp->TargetPc;
194 ms_exc->ExceptionInformation[3] = exc->private_[3];
195 // Give NTRTL some scratch space to keep track of the collided unwind.
196 // Don't use the one that was passed in; we don't want to overwrite the
197 // context in the DISPATCHER_CONTEXT.
199 RtlUnwindEx(frame, (PVOID)target, ms_exc, (PVOID)retval, &new_ctx, disp->HistoryTable);
200 _LIBUNWIND_ABORT("RtlUnwindEx() failed");
202 // Anything else indicates a serious problem.
203 default: return ExceptionContinueExecution;
207 /// Personality function returned by \c __unw_get_proc_info() in SEH contexts.
208 /// This is a wrapper that calls the real SEH handler function, which in
209 /// turn (at least, for Itanium-style frames) calls the real Itanium
210 /// personality function (see \c _GCC_specific_handler()).
211 extern "C" _Unwind_Reason_Code
212 __libunwind_seh_personality(int version, _Unwind_Action state,
213 uint64_t klass, _Unwind_Exception *exc,
214 struct _Unwind_Context *context) {
217 EXCEPTION_RECORD ms_exc;
218 bool phase2 = (state & (_UA_SEARCH_PHASE|_UA_CLEANUP_PHASE)) == _UA_CLEANUP_PHASE;
219 ms_exc.ExceptionCode = STATUS_GCC_THROW;
220 ms_exc.ExceptionFlags = 0;
221 ms_exc.NumberParameters = 3;
222 ms_exc.ExceptionInformation[0] = (ULONG_PTR)exc;
223 ms_exc.ExceptionInformation[1] = (ULONG_PTR)context;
224 ms_exc.ExceptionInformation[2] = state;
225 DISPATCHER_CONTEXT *disp_ctx =
226 __unw_seh_get_disp_ctx((unw_cursor_t *)context);
227 EXCEPTION_DISPOSITION ms_act = disp_ctx->LanguageHandler(&ms_exc,
228 (PVOID)disp_ctx->EstablisherFrame,
229 disp_ctx->ContextRecord,
232 case ExceptionContinueSearch: return _URC_CONTINUE_UNWIND;
233 case 4 /*ExceptionExecuteHandler*/:
234 return phase2 ? _URC_INSTALL_CONTEXT : _URC_HANDLER_FOUND;
236 return phase2 ? _URC_FATAL_PHASE2_ERROR : _URC_FATAL_PHASE1_ERROR;
240 static _Unwind_Reason_Code
241 unwind_phase2_forced(unw_context_t *uc,
242 _Unwind_Exception *exception_object,
243 _Unwind_Stop_Fn stop, void *stop_parameter) {
244 unw_cursor_t cursor2;
245 __unw_init_local(&cursor2, uc);
247 // Walk each frame until we reach where search phase said to stop
248 while (__unw_step(&cursor2) > 0) {
250 // Update info about this frame.
251 unw_proc_info_t frameInfo;
252 if (__unw_get_proc_info(&cursor2, &frameInfo) != UNW_ESUCCESS) {
253 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): __unw_step "
254 "failed => _URC_END_OF_STACK",
255 (void *)exception_object);
256 return _URC_FATAL_PHASE2_ERROR;
259 // When tracing, print state information.
260 if (_LIBUNWIND_TRACING_UNWINDING) {
261 char functionBuf[512];
262 const char *functionName = functionBuf;
264 if ((__unw_get_proc_name(&cursor2, functionBuf, sizeof(functionBuf),
265 &offset) != UNW_ESUCCESS) ||
266 (frameInfo.start_ip + offset > frameInfo.end_ip))
267 functionName = ".anonymous.";
268 _LIBUNWIND_TRACE_UNWINDING(
269 "unwind_phase2_forced(ex_ojb=%p): start_ip=0x%" PRIx64
270 ", func=%s, lsda=0x%" PRIx64 ", personality=0x%" PRIx64,
271 (void *)exception_object, frameInfo.start_ip, functionName,
272 frameInfo.lsda, frameInfo.handler);
275 // Call stop function at each frame.
276 _Unwind_Action action =
277 (_Unwind_Action)(_UA_FORCE_UNWIND | _UA_CLEANUP_PHASE);
278 _Unwind_Reason_Code stopResult =
279 (*stop)(1, action, exception_object->exception_class, exception_object,
280 (struct _Unwind_Context *)(&cursor2), stop_parameter);
281 _LIBUNWIND_TRACE_UNWINDING(
282 "unwind_phase2_forced(ex_ojb=%p): stop function returned %d",
283 (void *)exception_object, stopResult);
284 if (stopResult != _URC_NO_REASON) {
285 _LIBUNWIND_TRACE_UNWINDING(
286 "unwind_phase2_forced(ex_ojb=%p): stopped by stop function",
287 (void *)exception_object);
288 return _URC_FATAL_PHASE2_ERROR;
291 // If there is a personality routine, tell it we are unwinding.
292 if (frameInfo.handler != 0) {
293 __personality_routine p =
294 (__personality_routine)(intptr_t)(frameInfo.handler);
295 _LIBUNWIND_TRACE_UNWINDING(
296 "unwind_phase2_forced(ex_ojb=%p): calling personality function %p",
297 (void *)exception_object, (void *)(uintptr_t)p);
298 _Unwind_Reason_Code personalityResult =
299 (*p)(1, action, exception_object->exception_class, exception_object,
300 (struct _Unwind_Context *)(&cursor2));
301 switch (personalityResult) {
302 case _URC_CONTINUE_UNWIND:
303 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
304 "personality returned "
305 "_URC_CONTINUE_UNWIND",
306 (void *)exception_object);
307 // Destructors called, continue unwinding
309 case _URC_INSTALL_CONTEXT:
310 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
311 "personality returned "
312 "_URC_INSTALL_CONTEXT",
313 (void *)exception_object);
314 // We may get control back if landing pad calls _Unwind_Resume().
315 __unw_resume(&cursor2);
318 // Personality routine returned an unknown result code.
319 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): "
320 "personality returned %d, "
321 "_URC_FATAL_PHASE2_ERROR",
322 (void *)exception_object, personalityResult);
323 return _URC_FATAL_PHASE2_ERROR;
328 // Call stop function one last time and tell it we've reached the end
330 _LIBUNWIND_TRACE_UNWINDING("unwind_phase2_forced(ex_ojb=%p): calling stop "
331 "function with _UA_END_OF_STACK",
332 (void *)exception_object);
333 _Unwind_Action lastAction =
334 (_Unwind_Action)(_UA_FORCE_UNWIND | _UA_CLEANUP_PHASE | _UA_END_OF_STACK);
335 (*stop)(1, lastAction, exception_object->exception_class, exception_object,
336 (struct _Unwind_Context *)(&cursor2), stop_parameter);
338 // Clean up phase did not resume at the frame that the search phase said it
340 return _URC_FATAL_PHASE2_ERROR;
343 /// Called by \c __cxa_throw(). Only returns if there is a fatal error.
344 _LIBUNWIND_EXPORT _Unwind_Reason_Code
345 _Unwind_RaiseException(_Unwind_Exception *exception_object) {
346 _LIBUNWIND_TRACE_API("_Unwind_RaiseException(ex_obj=%p)",
347 (void *)exception_object);
349 // Mark that this is a non-forced unwind, so _Unwind_Resume()
350 // can do the right thing.
351 memset(exception_object->private_, 0, sizeof(exception_object->private_));
353 // phase 1: the search phase
354 // We'll let the system do that for us.
355 RaiseException(STATUS_GCC_THROW, 0, 1, (ULONG_PTR *)&exception_object);
357 // If we get here, either something went horribly wrong or we reached the
358 // top of the stack. Either way, let libc++abi call std::terminate().
359 return _URC_END_OF_STACK;
362 /// When \c _Unwind_RaiseException() is in phase2, it hands control
363 /// to the personality function at each frame. The personality
364 /// may force a jump to a landing pad in that function; the landing
365 /// pad code may then call \c _Unwind_Resume() to continue with the
366 /// unwinding. Note: the call to \c _Unwind_Resume() is from compiler
367 /// geneated user code. All other \c _Unwind_* routines are called
368 /// by the C++ runtime \c __cxa_* routines.
370 /// Note: re-throwing an exception (as opposed to continuing the unwind)
371 /// is implemented by having the code call \c __cxa_rethrow() which
372 /// in turn calls \c _Unwind_Resume_or_Rethrow().
373 _LIBUNWIND_EXPORT void
374 _Unwind_Resume(_Unwind_Exception *exception_object) {
375 _LIBUNWIND_TRACE_API("_Unwind_Resume(ex_obj=%p)", (void *)exception_object);
377 if (exception_object->private_[0] != 0) {
380 __unw_getcontext(&uc);
381 unwind_phase2_forced(&uc, exception_object,
382 (_Unwind_Stop_Fn) exception_object->private_[0],
383 (void *)exception_object->private_[4]);
385 // Recover the parameters for the unwind from the exception object
386 // so we can start unwinding again.
387 EXCEPTION_RECORD ms_exc;
389 UNWIND_HISTORY_TABLE hist;
391 memset(&ms_exc, 0, sizeof(ms_exc));
392 memset(&hist, 0, sizeof(hist));
393 ms_exc.ExceptionCode = STATUS_GCC_THROW;
394 ms_exc.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
395 ms_exc.NumberParameters = 4;
396 ms_exc.ExceptionInformation[0] = (ULONG_PTR)exception_object;
397 ms_exc.ExceptionInformation[1] = exception_object->private_[1];
398 ms_exc.ExceptionInformation[2] = exception_object->private_[2];
399 ms_exc.ExceptionInformation[3] = exception_object->private_[3];
400 RtlUnwindEx((PVOID)exception_object->private_[1],
401 (PVOID)exception_object->private_[2], &ms_exc,
402 exception_object, &ms_ctx, &hist);
405 // Clients assume _Unwind_Resume() does not return, so all we can do is abort.
406 _LIBUNWIND_ABORT("_Unwind_Resume() can't return");
410 /// Unwinds stack, calling "stop" function at each frame.
411 /// Could be used to implement \c longjmp().
412 _LIBUNWIND_EXPORT _Unwind_Reason_Code
413 _Unwind_ForcedUnwind(_Unwind_Exception *exception_object,
414 _Unwind_Stop_Fn stop, void *stop_parameter) {
415 _LIBUNWIND_TRACE_API("_Unwind_ForcedUnwind(ex_obj=%p, stop=%p)",
416 (void *)exception_object, (void *)(uintptr_t)stop);
418 __unw_getcontext(&uc);
420 // Mark that this is a forced unwind, so _Unwind_Resume() can do
422 exception_object->private_[0] = (uintptr_t) stop;
423 exception_object->private_[4] = (uintptr_t) stop_parameter;
426 return unwind_phase2_forced(&uc, exception_object, stop, stop_parameter);
429 /// Called by personality handler during phase 2 to get LSDA for current frame.
430 _LIBUNWIND_EXPORT uintptr_t
431 _Unwind_GetLanguageSpecificData(struct _Unwind_Context *context) {
433 (uintptr_t)__unw_seh_get_disp_ctx((unw_cursor_t *)context)->HandlerData;
434 _LIBUNWIND_TRACE_API(
435 "_Unwind_GetLanguageSpecificData(context=%p) => 0x%" PRIxPTR,
436 (void *)context, result);
440 /// Called by personality handler during phase 2 to find the start of the
442 _LIBUNWIND_EXPORT uintptr_t
443 _Unwind_GetRegionStart(struct _Unwind_Context *context) {
444 DISPATCHER_CONTEXT *disp = __unw_seh_get_disp_ctx((unw_cursor_t *)context);
445 uintptr_t result = (uintptr_t)disp->FunctionEntry->BeginAddress + disp->ImageBase;
446 _LIBUNWIND_TRACE_API("_Unwind_GetRegionStart(context=%p) => 0x%" PRIxPTR,
447 (void *)context, result);
451 static int __unw_init_seh(unw_cursor_t *cursor, CONTEXT *context) {
452 #ifdef _LIBUNWIND_TARGET_X86_64
453 new (reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_x86_64> *>(cursor))
454 UnwindCursor<LocalAddressSpace, Registers_x86_64>(
455 context, LocalAddressSpace::sThisAddressSpace);
456 auto *co = reinterpret_cast<AbstractUnwindCursor *>(cursor);
457 co->setInfoBasedOnIPRegister();
459 #elif defined(_LIBUNWIND_TARGET_ARM)
460 new (reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_arm> *>(cursor))
461 UnwindCursor<LocalAddressSpace, Registers_arm>(
462 context, LocalAddressSpace::sThisAddressSpace);
463 auto *co = reinterpret_cast<AbstractUnwindCursor *>(cursor);
464 co->setInfoBasedOnIPRegister();
466 #elif defined(_LIBUNWIND_TARGET_AARCH64)
467 new (reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_arm64> *>(cursor))
468 UnwindCursor<LocalAddressSpace, Registers_arm64>(
469 context, LocalAddressSpace::sThisAddressSpace);
470 auto *co = reinterpret_cast<AbstractUnwindCursor *>(cursor);
471 co->setInfoBasedOnIPRegister();
478 static DISPATCHER_CONTEXT *__unw_seh_get_disp_ctx(unw_cursor_t *cursor) {
479 #ifdef _LIBUNWIND_TARGET_X86_64
480 return reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_x86_64> *>(cursor)->getDispatcherContext();
481 #elif defined(_LIBUNWIND_TARGET_ARM)
482 return reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_arm> *>(cursor)->getDispatcherContext();
483 #elif defined(_LIBUNWIND_TARGET_AARCH64)
484 return reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_arm64> *>(cursor)->getDispatcherContext();
490 static void __unw_seh_set_disp_ctx(unw_cursor_t *cursor,
491 DISPATCHER_CONTEXT *disp) {
492 #ifdef _LIBUNWIND_TARGET_X86_64
493 reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_x86_64> *>(cursor)->setDispatcherContext(disp);
494 #elif defined(_LIBUNWIND_TARGET_ARM)
495 reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_arm> *>(cursor)->setDispatcherContext(disp);
496 #elif defined(_LIBUNWIND_TARGET_AARCH64)
497 reinterpret_cast<UnwindCursor<LocalAddressSpace, Registers_arm64> *>(cursor)->setDispatcherContext(disp);
501 #endif // defined(_LIBUNWIND_SUPPORT_SEH_UNWIND)