Path: blob/main/contrib/llvm-project/libunwind/src/libunwind.cpp
35148 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//7// Implements unw_* functions from <libunwind.h>8//9//===----------------------------------------------------------------------===//1011#include <libunwind.h>1213#include "config.h"14#include "libunwind_ext.h"1516#include <stdlib.h>1718// Define the __has_feature extension for compilers that do not support it so19// that we can later check for the presence of ASan in a compiler-neutral way.20#if !defined(__has_feature)21#define __has_feature(feature) 022#endif2324#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)25#include <sanitizer/asan_interface.h>26#endif2728#if !defined(__USING_SJLJ_EXCEPTIONS__) && !defined(__wasm__)29#include "AddressSpace.hpp"30#include "UnwindCursor.hpp"3132using namespace libunwind;3334/// internal object to represent this processes address space35LocalAddressSpace LocalAddressSpace::sThisAddressSpace;3637_LIBUNWIND_EXPORT unw_addr_space_t unw_local_addr_space =38(unw_addr_space_t)&LocalAddressSpace::sThisAddressSpace;3940/// Create a cursor of a thread in this process given 'context' recorded by41/// __unw_getcontext().42_LIBUNWIND_HIDDEN int __unw_init_local(unw_cursor_t *cursor,43unw_context_t *context) {44_LIBUNWIND_TRACE_API("__unw_init_local(cursor=%p, context=%p)",45static_cast<void *>(cursor),46static_cast<void *>(context));47#if defined(__i386__)48# define REGISTER_KIND Registers_x8649#elif defined(__x86_64__)50# define REGISTER_KIND Registers_x86_6451#elif defined(__powerpc64__)52# define REGISTER_KIND Registers_ppc6453#elif defined(__powerpc__)54# define REGISTER_KIND Registers_ppc55#elif defined(__aarch64__)56# define REGISTER_KIND Registers_arm6457#elif defined(__arm__)58# define REGISTER_KIND Registers_arm59#elif defined(__or1k__)60# define REGISTER_KIND Registers_or1k61#elif defined(__hexagon__)62# define REGISTER_KIND Registers_hexagon63#elif defined(__mips__) && defined(_ABIO32) && _MIPS_SIM == _ABIO3264# define REGISTER_KIND Registers_mips_o3265#elif defined(__mips64)66# define REGISTER_KIND Registers_mips_newabi67#elif defined(__mips__)68# warning The MIPS architecture is not supported with this ABI and environment!69#elif defined(__sparc__) && defined(__arch64__)70#define REGISTER_KIND Registers_sparc6471#elif defined(__sparc__)72# define REGISTER_KIND Registers_sparc73#elif defined(__riscv)74# define REGISTER_KIND Registers_riscv75#elif defined(__ve__)76# define REGISTER_KIND Registers_ve77#elif defined(__s390x__)78# define REGISTER_KIND Registers_s390x79#elif defined(__loongarch__) && __loongarch_grlen == 6480#define REGISTER_KIND Registers_loongarch81#else82# error Architecture not supported83#endif84// Use "placement new" to allocate UnwindCursor in the cursor buffer.85new (reinterpret_cast<UnwindCursor<LocalAddressSpace, REGISTER_KIND> *>(cursor))86UnwindCursor<LocalAddressSpace, REGISTER_KIND>(87context, LocalAddressSpace::sThisAddressSpace);88#undef REGISTER_KIND89AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;90co->setInfoBasedOnIPRegister();9192return UNW_ESUCCESS;93}94_LIBUNWIND_WEAK_ALIAS(__unw_init_local, unw_init_local)9596/// Get value of specified register at cursor position in stack frame.97_LIBUNWIND_HIDDEN int __unw_get_reg(unw_cursor_t *cursor, unw_regnum_t regNum,98unw_word_t *value) {99_LIBUNWIND_TRACE_API("__unw_get_reg(cursor=%p, regNum=%d, &value=%p)",100static_cast<void *>(cursor), regNum,101static_cast<void *>(value));102AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;103if (co->validReg(regNum)) {104*value = co->getReg(regNum);105return UNW_ESUCCESS;106}107return UNW_EBADREG;108}109_LIBUNWIND_WEAK_ALIAS(__unw_get_reg, unw_get_reg)110111/// Set value of specified register at cursor position in stack frame.112_LIBUNWIND_HIDDEN int __unw_set_reg(unw_cursor_t *cursor, unw_regnum_t regNum,113unw_word_t value) {114_LIBUNWIND_TRACE_API("__unw_set_reg(cursor=%p, regNum=%d, value=0x%" PRIxPTR115")",116static_cast<void *>(cursor), regNum, value);117typedef LocalAddressSpace::pint_t pint_t;118AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;119if (co->validReg(regNum)) {120co->setReg(regNum, (pint_t)value);121// special case altering IP to re-find info (being called by personality122// function)123if (regNum == UNW_REG_IP) {124unw_proc_info_t info;125// First, get the FDE for the old location and then update it.126co->getInfo(&info);127co->setInfoBasedOnIPRegister(false);128// If the original call expects stack adjustment, perform this now.129// Normal frame unwinding would have included the offset already in the130// CFA computation.131// Note: for PA-RISC and other platforms where the stack grows up,132// this should actually be - info.gp. LLVM doesn't currently support133// any such platforms and Clang doesn't export a macro for them.134if (info.gp)135co->setReg(UNW_REG_SP, co->getReg(UNW_REG_SP) + info.gp);136}137return UNW_ESUCCESS;138}139return UNW_EBADREG;140}141_LIBUNWIND_WEAK_ALIAS(__unw_set_reg, unw_set_reg)142143/// Get value of specified float register at cursor position in stack frame.144_LIBUNWIND_HIDDEN int __unw_get_fpreg(unw_cursor_t *cursor, unw_regnum_t regNum,145unw_fpreg_t *value) {146_LIBUNWIND_TRACE_API("__unw_get_fpreg(cursor=%p, regNum=%d, &value=%p)",147static_cast<void *>(cursor), regNum,148static_cast<void *>(value));149AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;150if (co->validFloatReg(regNum)) {151*value = co->getFloatReg(regNum);152return UNW_ESUCCESS;153}154return UNW_EBADREG;155}156_LIBUNWIND_WEAK_ALIAS(__unw_get_fpreg, unw_get_fpreg)157158/// Set value of specified float register at cursor position in stack frame.159_LIBUNWIND_HIDDEN int __unw_set_fpreg(unw_cursor_t *cursor, unw_regnum_t regNum,160unw_fpreg_t value) {161#if defined(_LIBUNWIND_ARM_EHABI)162_LIBUNWIND_TRACE_API("__unw_set_fpreg(cursor=%p, regNum=%d, value=%llX)",163static_cast<void *>(cursor), regNum, value);164#else165_LIBUNWIND_TRACE_API("__unw_set_fpreg(cursor=%p, regNum=%d, value=%g)",166static_cast<void *>(cursor), regNum, value);167#endif168AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;169if (co->validFloatReg(regNum)) {170co->setFloatReg(regNum, value);171return UNW_ESUCCESS;172}173return UNW_EBADREG;174}175_LIBUNWIND_WEAK_ALIAS(__unw_set_fpreg, unw_set_fpreg)176177/// Move cursor to next frame.178_LIBUNWIND_HIDDEN int __unw_step(unw_cursor_t *cursor) {179_LIBUNWIND_TRACE_API("__unw_step(cursor=%p)", static_cast<void *>(cursor));180AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;181return co->step();182}183_LIBUNWIND_WEAK_ALIAS(__unw_step, unw_step)184185// Move cursor to next frame and for stage2 of unwinding.186// This resets MTE tags of tagged frames to zero.187extern "C" _LIBUNWIND_HIDDEN int __unw_step_stage2(unw_cursor_t *cursor) {188_LIBUNWIND_TRACE_API("__unw_step_stage2(cursor=%p)",189static_cast<void *>(cursor));190AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;191return co->step(true);192}193194/// Get unwind info at cursor position in stack frame.195_LIBUNWIND_HIDDEN int __unw_get_proc_info(unw_cursor_t *cursor,196unw_proc_info_t *info) {197_LIBUNWIND_TRACE_API("__unw_get_proc_info(cursor=%p, &info=%p)",198static_cast<void *>(cursor), static_cast<void *>(info));199AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;200co->getInfo(info);201if (info->end_ip == 0)202return UNW_ENOINFO;203return UNW_ESUCCESS;204}205_LIBUNWIND_WEAK_ALIAS(__unw_get_proc_info, unw_get_proc_info)206207/// Resume execution at cursor position (aka longjump).208_LIBUNWIND_HIDDEN int __unw_resume(unw_cursor_t *cursor) {209_LIBUNWIND_TRACE_API("__unw_resume(cursor=%p)", static_cast<void *>(cursor));210#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)211// Inform the ASan runtime that now might be a good time to clean stuff up.212__asan_handle_no_return();213#endif214AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;215co->jumpto();216return UNW_EUNSPEC;217}218_LIBUNWIND_WEAK_ALIAS(__unw_resume, unw_resume)219220/// Get name of function at cursor position in stack frame.221_LIBUNWIND_HIDDEN int __unw_get_proc_name(unw_cursor_t *cursor, char *buf,222size_t bufLen, unw_word_t *offset) {223_LIBUNWIND_TRACE_API("__unw_get_proc_name(cursor=%p, &buf=%p, bufLen=%lu)",224static_cast<void *>(cursor), static_cast<void *>(buf),225static_cast<unsigned long>(bufLen));226AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;227if (co->getFunctionName(buf, bufLen, offset))228return UNW_ESUCCESS;229return UNW_EUNSPEC;230}231_LIBUNWIND_WEAK_ALIAS(__unw_get_proc_name, unw_get_proc_name)232233/// Checks if a register is a floating-point register.234_LIBUNWIND_HIDDEN int __unw_is_fpreg(unw_cursor_t *cursor,235unw_regnum_t regNum) {236_LIBUNWIND_TRACE_API("__unw_is_fpreg(cursor=%p, regNum=%d)",237static_cast<void *>(cursor), regNum);238AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;239return co->validFloatReg(regNum);240}241_LIBUNWIND_WEAK_ALIAS(__unw_is_fpreg, unw_is_fpreg)242243/// Checks if a register is a floating-point register.244_LIBUNWIND_HIDDEN const char *__unw_regname(unw_cursor_t *cursor,245unw_regnum_t regNum) {246_LIBUNWIND_TRACE_API("__unw_regname(cursor=%p, regNum=%d)",247static_cast<void *>(cursor), regNum);248AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;249return co->getRegisterName(regNum);250}251_LIBUNWIND_WEAK_ALIAS(__unw_regname, unw_regname)252253/// Checks if current frame is signal trampoline.254_LIBUNWIND_HIDDEN int __unw_is_signal_frame(unw_cursor_t *cursor) {255_LIBUNWIND_TRACE_API("__unw_is_signal_frame(cursor=%p)",256static_cast<void *>(cursor));257AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;258return co->isSignalFrame();259}260_LIBUNWIND_WEAK_ALIAS(__unw_is_signal_frame, unw_is_signal_frame)261262#ifdef _AIX263_LIBUNWIND_EXPORT uintptr_t __unw_get_data_rel_base(unw_cursor_t *cursor) {264_LIBUNWIND_TRACE_API("unw_get_data_rel_base(cursor=%p)",265static_cast<void *>(cursor));266AbstractUnwindCursor *co = reinterpret_cast<AbstractUnwindCursor *>(cursor);267return co->getDataRelBase();268}269_LIBUNWIND_WEAK_ALIAS(__unw_get_data_rel_base, unw_get_data_rel_base)270#endif271272#ifdef __arm__273// Save VFP registers d0-d15 using FSTMIADX instead of FSTMIADD274_LIBUNWIND_HIDDEN void __unw_save_vfp_as_X(unw_cursor_t *cursor) {275_LIBUNWIND_TRACE_API("__unw_get_fpreg_save_vfp_as_X(cursor=%p)",276static_cast<void *>(cursor));277AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;278return co->saveVFPAsX();279}280_LIBUNWIND_WEAK_ALIAS(__unw_save_vfp_as_X, unw_save_vfp_as_X)281#endif282283284#if defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)285/// SPI: walks cached DWARF entries286_LIBUNWIND_HIDDEN void __unw_iterate_dwarf_unwind_cache(void (*func)(287unw_word_t ip_start, unw_word_t ip_end, unw_word_t fde, unw_word_t mh)) {288_LIBUNWIND_TRACE_API("__unw_iterate_dwarf_unwind_cache(func=%p)",289reinterpret_cast<void *>(func));290DwarfFDECache<LocalAddressSpace>::iterateCacheEntries(func);291}292_LIBUNWIND_WEAK_ALIAS(__unw_iterate_dwarf_unwind_cache,293unw_iterate_dwarf_unwind_cache)294295/// IPI: for __register_frame()296void __unw_add_dynamic_fde(unw_word_t fde) {297CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;298CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;299const char *message = CFI_Parser<LocalAddressSpace>::decodeFDE(300LocalAddressSpace::sThisAddressSpace,301(LocalAddressSpace::pint_t) fde, &fdeInfo, &cieInfo);302if (message == NULL) {303// dynamically registered FDEs don't have a mach_header group they are in.304// Use fde as mh_group305unw_word_t mh_group = fdeInfo.fdeStart;306DwarfFDECache<LocalAddressSpace>::add((LocalAddressSpace::pint_t)mh_group,307fdeInfo.pcStart, fdeInfo.pcEnd,308fdeInfo.fdeStart);309} else {310_LIBUNWIND_DEBUG_LOG("__unw_add_dynamic_fde: bad fde: %s", message);311}312}313314/// IPI: for __deregister_frame()315void __unw_remove_dynamic_fde(unw_word_t fde) {316// fde is own mh_group317DwarfFDECache<LocalAddressSpace>::removeAllIn((LocalAddressSpace::pint_t)fde);318}319320void __unw_add_dynamic_eh_frame_section(unw_word_t eh_frame_start) {321// The eh_frame section start serves as the mh_group322unw_word_t mh_group = eh_frame_start;323CFI_Parser<LocalAddressSpace>::CIE_Info cieInfo;324CFI_Parser<LocalAddressSpace>::FDE_Info fdeInfo;325auto p = (LocalAddressSpace::pint_t)eh_frame_start;326while (LocalAddressSpace::sThisAddressSpace.get32(p)) {327if (CFI_Parser<LocalAddressSpace>::decodeFDE(328LocalAddressSpace::sThisAddressSpace, p, &fdeInfo, &cieInfo,329true) == NULL) {330DwarfFDECache<LocalAddressSpace>::add((LocalAddressSpace::pint_t)mh_group,331fdeInfo.pcStart, fdeInfo.pcEnd,332fdeInfo.fdeStart);333p += fdeInfo.fdeLength;334} else if (CFI_Parser<LocalAddressSpace>::parseCIE(335LocalAddressSpace::sThisAddressSpace, p, &cieInfo) == NULL) {336p += cieInfo.cieLength;337} else338return;339}340}341342void __unw_remove_dynamic_eh_frame_section(unw_word_t eh_frame_start) {343// The eh_frame section start serves as the mh_group344DwarfFDECache<LocalAddressSpace>::removeAllIn(345(LocalAddressSpace::pint_t)eh_frame_start);346}347348#endif // defined(_LIBUNWIND_SUPPORT_DWARF_UNWIND)349#endif // !defined(__USING_SJLJ_EXCEPTIONS__) && !defined(__wasm__)350351#ifdef __APPLE__352353namespace libunwind {354355static constexpr size_t MAX_DYNAMIC_UNWIND_SECTIONS_FINDERS = 8;356357static RWMutex findDynamicUnwindSectionsLock;358static size_t numDynamicUnwindSectionsFinders = 0;359static unw_find_dynamic_unwind_sections360dynamicUnwindSectionsFinders[MAX_DYNAMIC_UNWIND_SECTIONS_FINDERS] = {0};361362bool findDynamicUnwindSections(void *addr, unw_dynamic_unwind_sections *info) {363bool found = false;364findDynamicUnwindSectionsLock.lock_shared();365for (size_t i = 0; i != numDynamicUnwindSectionsFinders; ++i) {366if (dynamicUnwindSectionsFinders[i]((unw_word_t)addr, info)) {367found = true;368break;369}370}371findDynamicUnwindSectionsLock.unlock_shared();372return found;373}374375} // namespace libunwind376377int __unw_add_find_dynamic_unwind_sections(378unw_find_dynamic_unwind_sections find_dynamic_unwind_sections) {379findDynamicUnwindSectionsLock.lock();380381// Check that we have enough space...382if (numDynamicUnwindSectionsFinders == MAX_DYNAMIC_UNWIND_SECTIONS_FINDERS) {383findDynamicUnwindSectionsLock.unlock();384return UNW_ENOMEM;385}386387// Check for value already present...388for (size_t i = 0; i != numDynamicUnwindSectionsFinders; ++i) {389if (dynamicUnwindSectionsFinders[i] == find_dynamic_unwind_sections) {390findDynamicUnwindSectionsLock.unlock();391return UNW_EINVAL;392}393}394395// Success -- add callback entry.396dynamicUnwindSectionsFinders[numDynamicUnwindSectionsFinders++] =397find_dynamic_unwind_sections;398findDynamicUnwindSectionsLock.unlock();399400return UNW_ESUCCESS;401}402403int __unw_remove_find_dynamic_unwind_sections(404unw_find_dynamic_unwind_sections find_dynamic_unwind_sections) {405findDynamicUnwindSectionsLock.lock();406407// Find index to remove.408size_t finderIdx = numDynamicUnwindSectionsFinders;409for (size_t i = 0; i != numDynamicUnwindSectionsFinders; ++i) {410if (dynamicUnwindSectionsFinders[i] == find_dynamic_unwind_sections) {411finderIdx = i;412break;413}414}415416// If no such registration is present then error out.417if (finderIdx == numDynamicUnwindSectionsFinders) {418findDynamicUnwindSectionsLock.unlock();419return UNW_EINVAL;420}421422// Remove entry.423for (size_t i = finderIdx; i != numDynamicUnwindSectionsFinders - 1; ++i)424dynamicUnwindSectionsFinders[i] = dynamicUnwindSectionsFinders[i + 1];425dynamicUnwindSectionsFinders[--numDynamicUnwindSectionsFinders] = nullptr;426427findDynamicUnwindSectionsLock.unlock();428return UNW_ESUCCESS;429}430431#endif // __APPLE__432433// Add logging hooks in Debug builds only434#ifndef NDEBUG435#include <stdlib.h>436437_LIBUNWIND_HIDDEN438bool logAPIs() {439// do manual lock to avoid use of _cxa_guard_acquire or initializers440static bool checked = false;441static bool log = false;442if (!checked) {443log = (getenv("LIBUNWIND_PRINT_APIS") != NULL);444checked = true;445}446return log;447}448449_LIBUNWIND_HIDDEN450bool logUnwinding() {451// do manual lock to avoid use of _cxa_guard_acquire or initializers452static bool checked = false;453static bool log = false;454if (!checked) {455log = (getenv("LIBUNWIND_PRINT_UNWINDING") != NULL);456checked = true;457}458return log;459}460461_LIBUNWIND_HIDDEN462bool logDWARF() {463// do manual lock to avoid use of _cxa_guard_acquire or initializers464static bool checked = false;465static bool log = false;466if (!checked) {467log = (getenv("LIBUNWIND_PRINT_DWARF") != NULL);468checked = true;469}470return log;471}472473#endif // NDEBUG474475476477