Merge pull request #927 from mugurc/libc-exceptions

feat(libc): exception runtime on macOS hosts
This commit is contained in:
Adrià
2026-10-08 12:35:51 +02:00
committed by GitHub
12 changed files with 355 additions and 26 deletions
+16 -9
View File
@@ -4,6 +4,7 @@ target_sources(libc PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src/specifics/gcc/StackGuard.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/specifics/windows/CrashReport.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/specifics/linux/DlIteratePhdr.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/specifics/macos/GuestImages.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/Strings.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/AllocatingStrings.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/WideConversion.cpp
@@ -263,15 +264,21 @@ if(BUILD_TESTING)
target_include_directories(exception_runtime_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(exception_runtime_tests PRIVATE libc)
add_test(NAME exception_runtime COMMAND exception_runtime_tests)
enable_language(C)
add_test_executable(exception_c_cleanup_tests ${LIBS_INCLUDE_DIR}/tests/ExceptionCCleanup.cpp ${LIBS_INCLUDE_DIR}/tests/ExceptionCCleanup.c)
set_source_files_properties(${LIBS_INCLUDE_DIR}/tests/ExceptionCCleanup.c PROPERTIES COMPILE_OPTIONS -fexceptions)
target_link_libraries(exception_c_cleanup_tests PRIVATE libc)
add_test(NAME exception_c_cleanup COMMAND exception_c_cleanup_tests)
add_test_executable(guest_image_anonymous_tests ${LIBS_INCLUDE_DIR}/tests/GuestImageAnonymous.cpp)
target_include_directories(guest_image_anonymous_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_image_anonymous_tests PRIVATE libc)
add_test(NAME guest_image_anonymous COMMAND guest_image_anonymous_tests)
add_test_executable(exception_personality_tests ${LIBS_INCLUDE_DIR}/tests/ExceptionPersonality.cpp)
target_include_directories(exception_personality_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(exception_personality_tests PRIVATE libc)
add_test(NAME exception_personality COMMAND exception_personality_tests)
if(NOT APPLE)
enable_language(C)
add_test_executable(exception_c_cleanup_tests ${LIBS_INCLUDE_DIR}/tests/ExceptionCCleanup.cpp ${LIBS_INCLUDE_DIR}/tests/ExceptionCCleanup.c)
set_source_files_properties(${LIBS_INCLUDE_DIR}/tests/ExceptionCCleanup.c PROPERTIES COMPILE_OPTIONS -fexceptions)
target_link_libraries(exception_c_cleanup_tests PRIVATE libc)
add_test(NAME exception_c_cleanup COMMAND exception_c_cleanup_tests)
add_test_executable(guest_image_anonymous_tests ${LIBS_INCLUDE_DIR}/tests/GuestImageAnonymous.cpp)
target_include_directories(guest_image_anonymous_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_image_anonymous_tests PRIVATE libc)
add_test(NAME guest_image_anonymous COMMAND guest_image_anonymous_tests)
endif()
endif()
endif()
@@ -99,6 +99,7 @@ inline unsigned EncodingSize(Byte encoding) {
extern "C" {
_Unwind_Reason_Code APS5_VABI __gxx_personality_v0_nid_postfix(int, _Unwind_Action, std::uint64_t, _Unwind_Exception*, _Unwind_Context*);
_Unwind_Reason_Code APS5_VABI __gcc_personality_v0_nid_postfix(int, _Unwind_Action, std::uint64_t, _Unwind_Exception*, _Unwind_Context*);
_Unwind_Reason_Code APS5_VABI _Unwind_RaiseException_nid_postfix(_Unwind_Exception*);
[[noreturn]] void APS5_VABI _Unwind_Resume_nid_postfix(_Unwind_Exception*);
_Unwind_Reason_Code APS5_VABI _Unwind_Resume_or_Rethrow_nid_postfix(_Unwind_Exception*);
@@ -3,4 +3,51 @@
#include <cxxabi.h>
#ifdef _LIBCPPABI_VERSION
#include <typeinfo>
namespace __cxxabiv1 {
class __class_type_info : public std::type_info {
public:
enum __sub_kind { __unknown = 0 };
struct __upcast_result;
struct __dyncast_result;
};
class __si_class_type_info : public __class_type_info {
public:
const __class_type_info* __base_type;
};
struct __base_class_type_info {
const __class_type_info* __base_type;
long __offset_flags;
};
class __vmi_class_type_info : public __class_type_info {
public:
unsigned int __flags;
unsigned int __base_count;
__base_class_type_info __base_info[1];
};
class __pbase_type_info : public std::type_info {
public:
unsigned int __flags;
const std::type_info* __pointee;
};
class __pointer_type_info : public __pbase_type_info {};
class __pointer_to_member_type_info : public __pbase_type_info {
public:
const __class_type_info* __context;
};
#ifdef __APPLE__
extern "C" int __cxa_thread_atexit(void (*)(void*), void*, void*) noexcept;
#endif
}
#endif
#endif
@@ -27,6 +27,10 @@ static constexpr std::uint32_t PT_GNU_EH_FRAME = 0x6474e550;
static constexpr std::uint32_t PF_X = 1;
static constexpr std::uint32_t PF_W = 2;
#ifdef __APPLE__
extern "C" int dl_iterate_phdr(int (*callback)(dl_phdr_info*, std::size_t, void*), void* data) __asm__("_dl_iterate_phdr_nid_no_patch");
#else
extern "C" int dl_iterate_phdr(int (*callback)(dl_phdr_info*, std::size_t, void*), void* data);
#endif
#endif
+1 -1
View File
@@ -4,7 +4,7 @@
#define _UNWIND_H
#endif
#include <cxxabi.h>
#include "prx/libc/include/specifics/itanium/CxxAbi.hpp"
#include <cstdint>
#include <cstdio>
#include <cstdlib>
@@ -1,5 +1,6 @@
#include <exception>
#ifndef _LIBCPP_VERSION
extern "C" {
void ExceptionPointerAddref(std::exception_ptr* self) noexcept asm("_ZNSt15__exception_ptr13exception_ptr9_M_addrefEv");
void ExceptionPointerRelease(std::exception_ptr* self) noexcept asm("_ZNSt15__exception_ptr13exception_ptr10_M_releaseEv");
@@ -79,3 +80,53 @@ const type_info* exception_ptr::__cxa_exception_type() const noexcept {
}
}
#else
namespace {
struct GuestExceptionPointer {
void* object {};
explicit GuestExceptionPointer(void* primary) noexcept : object(primary) {}
GuestExceptionPointer(const GuestExceptionPointer&) = delete;
~GuestExceptionPointer() {}
};
}
extern "C" {
void APS5_VABI _ZNSt15__exception_ptr13exception_ptr9_M_addrefEv_nid_postfix(GuestExceptionPointer* self) noexcept {
__cxa_increment_exception_refcount_nid_postfix(self->object);
}
void APS5_VABI _ZNSt15__exception_ptr13exception_ptr10_M_releaseEv_nid_postfix(GuestExceptionPointer* self) noexcept {
__cxa_decrement_exception_refcount_nid_postfix(self->object);
self->object = nullptr;
}
void* APS5_VABI _ZNKSt15__exception_ptr13exception_ptr6_M_getEv_nid_postfix(const GuestExceptionPointer* self) noexcept {
return self->object;
}
void APS5_VABI _ZNSt15__exception_ptr13exception_ptrC1EPv_nid_postfix(GuestExceptionPointer* self, void* exception) noexcept {
self->object = exception;
__cxa_increment_exception_refcount_nid_postfix(exception);
}
void APS5_VABI _ZNSt15__exception_ptr13exception_ptrC2EPv_nid_postfix(GuestExceptionPointer* self, void* exception) noexcept {
_ZNSt15__exception_ptr13exception_ptrC1EPv_nid_postfix(self, exception);
}
const std::type_info* APS5_VABI _ZNKSt15__exception_ptr13exception_ptr20__cxa_exception_typeEv_nid_postfix(const GuestExceptionPointer* self) noexcept {
return LibcException::FromObject(self->object)->type;
}
GuestExceptionPointer APS5_VABI _ZSt17current_exceptionv_nid_postfix() noexcept {
return GuestExceptionPointer(__cxa_current_primary_exception_nid_postfix());
}
[[noreturn]] void APS5_VABI _ZSt17rethrow_exceptionNSt15__exception_ptr13exception_ptrE_nid_postfix(GuestExceptionPointer& exception) {
__cxa_rethrow_primary_exception_nid_postfix(exception.object);
LibcException::Terminate();
}
}
#endif
@@ -71,14 +71,7 @@ extern "C" _Unwind_Reason_Code APS5_VABI __gxx_personality_v0_nid_postfix(
return _URC_CONTINUE_UNWIND;
}
extern "C" _Unwind_Reason_Code __gxx_personality_v0(
int version, _Unwind_Action actions, std::uint64_t exceptionClass,
_Unwind_Exception* exception, _Unwind_Context* context
) {
return __gxx_personality_v0_nid_postfix(version, actions, exceptionClass, exception, context);
}
extern "C" _Unwind_Reason_Code __gcc_personality_v0(
extern "C" _Unwind_Reason_Code APS5_VABI __gcc_personality_v0_nid_postfix(
int version, _Unwind_Action actions, std::uint64_t,
_Unwind_Exception* exception, _Unwind_Context* context
) {
@@ -107,3 +100,19 @@ extern "C" _Unwind_Reason_Code __gcc_personality_v0(
}
return _URC_CONTINUE_UNWIND;
}
#ifndef __APPLE__
extern "C" _Unwind_Reason_Code __gxx_personality_v0(
int version, _Unwind_Action actions, std::uint64_t exceptionClass,
_Unwind_Exception* exception, _Unwind_Context* context
) {
return __gxx_personality_v0_nid_postfix(version, actions, exceptionClass, exception, context);
}
extern "C" _Unwind_Reason_Code __gcc_personality_v0(
int version, _Unwind_Action actions, std::uint64_t exceptionClass,
_Unwind_Exception* exception, _Unwind_Context* context
) {
return __gcc_personality_v0_nid_postfix(version, actions, exceptionClass, exception, context);
}
#endif
+34 -7
View File
@@ -5,13 +5,16 @@
#ifdef _WIN32
#include <windows.h>
#endif
#ifdef __APPLE__
#include <dlfcn.h>
#include <mach-o/getsect.h>
#include <mach-o/loader.h>
#endif
#if defined(__linux__) || defined(_WIN32)
#if defined(__linux__) || defined(_WIN32) || defined(__APPLE__)
#if defined(_WIN32) || defined(__linux__)
extern "C" _Unwind_Reason_Code __gxx_personality_v0(int, _Unwind_Action, std::uint64_t, _Unwind_Exception*, _Unwind_Context*);
extern "C" _Unwind_Reason_Code __gcc_personality_v0(int, _Unwind_Action, std::uint64_t, _Unwind_Exception*, _Unwind_Context*);
#endif
namespace LibcUnwind {
_Unwind_Reason_Code CallPersonality(Word personality, _Unwind_Action actions, _Unwind_Exception* exception, _Unwind_Context* context) {
@@ -25,13 +28,13 @@ _Unwind_Reason_Code CallPersonality(Word personality, _Unwind_Action actions, _U
#endif
if (personality == reinterpret_cast<Word>(__gxx_personality_v0_nid_postfix) || personality == reinterpret_cast<Word>(__gxx_personality_v0))
return __gxx_personality_v0_nid_postfix(1, actions, exception->exception_class, exception, context);
if (personality == reinterpret_cast<Word>(__gcc_personality_v0))
return __gcc_personality_v0(1, actions, exception->exception_class, exception, context);
if (personality == reinterpret_cast<Word>(__gcc_personality_v0_nid_postfix) || personality == reinterpret_cast<Word>(__gcc_personality_v0))
return __gcc_personality_v0_nid_postfix(1, actions, exception->exception_class, exception, context);
return (actions & _UA_SEARCH_PHASE) ? _URC_FATAL_PHASE1_ERROR : _URC_FATAL_PHASE2_ERROR;
}
struct Lookup { Word pc; const Byte* fde {}; Word text {}; Word data {}; };
#ifdef __linux__
#if defined(__linux__) || defined(__APPLE__)
int FindFrame(dl_phdr_info* info, std::size_t, void* argument) {
auto& query = *static_cast<Lookup*>(argument);
const Byte* header = nullptr;
@@ -141,8 +144,32 @@ bool DecodeCandidate(_Unwind_Context& context, Frame& frame, const Lookup& query
bool DecodeFrame(_Unwind_Context& context, Frame& frame) {
Lookup query {context.registers[16] - !context.signalFrame};
#ifdef __linux__
#if defined(__linux__) || defined(__APPLE__)
dl_iterate_phdr(FindFrame, &query);
#ifdef __APPLE__
if (!query.fde) {
Dl_info image {};
if (!dladdr(reinterpret_cast<void*>(query.pc), &image) || !image.dli_fbase) return false;
unsigned long size = 0;
const Byte* p = getsectiondata(static_cast<const mach_header_64*>(image.dli_fbase), "__TEXT", "__eh_frame", &size);
if (!p) return false;
const Byte* end = p + size;
while (end - p >= 8) {
const Byte* record = p;
const auto length = Read<std::uint32_t>(p);
if (length == 0) return false;
if (length == 0xffffffff || length < 4 || Word(end - p) < length) return false;
const Byte* next = p + length;
if (Read<std::uint32_t>(p)) {
query.fde = record;
frame = {};
if (DecodeCandidate(context, frame, query)) return true;
}
p = next;
}
return false;
}
#endif
return DecodeCandidate(context, frame, query);
#else
MEMORY_BASIC_INFORMATION memory{};
@@ -7,7 +7,7 @@
extern "C" {
int APS5_VABI dl_iterate_phdr_nid_postfix(int (*callback)(dl_phdr_info*, std::size_t, void*), void* data) {
#if defined(__linux__)
#if defined(__linux__) || defined(__APPLE__)
return dl_iterate_phdr(callback, data);
#else
(void)callback;
@@ -0,0 +1,42 @@
#ifdef __APPLE__
#include "prx/libc/include/specifics/linux/ElfTypes.hpp"
#include <mach-o/dyld.h>
#include <mach-o/getsect.h>
#include <mach-o/loader.h>
#include <cstring>
namespace {
constexpr std::uint64_t MetaVersion = 2;
constexpr std::size_t LoadBiasOffset = 0x08;
constexpr std::size_t HeaderCountOffset = 0x58;
constexpr std::size_t HeadersOffset = 0x60;
}
extern "C" int dl_iterate_phdr(int (*callback)(dl_phdr_info*, std::size_t, void*), void* data) {
for (std::uint32_t index = 0; index < _dyld_image_count(); ++index) {
const auto* header = reinterpret_cast<const mach_header_64*>(_dyld_get_image_header(index));
if (header == nullptr || header->magic != MH_MAGIC_64 || (header->flags & MH_DYLIB_IN_CACHE) != 0) continue;
unsigned long size = 0;
const auto* meta = getsectiondata(header, "__APS5DATA", "__meta", &size);
if (meta == nullptr || size < HeadersOffset) continue;
std::uint64_t version;
std::uint64_t loadBias;
std::uint64_t count;
std::memcpy(&version, meta, sizeof(version));
std::memcpy(&loadBias, meta + LoadBiasOffset, sizeof(loadBias));
std::memcpy(&count, meta + HeaderCountOffset, sizeof(count));
if (version != MetaVersion || count > 0xffff || count > (size - HeadersOffset) / sizeof(Elf64_Phdr)) continue;
dl_phdr_info info {};
info.dlpi_addr = static_cast<std::uintptr_t>(loadBias);
info.dlpi_name = header->filetype == MH_EXECUTE ? "" : _dyld_get_image_name(index);
info.dlpi_phdr = reinterpret_cast<const Elf64_Phdr*>(meta + HeadersOffset);
info.dlpi_phnum = static_cast<std::uint16_t>(count);
if (const int result = callback(&info, sizeof(info), data); result != 0) return result;
}
return 0;
}
#endif
@@ -11,6 +11,10 @@
#ifdef _WIN32
#include <windows.h>
#include <psapi.h>
#elif defined(__APPLE__)
#include <dlfcn.h>
#include <mach-o/getsect.h>
#include <mach-o/loader.h>
#else
#include <fstream>
#endif
@@ -107,6 +111,51 @@ int APS5_VABI sceKernelGetModuleInfoForUnwind(uint64_t addr, int flags, ModuleIn
std::strncpy(info->name, path, sizeof(info->name) - 1);
info->name[sizeof(info->name) - 1] = '\0';
return 0;
#elif defined(__APPLE__)
struct Search {
std::uint64_t address;
ModuleInfoForUnwind* info;
bool found;
} search {addr, info, false};
dl_iterate_phdr([](dl_phdr_info* image, std::size_t, void* data) {
auto& search = *static_cast<Search*>(data);
const Elf64_Phdr* first = nullptr;
const Elf64_Phdr* frames = nullptr;
bool contains = false;
for (std::uint16_t index = 0; index < image->dlpi_phnum; ++index) {
const auto& header = image->dlpi_phdr[index];
const auto start = image->dlpi_addr + header.p_vaddr;
if (header.p_type == PT_LOAD && first == nullptr) first = &header;
if (header.p_type == PT_LOAD && search.address >= start && search.address - start < header.p_memsz) contains = true;
if (header.p_type == PT_GNU_EH_FRAME) frames = &header;
}
if (!contains) return 0;
auto* info = search.info;
info->st_size = sizeof(ModuleInfoForUnwind);
std::strncpy(info->name, image->dlpi_name != nullptr ? image->dlpi_name : "", sizeof(info->name) - 1);
info->name[sizeof(info->name) - 1] = '\0';
info->eh_frame_hdr_addr = frames != nullptr ? image->dlpi_addr + frames->p_vaddr : 0;
info->eh_frame_addr = 0;
info->eh_frame_size = 0;
info->seg0_addr = image->dlpi_addr + first->p_vaddr;
info->seg0_size = first->p_memsz;
search.found = true;
return 1;
}, &search);
if (search.found) return 0;
Dl_info image {};
if (!dladdr(reinterpret_cast<void*>(addr), &image) || image.dli_fbase == nullptr) return SCE_KERNEL_ERROR_ESRCH;
unsigned long textSize = 0;
getsegmentdata(static_cast<const mach_header_64*>(image.dli_fbase), "__TEXT", &textSize);
info->st_size = sizeof(ModuleInfoForUnwind);
std::strncpy(info->name, image.dli_fname != nullptr ? image.dli_fname : "", sizeof(info->name) - 1);
info->name[sizeof(info->name) - 1] = '\0';
info->eh_frame_hdr_addr = 0;
info->eh_frame_addr = 0;
info->eh_frame_size = 0;
info->seg0_addr = reinterpret_cast<std::uint64_t>(image.dli_fbase);
info->seg0_size = textSize;
return 0;
#else
std::ifstream maps("/proc/self/maps");
if (!maps) throw std::runtime_error("sceKernelGetModuleInfoForUnwind: failed to open /proc/self/maps");
+92
View File
@@ -0,0 +1,92 @@
#include "prx/libc/include/exceptions/Unwind.hpp"
#include <cstdio>
#include <cstdlib>
namespace LibcUnwind {
_Unwind_Reason_Code CallPersonality(Word personality, _Unwind_Action actions, _Unwind_Exception* exception, _Unwind_Context* context);
}
static void Require(bool value) { if (!value) std::abort(); }
static const unsigned char cleanupTable[] = {0xff, 0xff, 0x01, 0x04, 0x10, 0x20, 0x40, 0x00};
static const unsigned char noLandingTable[] = {0xff, 0xff, 0x01, 0x04, 0x10, 0x20, 0x00, 0x00};
constexpr std::uintptr_t region = 0x10000;
struct Frame {
_Unwind_Context context {};
_Unwind_Exception exception {};
Frame(const unsigned char* table, std::uintptr_t resume, bool signalFrame = false) {
context.region = region;
context.lsda = reinterpret_cast<std::uintptr_t>(table);
context.registers[16] = region + resume;
context.signalFrame = signalFrame;
}
};
static _Unwind_Reason_Code Direct(Frame& frame, _Unwind_Action actions, int version = 1) {
return __gcc_personality_v0_nid_postfix(version, actions, 0, &frame.exception, &frame.context);
}
static _Unwind_Reason_Code Routed(Frame& frame, _Unwind_Action actions) {
return LibcUnwind::CallPersonality(reinterpret_cast<std::uintptr_t>(__gcc_personality_v0_nid_postfix), actions, &frame.exception, &frame.context);
}
static void RequireInstalled(Frame& frame) {
Require(frame.context.registers[0] == reinterpret_cast<std::uintptr_t>(&frame.exception));
Require(frame.context.registers[1] == 0);
Require(frame.context.registers[16] == region + 0x40);
}
int main() {
{
Frame frame(cleanupTable, 0x18);
Require(Direct(frame, _UA_CLEANUP_PHASE) == _URC_INSTALL_CONTEXT);
RequireInstalled(frame);
}
{
Frame frame(cleanupTable, 0x18);
Require(Routed(frame, _UA_CLEANUP_PHASE) == _URC_INSTALL_CONTEXT);
RequireInstalled(frame);
}
{
Frame frame(cleanupTable, 0x18);
Require(Direct(frame, _UA_SEARCH_PHASE) == _URC_CONTINUE_UNWIND);
Require(frame.context.registers[16] == region + 0x18);
}
{
Frame frame(cleanupTable, 0x18);
Require(Routed(frame, _UA_SEARCH_PHASE) == _URC_CONTINUE_UNWIND);
}
{
Frame before(cleanupTable, 0x10);
Require(Direct(before, _UA_CLEANUP_PHASE) == _URC_CONTINUE_UNWIND);
Frame after(cleanupTable, 0x31);
Require(Direct(after, _UA_CLEANUP_PHASE) == _URC_CONTINUE_UNWIND);
}
{
Frame frame(cleanupTable, 0x10, true);
Require(Direct(frame, _UA_CLEANUP_PHASE) == _URC_INSTALL_CONTEXT);
RequireInstalled(frame);
}
{
Frame frame(noLandingTable, 0x18);
Require(Direct(frame, _UA_CLEANUP_PHASE) == _URC_CONTINUE_UNWIND);
}
{
Frame frame(nullptr, 0x18);
Require(Direct(frame, _UA_CLEANUP_PHASE) == _URC_CONTINUE_UNWIND);
}
{
Frame frame(cleanupTable, 0x18);
Require(Direct(frame, _UA_CLEANUP_PHASE, 2) == _URC_FATAL_PHASE1_ERROR);
}
{
Frame frame(cleanupTable, 0x18);
Require(LibcUnwind::CallPersonality(0x1000, _UA_SEARCH_PHASE, &frame.exception, &frame.context) == _URC_FATAL_PHASE1_ERROR);
Require(LibcUnwind::CallPersonality(0x1000, _UA_CLEANUP_PHASE, &frame.exception, &frame.context) == _URC_FATAL_PHASE2_ERROR);
}
std::puts("exception personality tests passed");
return 0;
}