blob: 079fd905037d4598e1514360ed61451e62717ac6 [file] [log] [blame]
//===-- ObjectFileMachO.cpp -----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringRef.h"
#include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
#include "Plugins/Process/Utility/RegisterContextDarwin_arm64.h"
#include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
#include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Progress.h"
#include "lldb/Core/Section.h"
#include "lldb/Host/Host.h"
#include "lldb/Symbol/DWARFCallFrameInfo.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/DynamicLoader.h"
#include "lldb/Target/MemoryRegionInfo.h"
#include "lldb/Target/Platform.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/SectionLoadList.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/ThreadList.h"
#include "lldb/Utility/ArchSpec.h"
#include "lldb/Utility/DataBuffer.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/FileSpecList.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/RangeMap.h"
#include "lldb/Utility/RegisterValue.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/Timer.h"
#include "lldb/Utility/UUID.h"
#include "lldb/Host/SafeMachO.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "ObjectFileMachO.h"
#if defined(__APPLE__)
#include <TargetConditionals.h>
// GetLLDBSharedCacheUUID() needs to call dlsym()
#include <dlfcn.h>
#include <mach/mach_init.h>
#include <mach/vm_map.h>
#include <lldb/Host/SafeMachO.h>
#endif
#ifndef __APPLE__
#include "lldb/Utility/AppleUuidCompatibility.h"
#else
#include <uuid/uuid.h>
#endif
#include <bitset>
#include <memory>
#include <optional>
// Unfortunately the signpost header pulls in the system MachO header, too.
#ifdef CPU_TYPE_ARM
#undef CPU_TYPE_ARM
#endif
#ifdef CPU_TYPE_ARM64
#undef CPU_TYPE_ARM64
#endif
#ifdef CPU_TYPE_ARM64_32
#undef CPU_TYPE_ARM64_32
#endif
#ifdef CPU_TYPE_I386
#undef CPU_TYPE_I386
#endif
#ifdef CPU_TYPE_X86_64
#undef CPU_TYPE_X86_64
#endif
#ifdef MH_DYLINKER
#undef MH_DYLINKER
#endif
#ifdef MH_OBJECT
#undef MH_OBJECT
#endif
#ifdef LC_VERSION_MIN_MACOSX
#undef LC_VERSION_MIN_MACOSX
#endif
#ifdef LC_VERSION_MIN_IPHONEOS
#undef LC_VERSION_MIN_IPHONEOS
#endif
#ifdef LC_VERSION_MIN_TVOS
#undef LC_VERSION_MIN_TVOS
#endif
#ifdef LC_VERSION_MIN_WATCHOS
#undef LC_VERSION_MIN_WATCHOS
#endif
#ifdef LC_BUILD_VERSION
#undef LC_BUILD_VERSION
#endif
#ifdef PLATFORM_MACOS
#undef PLATFORM_MACOS
#endif
#ifdef PLATFORM_MACCATALYST
#undef PLATFORM_MACCATALYST
#endif
#ifdef PLATFORM_IOS
#undef PLATFORM_IOS
#endif
#ifdef PLATFORM_IOSSIMULATOR
#undef PLATFORM_IOSSIMULATOR
#endif
#ifdef PLATFORM_TVOS
#undef PLATFORM_TVOS
#endif
#ifdef PLATFORM_TVOSSIMULATOR
#undef PLATFORM_TVOSSIMULATOR
#endif
#ifdef PLATFORM_WATCHOS
#undef PLATFORM_WATCHOS
#endif
#ifdef PLATFORM_WATCHOSSIMULATOR
#undef PLATFORM_WATCHOSSIMULATOR
#endif
#define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
using namespace lldb;
using namespace lldb_private;
using namespace llvm::MachO;
static constexpr llvm::StringLiteral g_loader_path = "@loader_path";
static constexpr llvm::StringLiteral g_executable_path = "@executable_path";
LLDB_PLUGIN_DEFINE(ObjectFileMachO)
static void PrintRegisterValue(RegisterContext *reg_ctx, const char *name,
const char *alt_name, size_t reg_byte_size,
Stream &data) {
const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
if (reg_info == nullptr)
reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
if (reg_info) {
lldb_private::RegisterValue reg_value;
if (reg_ctx->ReadRegister(reg_info, reg_value)) {
if (reg_info->byte_size >= reg_byte_size)
data.Write(reg_value.GetBytes(), reg_byte_size);
else {
data.Write(reg_value.GetBytes(), reg_info->byte_size);
for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n; ++i)
data.PutChar(0);
}
return;
}
}
// Just write zeros if all else fails
for (size_t i = 0; i < reg_byte_size; ++i)
data.PutChar(0);
}
class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 {
public:
RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread,
const DataExtractor &data)
: RegisterContextDarwin_x86_64(thread, 0) {
SetRegisterDataFrom_LC_THREAD(data);
}
void InvalidateAllRegisters() override {
// Do nothing... registers are always valid...
}
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
lldb::offset_t offset = 0;
SetError(GPRRegSet, Read, -1);
SetError(FPURegSet, Read, -1);
SetError(EXCRegSet, Read, -1);
bool done = false;
while (!done) {
int flavor = data.GetU32(&offset);
if (flavor == 0)
done = true;
else {
uint32_t i;
uint32_t count = data.GetU32(&offset);
switch (flavor) {
case GPRRegSet:
for (i = 0; i < count; ++i)
(&gpr.rax)[i] = data.GetU64(&offset);
SetError(GPRRegSet, Read, 0);
done = true;
break;
case FPURegSet:
// TODO: fill in FPU regs....
// SetError (FPURegSet, Read, -1);
done = true;
break;
case EXCRegSet:
exc.trapno = data.GetU32(&offset);
exc.err = data.GetU32(&offset);
exc.faultvaddr = data.GetU64(&offset);
SetError(EXCRegSet, Read, 0);
done = true;
break;
case 7:
case 8:
case 9:
// fancy flavors that encapsulate of the above flavors...
break;
default:
done = true;
break;
}
}
}
}
static bool Create_LC_THREAD(Thread *thread, Stream &data) {
RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
if (reg_ctx_sp) {
RegisterContext *reg_ctx = reg_ctx_sp.get();
data.PutHex32(GPRRegSet); // Flavor
data.PutHex32(GPRWordCount);
PrintRegisterValue(reg_ctx, "rax", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rbx", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rcx", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rdx", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rdi", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rsi", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rbp", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rsp", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r8", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r9", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r10", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r11", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r12", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r13", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r14", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "r15", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rip", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "rflags", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "cs", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "fs", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "gs", nullptr, 8, data);
// // Write out the FPU registers
// const size_t fpu_byte_size = sizeof(FPU);
// size_t bytes_written = 0;
// data.PutHex32 (FPURegSet);
// data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
// bytes_written += data.PutHex32(0); // uint32_t pad[0]
// bytes_written += data.PutHex32(0); // uint32_t pad[1]
// bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
// data); // uint16_t fcw; // "fctrl"
// bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
// data); // uint16_t fsw; // "fstat"
// bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
// data); // uint8_t ftw; // "ftag"
// bytes_written += data.PutHex8 (0); // uint8_t pad1;
// bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
// data); // uint16_t fop; // "fop"
// bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
// data); // uint32_t ip; // "fioff"
// bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
// data); // uint16_t cs; // "fiseg"
// bytes_written += data.PutHex16 (0); // uint16_t pad2;
// bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
// data); // uint32_t dp; // "fooff"
// bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
// data); // uint16_t ds; // "foseg"
// bytes_written += data.PutHex16 (0); // uint16_t pad3;
// bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
// data); // uint32_t mxcsr;
// bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
// 4, data);// uint32_t mxcsrmask;
// bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
// sizeof(MMSReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
// sizeof(XMMReg), data);
// bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
// sizeof(XMMReg), data);
//
// // Fill rest with zeros
// for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
// i)
// data.PutChar(0);
// Write out the EXC registers
data.PutHex32(EXCRegSet);
data.PutHex32(EXCWordCount);
PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 8, data);
return true;
}
return false;
}
protected:
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
return 0;
}
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
return 0;
}
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
return 0;
}
};
class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 {
public:
RegisterContextDarwin_i386_Mach(lldb_private::Thread &thread,
const DataExtractor &data)
: RegisterContextDarwin_i386(thread, 0) {
SetRegisterDataFrom_LC_THREAD(data);
}
void InvalidateAllRegisters() override {
// Do nothing... registers are always valid...
}
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
lldb::offset_t offset = 0;
SetError(GPRRegSet, Read, -1);
SetError(FPURegSet, Read, -1);
SetError(EXCRegSet, Read, -1);
bool done = false;
while (!done) {
int flavor = data.GetU32(&offset);
if (flavor == 0)
done = true;
else {
uint32_t i;
uint32_t count = data.GetU32(&offset);
switch (flavor) {
case GPRRegSet:
for (i = 0; i < count; ++i)
(&gpr.eax)[i] = data.GetU32(&offset);
SetError(GPRRegSet, Read, 0);
done = true;
break;
case FPURegSet:
// TODO: fill in FPU regs....
// SetError (FPURegSet, Read, -1);
done = true;
break;
case EXCRegSet:
exc.trapno = data.GetU32(&offset);
exc.err = data.GetU32(&offset);
exc.faultvaddr = data.GetU32(&offset);
SetError(EXCRegSet, Read, 0);
done = true;
break;
case 7:
case 8:
case 9:
// fancy flavors that encapsulate of the above flavors...
break;
default:
done = true;
break;
}
}
}
}
static bool Create_LC_THREAD(Thread *thread, Stream &data) {
RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
if (reg_ctx_sp) {
RegisterContext *reg_ctx = reg_ctx_sp.get();
data.PutHex32(GPRRegSet); // Flavor
data.PutHex32(GPRWordCount);
PrintRegisterValue(reg_ctx, "eax", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ebx", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ecx", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "edx", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "edi", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "esi", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ebp", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "esp", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ss", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "eflags", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "eip", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "cs", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "ds", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "es", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "fs", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "gs", nullptr, 4, data);
// Write out the EXC registers
data.PutHex32(EXCRegSet);
data.PutHex32(EXCWordCount);
PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 4, data);
return true;
}
return false;
}
protected:
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
return 0;
}
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
return 0;
}
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
return 0;
}
};
class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm {
public:
RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread,
const DataExtractor &data)
: RegisterContextDarwin_arm(thread, 0) {
SetRegisterDataFrom_LC_THREAD(data);
}
void InvalidateAllRegisters() override {
// Do nothing... registers are always valid...
}
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
lldb::offset_t offset = 0;
SetError(GPRRegSet, Read, -1);
SetError(FPURegSet, Read, -1);
SetError(EXCRegSet, Read, -1);
bool done = false;
while (!done) {
int flavor = data.GetU32(&offset);
uint32_t count = data.GetU32(&offset);
lldb::offset_t next_thread_state = offset + (count * 4);
switch (flavor) {
case GPRAltRegSet:
case GPRRegSet: {
// r0-r15, plus CPSR
uint32_t gpr_buf_count = (sizeof(gpr.r) / sizeof(gpr.r[0])) + 1;
if (count == gpr_buf_count) {
for (uint32_t i = 0; i < (count - 1); ++i) {
gpr.r[i] = data.GetU32(&offset);
}
gpr.cpsr = data.GetU32(&offset);
SetError(GPRRegSet, Read, 0);
}
}
offset = next_thread_state;
break;
case FPURegSet: {
uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats;
const int fpu_reg_buf_size = sizeof(fpu.floats);
if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
fpu_reg_buf) == fpu_reg_buf_size) {
offset += fpu_reg_buf_size;
fpu.fpscr = data.GetU32(&offset);
SetError(FPURegSet, Read, 0);
} else {
done = true;
}
}
offset = next_thread_state;
break;
case EXCRegSet:
if (count == 3) {
exc.exception = data.GetU32(&offset);
exc.fsr = data.GetU32(&offset);
exc.far = data.GetU32(&offset);
SetError(EXCRegSet, Read, 0);
}
done = true;
offset = next_thread_state;
break;
// Unknown register set flavor, stop trying to parse.
default:
done = true;
}
}
}
static bool Create_LC_THREAD(Thread *thread, Stream &data) {
RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
if (reg_ctx_sp) {
RegisterContext *reg_ctx = reg_ctx_sp.get();
data.PutHex32(GPRRegSet); // Flavor
data.PutHex32(GPRWordCount);
PrintRegisterValue(reg_ctx, "r0", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r1", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r2", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r3", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r4", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r5", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r6", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r7", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r8", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r9", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r10", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r11", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "r12", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "sp", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "lr", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "pc", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
// Write out the EXC registers
// data.PutHex32 (EXCRegSet);
// data.PutHex32 (EXCWordCount);
// WriteRegister (reg_ctx, "exception", NULL, 4, data);
// WriteRegister (reg_ctx, "fsr", NULL, 4, data);
// WriteRegister (reg_ctx, "far", NULL, 4, data);
return true;
}
return false;
}
protected:
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
return 0;
}
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
return 0;
}
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
return 0;
}
int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
return -1;
}
};
class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 {
public:
RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread,
const DataExtractor &data)
: RegisterContextDarwin_arm64(thread, 0) {
SetRegisterDataFrom_LC_THREAD(data);
}
void InvalidateAllRegisters() override {
// Do nothing... registers are always valid...
}
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
lldb::offset_t offset = 0;
SetError(GPRRegSet, Read, -1);
SetError(FPURegSet, Read, -1);
SetError(EXCRegSet, Read, -1);
bool done = false;
while (!done) {
int flavor = data.GetU32(&offset);
uint32_t count = data.GetU32(&offset);
lldb::offset_t next_thread_state = offset + (count * 4);
switch (flavor) {
case GPRRegSet:
// x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
// 32-bit register)
if (count >= (33 * 2) + 1) {
for (uint32_t i = 0; i < 29; ++i)
gpr.x[i] = data.GetU64(&offset);
gpr.fp = data.GetU64(&offset);
gpr.lr = data.GetU64(&offset);
gpr.sp = data.GetU64(&offset);
gpr.pc = data.GetU64(&offset);
gpr.cpsr = data.GetU32(&offset);
SetError(GPRRegSet, Read, 0);
}
offset = next_thread_state;
break;
case FPURegSet: {
uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
const int fpu_reg_buf_size = sizeof(fpu);
if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
fpu_reg_buf) == fpu_reg_buf_size) {
SetError(FPURegSet, Read, 0);
} else {
done = true;
}
}
offset = next_thread_state;
break;
case EXCRegSet:
if (count == 4) {
exc.far = data.GetU64(&offset);
exc.esr = data.GetU32(&offset);
exc.exception = data.GetU32(&offset);
SetError(EXCRegSet, Read, 0);
}
offset = next_thread_state;
break;
default:
done = true;
break;
}
}
}
static bool Create_LC_THREAD(Thread *thread, Stream &data) {
RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
if (reg_ctx_sp) {
RegisterContext *reg_ctx = reg_ctx_sp.get();
data.PutHex32(GPRRegSet); // Flavor
data.PutHex32(GPRWordCount);
PrintRegisterValue(reg_ctx, "x0", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x1", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x2", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x3", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x4", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x5", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x6", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x7", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x8", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x9", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x10", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x11", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x12", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x13", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x14", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x15", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x16", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x17", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x18", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x19", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x20", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x21", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x22", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x23", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x24", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x25", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x26", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x27", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "x28", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "fp", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "lr", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "sp", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "pc", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
data.PutHex32(0); // uint32_t pad at the end
// Write out the EXC registers
data.PutHex32(EXCRegSet);
data.PutHex32(EXCWordCount);
PrintRegisterValue(reg_ctx, "far", nullptr, 8, data);
PrintRegisterValue(reg_ctx, "esr", nullptr, 4, data);
PrintRegisterValue(reg_ctx, "exception", nullptr, 4, data);
return true;
}
return false;
}
protected:
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
return 0;
}
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
return 0;
}
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
return 0;
}
int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
return -1;
}
};
static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
switch (magic) {
case MH_MAGIC:
case MH_CIGAM:
return sizeof(struct llvm::MachO::mach_header);
case MH_MAGIC_64:
case MH_CIGAM_64:
return sizeof(struct llvm::MachO::mach_header_64);
break;
default:
break;
}
return 0;
}
#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
char ObjectFileMachO::ID;
void ObjectFileMachO::Initialize() {
PluginManager::RegisterPlugin(
GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
CreateMemoryInstance, GetModuleSpecifications, SaveCore);
}
void ObjectFileMachO::Terminate() {
PluginManager::UnregisterPlugin(CreateInstance);
}
ObjectFile *ObjectFileMachO::CreateInstance(const lldb::ModuleSP &module_sp,
DataBufferSP data_sp,
lldb::offset_t data_offset,
const FileSpec *file,
lldb::offset_t file_offset,
lldb::offset_t length) {
if (!data_sp) {
data_sp = MapFileData(*file, length, file_offset);
if (!data_sp)
return nullptr;
data_offset = 0;
}
if (!ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
return nullptr;
// Update the data to contain the entire file if it doesn't already
if (data_sp->GetByteSize() < length) {
data_sp = MapFileData(*file, length, file_offset);
if (!data_sp)
return nullptr;
data_offset = 0;
}
auto objfile_up = std::make_unique<ObjectFileMachO>(
module_sp, data_sp, data_offset, file, file_offset, length);
if (!objfile_up || !objfile_up->ParseHeader())
return nullptr;
return objfile_up.release();
}
ObjectFile *ObjectFileMachO::CreateMemoryInstance(
const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp,
const ProcessSP &process_sp, lldb::addr_t header_addr) {
if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
std::unique_ptr<ObjectFile> objfile_up(
new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
if (objfile_up.get() && objfile_up->ParseHeader())
return objfile_up.release();
}
return nullptr;
}
size_t ObjectFileMachO::GetModuleSpecifications(
const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
lldb::offset_t data_offset, lldb::offset_t file_offset,
lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
const size_t initial_count = specs.GetSize();
if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
DataExtractor data;
data.SetData(data_sp);
llvm::MachO::mach_header header;
if (ParseHeader(data, &data_offset, header)) {
size_t header_and_load_cmds =
header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
if (header_and_load_cmds >= data_sp->GetByteSize()) {
data_sp = MapFileData(file, header_and_load_cmds, file_offset);
data.SetData(data_sp);
data_offset = MachHeaderSizeFromMagic(header.magic);
}
if (data_sp) {
ModuleSpec base_spec;
base_spec.GetFileSpec() = file;
base_spec.SetObjectOffset(file_offset);
base_spec.SetObjectSize(length);
GetAllArchSpecs(header, data, data_offset, base_spec, specs);
}
}
}
return specs.GetSize() - initial_count;
}
ConstString ObjectFileMachO::GetSegmentNameTEXT() {
static ConstString g_segment_name_TEXT("__TEXT");
return g_segment_name_TEXT;
}
ConstString ObjectFileMachO::GetSegmentNameDATA() {
static ConstString g_segment_name_DATA("__DATA");
return g_segment_name_DATA;
}
ConstString ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
static ConstString g_segment_name("__DATA_DIRTY");
return g_segment_name;
}
ConstString ObjectFileMachO::GetSegmentNameDATA_CONST() {
static ConstString g_segment_name("__DATA_CONST");
return g_segment_name;
}
ConstString ObjectFileMachO::GetSegmentNameOBJC() {
static ConstString g_segment_name_OBJC("__OBJC");
return g_segment_name_OBJC;
}
ConstString ObjectFileMachO::GetSegmentNameLINKEDIT() {
static ConstString g_section_name_LINKEDIT("__LINKEDIT");
return g_section_name_LINKEDIT;
}
ConstString ObjectFileMachO::GetSegmentNameDWARF() {
static ConstString g_section_name("__DWARF");
return g_section_name;
}
ConstString ObjectFileMachO::GetSegmentNameLLVM_COV() {
static ConstString g_section_name("__LLVM_COV");
return g_section_name;
}
ConstString ObjectFileMachO::GetSectionNameEHFrame() {
static ConstString g_section_name_eh_frame("__eh_frame");
return g_section_name_eh_frame;
}
bool ObjectFileMachO::MagicBytesMatch(DataBufferSP data_sp,
lldb::addr_t data_offset,
lldb::addr_t data_length) {
DataExtractor data;
data.SetData(data_sp, data_offset, data_length);
lldb::offset_t offset = 0;
uint32_t magic = data.GetU32(&offset);
offset += 4; // cputype
offset += 4; // cpusubtype
uint32_t filetype = data.GetU32(&offset);
// A fileset has a Mach-O header but is not an
// individual file and must be handled via an
// ObjectContainer plugin.
if (filetype == llvm::MachO::MH_FILESET)
return false;
return MachHeaderSizeFromMagic(magic) != 0;
}
ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
DataBufferSP data_sp,
lldb::offset_t data_offset,
const FileSpec *file,
lldb::offset_t file_offset,
lldb::offset_t length)
: ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
m_mach_sections(), m_entry_point_address(), m_thread_context_offsets(),
m_thread_context_offsets_valid(false), m_reexported_dylibs(),
m_allow_assembly_emulation_unwind_plans(true) {
::memset(&m_header, 0, sizeof(m_header));
::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
}
ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
lldb::WritableDataBufferSP header_data_sp,
const lldb::ProcessSP &process_sp,
lldb::addr_t header_addr)
: ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
m_mach_sections(), m_entry_point_address(), m_thread_context_offsets(),
m_thread_context_offsets_valid(false), m_reexported_dylibs(),
m_allow_assembly_emulation_unwind_plans(true) {
::memset(&m_header, 0, sizeof(m_header));
::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
}
bool ObjectFileMachO::ParseHeader(DataExtractor &data,
lldb::offset_t *data_offset_ptr,
llvm::MachO::mach_header &header) {
data.SetByteOrder(endian::InlHostByteOrder());
// Leave magic in the original byte order
header.magic = data.GetU32(data_offset_ptr);
bool can_parse = false;
bool is_64_bit = false;
switch (header.magic) {
case MH_MAGIC:
data.SetByteOrder(endian::InlHostByteOrder());
data.SetAddressByteSize(4);
can_parse = true;
break;
case MH_MAGIC_64:
data.SetByteOrder(endian::InlHostByteOrder());
data.SetAddressByteSize(8);
can_parse = true;
is_64_bit = true;
break;
case MH_CIGAM:
data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
? eByteOrderLittle
: eByteOrderBig);
data.SetAddressByteSize(4);
can_parse = true;
break;
case MH_CIGAM_64:
data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
? eByteOrderLittle
: eByteOrderBig);
data.SetAddressByteSize(8);
is_64_bit = true;
can_parse = true;
break;
default:
break;
}
if (can_parse) {
data.GetU32(data_offset_ptr, &header.cputype, 6);
if (is_64_bit)
*data_offset_ptr += 4;
return true;
} else {
memset(&header, 0, sizeof(header));
}
return false;
}
bool ObjectFileMachO::ParseHeader() {
ModuleSP module_sp(GetModule());
if (!module_sp)
return false;
std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
bool can_parse = false;
lldb::offset_t offset = 0;
m_data.SetByteOrder(endian::InlHostByteOrder());
// Leave magic in the original byte order
m_header.magic = m_data.GetU32(&offset);
switch (m_header.magic) {
case MH_MAGIC:
m_data.SetByteOrder(endian::InlHostByteOrder());
m_data.SetAddressByteSize(4);
can_parse = true;
break;
case MH_MAGIC_64:
m_data.SetByteOrder(endian::InlHostByteOrder());
m_data.SetAddressByteSize(8);
can_parse = true;
break;
case MH_CIGAM:
m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
? eByteOrderLittle
: eByteOrderBig);
m_data.SetAddressByteSize(4);
can_parse = true;
break;
case MH_CIGAM_64:
m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
? eByteOrderLittle
: eByteOrderBig);
m_data.SetAddressByteSize(8);
can_parse = true;
break;
default:
break;
}
if (can_parse) {
m_data.GetU32(&offset, &m_header.cputype, 6);
ModuleSpecList all_specs;
ModuleSpec base_spec;
GetAllArchSpecs(m_header, m_data, MachHeaderSizeFromMagic(m_header.magic),
base_spec, all_specs);
for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
ArchSpec mach_arch =
all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
// Check if the module has a required architecture
const ArchSpec &module_arch = module_sp->GetArchitecture();
if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
continue;
if (SetModulesArchitecture(mach_arch)) {
const size_t header_and_lc_size =
m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
if (m_data.GetByteSize() < header_and_lc_size) {
DataBufferSP data_sp;
ProcessSP process_sp(m_process_wp.lock());
if (process_sp) {
data_sp = ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
} else {
// Read in all only the load command data from the file on disk
data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
if (data_sp->GetByteSize() != header_and_lc_size)
continue;
}
if (data_sp)
m_data.SetData(data_sp);
}
}
return true;
}
// None found.
return false;
} else {
memset(&m_header, 0, sizeof(struct llvm::MachO::mach_header));
}
return false;
}
ByteOrder ObjectFileMachO::GetByteOrder() const {
return m_data.GetByteOrder();
}
bool ObjectFileMachO::IsExecutable() const {
return m_header.filetype == MH_EXECUTE;
}
bool ObjectFileMachO::IsDynamicLoader() const {
return m_header.filetype == MH_DYLINKER;
}
bool ObjectFileMachO::IsSharedCacheBinary() const {
return m_header.flags & MH_DYLIB_IN_CACHE;
}
bool ObjectFileMachO::IsKext() const {
return m_header.filetype == MH_KEXT_BUNDLE;
}
uint32_t ObjectFileMachO::GetAddressByteSize() const {
return m_data.GetAddressByteSize();
}
AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
Symtab *symtab = GetSymtab();
if (!symtab)
return AddressClass::eUnknown;
Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
if (symbol) {
if (symbol->ValueIsAddress()) {
SectionSP section_sp(symbol->GetAddressRef().GetSection());
if (section_sp) {
const lldb::SectionType section_type = section_sp->GetType();
switch (section_type) {
case eSectionTypeInvalid:
return AddressClass::eUnknown;
case eSectionTypeCode:
if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
// For ARM we have a bit in the n_desc field of the symbol that
// tells us ARM/Thumb which is bit 0x0008.
if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
return AddressClass::eCodeAlternateISA;
}
return AddressClass::eCode;
case eSectionTypeContainer:
return AddressClass::eUnknown;
case eSectionTypeData:
case eSectionTypeDataCString:
case eSectionTypeDataCStringPointers:
case eSectionTypeDataSymbolAddress:
case eSectionTypeData4:
case eSectionTypeData8:
case eSectionTypeData16:
case eSectionTypeDataPointers:
case eSectionTypeZeroFill:
case eSectionTypeDataObjCMessageRefs:
case eSectionTypeDataObjCCFStrings:
case eSectionTypeGoSymtab:
return AddressClass::eData;
case eSectionTypeDebug:
case eSectionTypeDWARFDebugAbbrev:
case eSectionTypeDWARFDebugAbbrevDwo:
case eSectionTypeDWARFDebugAddr:
case eSectionTypeDWARFDebugAranges:
case eSectionTypeDWARFDebugCuIndex:
case eSectionTypeDWARFDebugFrame:
case eSectionTypeDWARFDebugInfo:
case eSectionTypeDWARFDebugInfoDwo:
case eSectionTypeDWARFDebugLine:
case eSectionTypeDWARFDebugLineStr:
case eSectionTypeDWARFDebugLoc:
case eSectionTypeDWARFDebugLocDwo:
case eSectionTypeDWARFDebugLocLists:
case eSectionTypeDWARFDebugLocListsDwo:
case eSectionTypeDWARFDebugMacInfo:
case eSectionTypeDWARFDebugMacro:
case eSectionTypeDWARFDebugNames:
case eSectionTypeDWARFDebugPubNames:
case eSectionTypeDWARFDebugPubTypes:
case eSectionTypeDWARFDebugRanges:
case eSectionTypeDWARFDebugRngLists:
case eSectionTypeDWARFDebugRngListsDwo:
case eSectionTypeDWARFDebugStr:
case eSectionTypeDWARFDebugStrDwo:
case eSectionTypeDWARFDebugStrOffsets:
case eSectionTypeDWARFDebugStrOffsetsDwo:
case eSectionTypeDWARFDebugTuIndex:
case eSectionTypeDWARFDebugTypes:
case eSectionTypeDWARFDebugTypesDwo:
case eSectionTypeDWARFAppleNames:
case eSectionTypeDWARFAppleTypes:
case eSectionTypeDWARFAppleNamespaces:
case eSectionTypeDWARFAppleObjC:
case eSectionTypeDWARFGNUDebugAltLink:
case eSectionTypeCTF:
case eSectionTypeSwiftModules:
return AddressClass::eDebug;
case eSectionTypeEHFrame:
case eSectionTypeARMexidx:
case eSectionTypeARMextab:
case eSectionTypeCompactUnwind:
return AddressClass::eRuntime;
case eSectionTypeAbsoluteAddress:
case eSectionTypeELFSymbolTable:
case eSectionTypeELFDynamicSymbols:
case eSectionTypeELFRelocationEntries:
case eSectionTypeELFDynamicLinkInfo:
case eSectionTypeOther:
return AddressClass::eUnknown;
}
}
}
const SymbolType symbol_type = symbol->GetType();
switch (symbol_type) {
case eSymbolTypeAny:
return AddressClass::eUnknown;
case eSymbolTypeAbsolute:
return AddressClass::eUnknown;
case eSymbolTypeCode:
case eSymbolTypeTrampoline:
case eSymbolTypeResolver:
if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
// For ARM we have a bit in the n_desc field of the symbol that tells
// us ARM/Thumb which is bit 0x0008.
if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
return AddressClass::eCodeAlternateISA;
}
return AddressClass::eCode;
case eSymbolTypeData:
return AddressClass::eData;
case eSymbolTypeRuntime:
return AddressClass::eRuntime;
case eSymbolTypeException:
return AddressClass::eRuntime;
case eSymbolTypeSourceFile:
return AddressClass::eDebug;
case eSymbolTypeHeaderFile:
return AddressClass::eDebug;
case eSymbolTypeObjectFile:
return AddressClass::eDebug;
case eSymbolTypeCommonBlock:
return AddressClass::eDebug;
case eSymbolTypeBlock:
return AddressClass::eDebug;
case eSymbolTypeLocal:
return AddressClass::eData;
case eSymbolTypeParam:
return AddressClass::eData;
case eSymbolTypeVariable:
return AddressClass::eData;
case eSymbolTypeVariableType:
return AddressClass::eDebug;
case eSymbolTypeLineEntry:
return AddressClass::eDebug;
case eSymbolTypeLineHeader:
return AddressClass::eDebug;
case eSymbolTypeScopeBegin:
return AddressClass::eDebug;
case eSymbolTypeScopeEnd:
return AddressClass::eDebug;
case eSymbolTypeAdditional:
return AddressClass::eUnknown;
case eSymbolTypeCompiler:
return AddressClass::eDebug;
case eSymbolTypeInstrumentation:
return AddressClass::eDebug;
case eSymbolTypeUndefined:
return AddressClass::eUnknown;
case eSymbolTypeObjCClass:
return AddressClass::eRuntime;
case eSymbolTypeObjCMetaClass:
return AddressClass::eRuntime;
case eSymbolTypeObjCIVar:
return AddressClass::eRuntime;
case eSymbolTypeReExported:
return AddressClass::eRuntime;
}
}
return AddressClass::eUnknown;
}
bool ObjectFileMachO::IsStripped() {
if (m_dysymtab.cmd == 0) {
ModuleSP module_sp(GetModule());
if (module_sp) {
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
llvm::MachO::load_command lc = {};
if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
break;
if (lc.cmd == LC_DYSYMTAB) {
m_dysymtab.cmd = lc.cmd;
m_dysymtab.cmdsize = lc.cmdsize;
if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
(sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
nullptr) {
// Clear m_dysymtab if we were unable to read all items from the
// load command
::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
}
}
offset = load_cmd_offset + lc.cmdsize;
}
}
}
if (m_dysymtab.cmd)
return m_dysymtab.nlocalsym <= 1;
return false;
}
ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
EncryptedFileRanges result;
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
llvm::MachO::encryption_info_command encryption_cmd;
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
if (m_data.GetU32(&offset, &encryption_cmd, 2) == nullptr)
break;
// LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
// 3 fields we care about, so treat them the same.
if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
if (encryption_cmd.cryptid != 0) {
EncryptedFileRanges::Entry entry;
entry.SetRangeBase(encryption_cmd.cryptoff);
entry.SetByteSize(encryption_cmd.cryptsize);
result.Append(entry);
}
}
}
offset = load_cmd_offset + encryption_cmd.cmdsize;
}
return result;
}
void ObjectFileMachO::SanitizeSegmentCommand(
llvm::MachO::segment_command_64 &seg_cmd, uint32_t cmd_idx) {
if (m_length == 0 || seg_cmd.filesize == 0)
return;
if (IsSharedCacheBinary() && !IsInMemory()) {
// In shared cache images, the load commands are relative to the
// shared cache file, and not the specific image we are
// examining. Let's fix this up so that it looks like a normal
// image.
if (strncmp(seg_cmd.segname, GetSegmentNameTEXT().GetCString(),
sizeof(seg_cmd.segname)) == 0)
m_text_address = seg_cmd.vmaddr;
if (strncmp(seg_cmd.segname, GetSegmentNameLINKEDIT().GetCString(),
sizeof(seg_cmd.segname)) == 0)
m_linkedit_original_offset = seg_cmd.fileoff;
seg_cmd.fileoff = seg_cmd.vmaddr - m_text_address;
}
if (seg_cmd.fileoff > m_length) {
// We have a load command that says it extends past the end of the file.
// This is likely a corrupt file. We don't have any way to return an error
// condition here (this method was likely invoked from something like
// ObjectFile::GetSectionList()), so we just null out the section contents,
// and dump a message to stdout. The most common case here is core file
// debugging with a truncated file.
const char *lc_segment_name =
seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
GetModule()->ReportWarning(
"load command {0} {1} has a fileoff ({2:x16}) that extends beyond "
"the end of the file ({3:x16}), ignoring this section",
cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
seg_cmd.fileoff = 0;
seg_cmd.filesize = 0;
}
if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
// We have a load command that says it extends past the end of the file.
// This is likely a corrupt file. We don't have any way to return an error
// condition here (this method was likely invoked from something like
// ObjectFile::GetSectionList()), so we just null out the section contents,
// and dump a message to stdout. The most common case here is core file
// debugging with a truncated file.
const char *lc_segment_name =
seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
GetModule()->ReportWarning(
"load command {0} {1} has a fileoff + filesize ({2:x16}) that "
"extends beyond the end of the file ({3:x16}), the segment will be "
"truncated to match",
cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
// Truncate the length
seg_cmd.filesize = m_length - seg_cmd.fileoff;
}
}
static uint32_t
GetSegmentPermissions(const llvm::MachO::segment_command_64 &seg_cmd) {
uint32_t result = 0;
if (seg_cmd.initprot & VM_PROT_READ)
result |= ePermissionsReadable;
if (seg_cmd.initprot & VM_PROT_WRITE)
result |= ePermissionsWritable;
if (seg_cmd.initprot & VM_PROT_EXECUTE)
result |= ePermissionsExecutable;
return result;
}
static lldb::SectionType GetSectionType(uint32_t flags,
ConstString section_name) {
if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
return eSectionTypeCode;
uint32_t mach_sect_type = flags & SECTION_TYPE;
static ConstString g_sect_name_objc_data("__objc_data");
static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
static ConstString g_sect_name_objc_const("__objc_const");
static ConstString g_sect_name_objc_classlist("__objc_classlist");
static ConstString g_sect_name_cfstring("__cfstring");
static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
static ConstString g_sect_name_dwarf_debug_abbrev_dwo("__debug_abbrev.dwo");
static ConstString g_sect_name_dwarf_debug_addr("__debug_addr");
static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
static ConstString g_sect_name_dwarf_debug_cu_index("__debug_cu_index");
static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
static ConstString g_sect_name_dwarf_debug_info("__debug_info");
static ConstString g_sect_name_dwarf_debug_info_dwo("__debug_info.dwo");
static ConstString g_sect_name_dwarf_debug_line("__debug_line");
static ConstString g_sect_name_dwarf_debug_line_dwo("__debug_line.dwo");
static ConstString g_sect_name_dwarf_debug_line_str("__debug_line_str");
static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
static ConstString g_sect_name_dwarf_debug_loclists_dwo("__debug_loclists.dwo");
static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
static ConstString g_sect_name_dwarf_debug_macro("__debug_macro");
static ConstString g_sect_name_dwarf_debug_macro_dwo("__debug_macro.dwo");
static ConstString g_sect_name_dwarf_debug_names("__debug_names");
static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
static ConstString g_sect_name_dwarf_debug_rnglists("__debug_rnglists");
static ConstString g_sect_name_dwarf_debug_str("__debug_str");
static ConstString g_sect_name_dwarf_debug_str_dwo("__debug_str.dwo");
static ConstString g_sect_name_dwarf_debug_str_offs("__debug_str_offs");
static ConstString g_sect_name_dwarf_debug_str_offs_dwo("__debug_str_offs.dwo");
static ConstString g_sect_name_dwarf_debug_tu_index("__debug_tu_index");
static ConstString g_sect_name_dwarf_debug_types("__debug_types");
static ConstString g_sect_name_dwarf_apple_names("__apple_names");
static ConstString g_sect_name_dwarf_apple_types("__apple_types");
static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
static ConstString g_sect_name_eh_frame("__eh_frame");
static ConstString g_sect_name_compact_unwind("__unwind_info");
static ConstString g_sect_name_text("__text");
static ConstString g_sect_name_data("__data");
static ConstString g_sect_name_go_symtab("__gosymtab");
static ConstString g_sect_name_ctf("__ctf");
static ConstString g_sect_name_swift_ast("__swift_ast");
if (section_name == g_sect_name_dwarf_debug_abbrev)
return eSectionTypeDWARFDebugAbbrev;
if (section_name == g_sect_name_dwarf_debug_abbrev_dwo)
return eSectionTypeDWARFDebugAbbrevDwo;
if (section_name == g_sect_name_dwarf_debug_addr)
return eSectionTypeDWARFDebugAddr;
if (section_name == g_sect_name_dwarf_debug_aranges)
return eSectionTypeDWARFDebugAranges;
if (section_name == g_sect_name_dwarf_debug_cu_index)
return eSectionTypeDWARFDebugCuIndex;
if (section_name == g_sect_name_dwarf_debug_frame)
return eSectionTypeDWARFDebugFrame;
if (section_name == g_sect_name_dwarf_debug_info)
return eSectionTypeDWARFDebugInfo;
if (section_name == g_sect_name_dwarf_debug_info_dwo)
return eSectionTypeDWARFDebugInfoDwo;
if (section_name == g_sect_name_dwarf_debug_line)
return eSectionTypeDWARFDebugLine;
if (section_name == g_sect_name_dwarf_debug_line_dwo)
return eSectionTypeDWARFDebugLine; // Same as debug_line.
if (section_name == g_sect_name_dwarf_debug_line_str)
return eSectionTypeDWARFDebugLineStr;
if (section_name == g_sect_name_dwarf_debug_loc)
return eSectionTypeDWARFDebugLoc;
if (section_name == g_sect_name_dwarf_debug_loclists)
return eSectionTypeDWARFDebugLocLists;
if (section_name == g_sect_name_dwarf_debug_loclists_dwo)
return eSectionTypeDWARFDebugLocListsDwo;
if (section_name == g_sect_name_dwarf_debug_macinfo)
return eSectionTypeDWARFDebugMacInfo;
if (section_name == g_sect_name_dwarf_debug_macro)
return eSectionTypeDWARFDebugMacro;
if (section_name == g_sect_name_dwarf_debug_macro_dwo)
return eSectionTypeDWARFDebugMacInfo; // Same as debug_macro.
if (section_name == g_sect_name_dwarf_debug_names)
return eSectionTypeDWARFDebugNames;
if (section_name == g_sect_name_dwarf_debug_pubnames)
return eSectionTypeDWARFDebugPubNames;
if (section_name == g_sect_name_dwarf_debug_pubtypes)
return eSectionTypeDWARFDebugPubTypes;
if (section_name == g_sect_name_dwarf_debug_ranges)
return eSectionTypeDWARFDebugRanges;
if (section_name == g_sect_name_dwarf_debug_rnglists)
return eSectionTypeDWARFDebugRngLists;
if (section_name == g_sect_name_dwarf_debug_str)
return eSectionTypeDWARFDebugStr;
if (section_name == g_sect_name_dwarf_debug_str_dwo)
return eSectionTypeDWARFDebugStrDwo;
if (section_name == g_sect_name_dwarf_debug_str_offs)
return eSectionTypeDWARFDebugStrOffsets;
if (section_name == g_sect_name_dwarf_debug_str_offs_dwo)
return eSectionTypeDWARFDebugStrOffsetsDwo;
if (section_name == g_sect_name_dwarf_debug_tu_index)
return eSectionTypeDWARFDebugTuIndex;
if (section_name == g_sect_name_dwarf_debug_types)
return eSectionTypeDWARFDebugTypes;
if (section_name == g_sect_name_dwarf_apple_names)
return eSectionTypeDWARFAppleNames;
if (section_name == g_sect_name_dwarf_apple_types)
return eSectionTypeDWARFAppleTypes;
if (section_name == g_sect_name_dwarf_apple_namespaces)
return eSectionTypeDWARFAppleNamespaces;
if (section_name == g_sect_name_dwarf_apple_objc)
return eSectionTypeDWARFAppleObjC;
if (section_name == g_sect_name_objc_selrefs)
return eSectionTypeDataCStringPointers;
if (section_name == g_sect_name_objc_msgrefs)
return eSectionTypeDataObjCMessageRefs;
if (section_name == g_sect_name_eh_frame)
return eSectionTypeEHFrame;
if (section_name == g_sect_name_compact_unwind)
return eSectionTypeCompactUnwind;
if (section_name == g_sect_name_cfstring)
return eSectionTypeDataObjCCFStrings;
if (section_name == g_sect_name_go_symtab)
return eSectionTypeGoSymtab;
if (section_name == g_sect_name_ctf)
return eSectionTypeCTF;
if (section_name == g_sect_name_swift_ast)
return eSectionTypeSwiftModules;
if (section_name == g_sect_name_objc_data ||
section_name == g_sect_name_objc_classrefs ||
section_name == g_sect_name_objc_superrefs ||
section_name == g_sect_name_objc_const ||
section_name == g_sect_name_objc_classlist) {
return eSectionTypeDataPointers;
}
switch (mach_sect_type) {
// TODO: categorize sections by other flags for regular sections
case S_REGULAR:
if (section_name == g_sect_name_text)
return eSectionTypeCode;
if (section_name == g_sect_name_data)
return eSectionTypeData;
return eSectionTypeOther;
case S_ZEROFILL:
return eSectionTypeZeroFill;
case S_CSTRING_LITERALS: // section with only literal C strings
return eSectionTypeDataCString;
case S_4BYTE_LITERALS: // section with only 4 byte literals
return eSectionTypeData4;
case S_8BYTE_LITERALS: // section with only 8 byte literals
return eSectionTypeData8;
case S_LITERAL_POINTERS: // section with only pointers to literals
return eSectionTypeDataPointers;
case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
return eSectionTypeDataPointers;
case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
return eSectionTypeDataPointers;
case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
// the reserved2 field
return eSectionTypeCode;
case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
// initialization
return eSectionTypeDataPointers;
case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
// termination
return eSectionTypeDataPointers;
case S_COALESCED:
return eSectionTypeOther;
case S_GB_ZEROFILL:
return eSectionTypeZeroFill;
case S_INTERPOSING: // section with only pairs of function pointers for
// interposing
return eSectionTypeCode;
case S_16BYTE_LITERALS: // section with only 16 byte literals
return eSectionTypeData16;
case S_DTRACE_DOF:
return eSectionTypeDebug;
case S_LAZY_DYLIB_SYMBOL_POINTERS:
return eSectionTypeDataPointers;
default:
return eSectionTypeOther;
}
}
struct ObjectFileMachO::SegmentParsingContext {
const EncryptedFileRanges EncryptedRanges;
lldb_private::SectionList &UnifiedList;
uint32_t NextSegmentIdx = 0;
uint32_t NextSectionIdx = 0;
bool FileAddressesChanged = false;
SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
lldb_private::SectionList &UnifiedList)
: EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
};
void ObjectFileMachO::ProcessSegmentCommand(
const llvm::MachO::load_command &load_cmd_, lldb::offset_t offset,
uint32_t cmd_idx, SegmentParsingContext &context) {
llvm::MachO::segment_command_64 load_cmd;
memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
return;
ModuleSP module_sp = GetModule();
const bool is_core = GetType() == eTypeCoreFile;
const bool is_dsym = (m_header.filetype == MH_DSYM);
bool add_section = true;
bool add_to_unified = true;
ConstString const_segname(
load_cmd.segname, strnlen(load_cmd.segname, sizeof(load_cmd.segname)));
SectionSP unified_section_sp(
context.UnifiedList.FindSectionByName(const_segname));
if (is_dsym && unified_section_sp) {
if (const_segname == GetSegmentNameLINKEDIT()) {
// We need to keep the __LINKEDIT segment private to this object file
// only
add_to_unified = false;
} else {
// This is the dSYM file and this section has already been created by the
// object file, no need to create it.
add_section = false;
}
}
load_cmd.vmaddr = m_data.GetAddress(&offset);
load_cmd.vmsize = m_data.GetAddress(&offset);
load_cmd.fileoff = m_data.GetAddress(&offset);
load_cmd.filesize = m_data.GetAddress(&offset);
if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
return;
SanitizeSegmentCommand(load_cmd, cmd_idx);
const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
const bool segment_is_encrypted =
(load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
// Use a segment ID of the segment index shifted left by 8 so they never
// conflict with any of the sections.
SectionSP segment_sp;
if (add_section && (const_segname || is_core)) {
segment_sp = std::make_shared<Section>(
module_sp, // Module to which this section belongs
this, // Object file to which this sections belongs
++context.NextSegmentIdx
<< 8, // Section ID is the 1 based segment index
// shifted right by 8 bits as not to collide with any of the 256
// section IDs that are possible
const_segname, // Name of this section
eSectionTypeContainer, // This section is a container of other
// sections.
load_cmd.vmaddr, // File VM address == addresses as they are
// found in the object file
load_cmd.vmsize, // VM size in bytes of this section
load_cmd.fileoff, // Offset to the data for this section in
// the file
load_cmd.filesize, // Size in bytes of this section as found
// in the file
0, // Segments have no alignment information
load_cmd.flags); // Flags for this section
segment_sp->SetIsEncrypted(segment_is_encrypted);
m_sections_up->AddSection(segment_sp);
segment_sp->SetPermissions(segment_permissions);
if (add_to_unified)
context.UnifiedList.AddSection(segment_sp);
} else if (unified_section_sp) {
// If this is a dSYM and the file addresses in the dSYM differ from the
// file addresses in the ObjectFile, we must use the file base address for
// the Section from the dSYM for the DWARF to resolve correctly.
// This only happens with binaries in the shared cache in practice;
// normally a mismatch like this would give a binary & dSYM that do not
// match UUIDs. When a binary is included in the shared cache, its
// segments are rearranged to optimize the shared cache, so its file
// addresses will differ from what the ObjectFile had originally,
// and what the dSYM has.
if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
Log *log = GetLog(LLDBLog::Symbols);
if (log) {
log->Printf(
"Installing dSYM's %s segment file address over ObjectFile's "
"so symbol table/debug info resolves correctly for %s",
const_segname.AsCString(),
module_sp->GetFileSpec().GetFilename().AsCString());
}
// Make sure we've parsed the symbol table from the ObjectFile before
// we go around changing its Sections.
module_sp->GetObjectFile()->GetSymtab();
// eh_frame would present the same problems but we parse that on a per-
// function basis as-needed so it's more difficult to remove its use of
// the Sections. Realistically, the environments where this code path
// will be taken will not have eh_frame sections.
unified_section_sp->SetFileAddress(load_cmd.vmaddr);
// Notify the module that the section addresses have been changed once
// we're done so any file-address caches can be updated.
context.FileAddressesChanged = true;
}
m_sections_up->AddSection(unified_section_sp);
}
llvm::MachO::section_64 sect64;
::memset(&sect64, 0, sizeof(sect64));
// Push a section into our mach sections for the section at index zero
// (NO_SECT) if we don't have any mach sections yet...
if (m_mach_sections.empty())
m_mach_sections.push_back(sect64);
uint32_t segment_sect_idx;
const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
++segment_sect_idx) {
if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
sizeof(sect64.sectname)) == nullptr)
break;
if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
sizeof(sect64.segname)) == nullptr)
break;
sect64.addr = m_data.GetAddress(&offset);
sect64.size = m_data.GetAddress(&offset);
if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == nullptr)
break;
if (IsSharedCacheBinary() && !IsInMemory()) {
sect64.offset = sect64.addr - m_text_address;
}
// Keep a list of mach sections around in case we need to get at data that
// isn't stored in the abstracted Sections.
m_mach_sections.push_back(sect64);
if (add_section) {
ConstString section_name(
sect64.sectname, strnlen(sect64.sectname, sizeof(sect64.sectname)));
if (!const_segname) {
// We have a segment with no name so we need to conjure up segments
// that correspond to the section's segname if there isn't already such
// a section. If there is such a section, we resize the section so that
// it spans all sections. We also mark these sections as fake so
// address matches don't hit if they land in the gaps between the child
// sections.
const_segname.SetTrimmedCStringWithLength(sect64.segname,
sizeof(sect64.segname));
segment_sp = context.UnifiedList.FindSectionByName(const_segname);
if (segment_sp.get()) {
Section *segment = segment_sp.get();
// Grow the section size as needed.
const lldb::addr_t sect64_min_addr = sect64.addr;
const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
const lldb::addr_t curr_seg_max_addr =
curr_seg_min_addr + curr_seg_byte_size;
if (sect64_min_addr >= curr_seg_min_addr) {
const lldb::addr_t new_seg_byte_size =
sect64_max_addr - curr_seg_min_addr;
// Only grow the section size if needed
if (new_seg_byte_size > curr_seg_byte_size)
segment->SetByteSize(new_seg_byte_size);
} else {
// We need to change the base address of the segment and adjust the
// child section offsets for all existing children.
const lldb::addr_t slide_amount =
sect64_min_addr - curr_seg_min_addr;
segment->Slide(slide_amount, false);
segment->GetChildren().Slide(-slide_amount, false);
segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
}
// Grow the section size as needed.
if (sect64.offset) {
const lldb::addr_t segment_min_file_offset =
segment->GetFileOffset();
const lldb::addr_t segment_max_file_offset =
segment_min_file_offset + segment->GetFileSize();
const lldb::addr_t section_min_file_offset = sect64.offset;
const lldb::addr_t section_max_file_offset =
section_min_file_offset + sect64.size;
const lldb::addr_t new_file_offset =
std::min(section_min_file_offset, segment_min_file_offset);
const lldb::addr_t new_file_size =
std::max(section_max_file_offset, segment_max_file_offset) -
new_file_offset;
segment->SetFileOffset(new_file_offset);
segment->SetFileSize(new_file_size);
}
} else {
// Create a fake section for the section's named segment
segment_sp = std::make_shared<Section>(
segment_sp, // Parent section
module_sp, // Module to which this section belongs
this, // Object file to which this section belongs
++context.NextSegmentIdx
<< 8, // Section ID is the 1 based segment index
// shifted right by 8 bits as not to
// collide with any of the 256 section IDs
// that are possible
const_segname, // Name of this section
eSectionTypeContainer, // This section is a container of
// other sections.
sect64.addr, // File VM address == addresses as they are
// found in the object file
sect64.size, // VM size in bytes of this section
sect64.offset, // Offset to the data for this section in
// the file
sect64.offset ? sect64.size : 0, // Size in bytes of
// this section as
// found in the file
sect64.align,
load_cmd.flags); // Flags for this section
segment_sp->SetIsFake(true);
segment_sp->SetPermissions(segment_permissions);
m_sections_up->AddSection(segment_sp);
if (add_to_unified)
context.UnifiedList.AddSection(segment_sp);
segment_sp->SetIsEncrypted(segment_is_encrypted);
}
}
assert(segment_sp.get());
lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
SectionSP section_sp(new Section(
segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
sect64.flags));
// Set the section to be encrypted to match the segment
bool section_is_encrypted = false;
if (!segment_is_encrypted && load_cmd.filesize != 0)
section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
sect64.offset) != nullptr;
section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
section_sp->SetPermissions(segment_permissions);
segment_sp->GetChildren().AddSection(section_sp);
if (segment_sp->IsFake()) {
segment_sp.reset();
const_segname.Clear();
}
}
}
if (segment_sp && is_dsym) {
if (first_segment_sectID <= context.NextSectionIdx) {
lldb::user_id_t sect_uid;
for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
++sect_uid) {
SectionSP curr_section_sp(
segment_sp->GetChildren().FindSectionByID(sect_uid));
SectionSP next_section_sp;
if (sect_uid + 1 <= context.NextSectionIdx)
next_section_sp =
segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
if (curr_section_sp.get()) {
if (curr_section_sp->GetByteSize() == 0) {
if (next_section_sp.get() != nullptr)
curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
curr_section_sp->GetFileAddress());
else
curr_section_sp->SetByteSize(load_cmd.vmsize);
}
}
}
}
}
}
void ObjectFileMachO::ProcessDysymtabCommand(
const llvm::MachO::load_command &load_cmd, lldb::offset_t offset) {
m_dysymtab.cmd = load_cmd.cmd;
m_dysymtab.cmdsize = load_cmd.cmdsize;
m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
(sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
}
void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
if (m_sections_up)
return;
m_sections_up = std::make_unique<SectionList>();
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
// bool dump_sections = false;
ModuleSP module_sp(GetModule());
offset = MachHeaderSizeFromMagic(m_header.magic);
SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
llvm::MachO::load_command load_cmd;
for (uint32_t i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t load_cmd_offset = offset;
if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
break;
if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
ProcessSegmentCommand(load_cmd, offset, i, context);
else if (load_cmd.cmd == LC_DYSYMTAB)
ProcessDysymtabCommand(load_cmd, offset);
offset = load_cmd_offset + load_cmd.cmdsize;
}
if (context.FileAddressesChanged && module_sp)
module_sp->SectionFileAddressesChanged();
}
class MachSymtabSectionInfo {
public:
MachSymtabSectionInfo(SectionList *section_list)
: m_section_list(section_list), m_section_infos() {
// Get the number of sections down to a depth of 1 to include all segments
// and their sections, but no other sections that may be added for debug
// map or
m_section_infos.resize(section_list->GetNumSections(1));
}
SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
if (n_sect == 0)
return SectionSP();
if (n_sect < m_section_infos.size()) {
if (!m_section_infos[n_sect].section_sp) {
SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
m_section_infos[n_sect].section_sp = section_sp;
if (section_sp) {
m_section_infos[n_sect].vm_range.SetBaseAddress(
section_sp->GetFileAddress());
m_section_infos[n_sect].vm_range.SetByteSize(
section_sp->GetByteSize());
} else {
std::string filename = "<unknown>";
SectionSP first_section_sp(m_section_list->GetSectionAtIndex(0));
if (first_section_sp)
filename = first_section_sp->GetObjectFile()->GetFileSpec().GetPath();
Debugger::ReportError(
llvm::formatv("unable to find section {0} for a symbol in "
"{1}, corrupt file?",
n_sect, filename));
}
}
if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
// Symbol is in section.
return m_section_infos[n_sect].section_sp;
} else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
m_section_infos[n_sect].vm_range.GetBaseAddress() ==
file_addr) {
// Symbol is in section with zero size, but has the same start address
// as the section. This can happen with linker symbols (symbols that
// start with the letter 'l' or 'L'.
return m_section_infos[n_sect].section_sp;
}
}
return m_section_list->FindSectionContainingFileAddress(file_addr);
}
protected:
struct SectionInfo {
SectionInfo() : vm_range(), section_sp() {}
VMRange vm_range;
SectionSP section_sp;
};
SectionList *m_section_list;
std::vector<SectionInfo> m_section_infos;
};
#define TRIE_SYMBOL_IS_THUMB (1ULL << 63)
struct TrieEntry {
void Dump() const {
printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
static_cast<unsigned long long>(address),
static_cast<unsigned long long>(flags),
static_cast<unsigned long long>(other), name.GetCString());
if (import_name)
printf(" -> \"%s\"\n", import_name.GetCString());
else
printf("\n");
}
ConstString name;
uint64_t address = LLDB_INVALID_ADDRESS;
uint64_t flags =
0; // EXPORT_SYMBOL_FLAGS_REEXPORT, EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER,
// TRIE_SYMBOL_IS_THUMB
uint64_t other = 0;
ConstString import_name;
};
struct TrieEntryWithOffset {
lldb::offset_t nodeOffset;
TrieEntry entry;
TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
void Dump(uint32_t idx) const {
printf("[%3u] 0x%16.16llx: ", idx,
static_cast<unsigned long long>(nodeOffset));
entry.Dump();
}
bool operator<(const TrieEntryWithOffset &other) const {
return (nodeOffset < other.nodeOffset);
}
};
static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
const bool is_arm, addr_t text_seg_base_addr,
std::vector<llvm::StringRef> &nameSlices,
std::set<lldb::addr_t> &resolver_addresses,
std::vector<TrieEntryWithOffset> &reexports,
std::vector<TrieEntryWithOffset> &ext_symbols) {
if (!data.ValidOffset(offset))
return true;
// Terminal node -- end of a branch, possibly add this to
// the symbol table or resolver table.
const uint64_t terminalSize = data.GetULEB128(&offset);
lldb::offset_t children_offset = offset + terminalSize;
if (terminalSize != 0) {
TrieEntryWithOffset e(offset);
e.entry.flags = data.GetULEB128(&offset);
const char *import_name = nullptr;
if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
e.entry.address = 0;
e.entry.other = data.GetULEB128(&offset); // dylib ordinal
import_name = data.GetCStr(&offset);
} else {
e.entry.address = data.GetULEB128(&offset);
if (text_seg_base_addr != LLDB_INVALID_ADDRESS)
e.entry.address += text_seg_base_addr;
if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
e.entry.other = data.GetULEB128(&offset);
uint64_t resolver_addr = e.entry.other;
if (text_seg_base_addr != LLDB_INVALID_ADDRESS)
resolver_addr += text_seg_base_addr;
if (is_arm)
resolver_addr &= THUMB_ADDRESS_BIT_MASK;
resolver_addresses.insert(resolver_addr);
} else
e.entry.other = 0;
}
bool add_this_entry = false;
if (Flags(e.entry.flags).Test(EXPORT_SYMBOL_FLAGS_REEXPORT) &&
import_name && import_name[0]) {
// add symbols that are reexport symbols with a valid import name.
add_this_entry = true;
} else if (e.entry.flags == 0 &&
(import_name == nullptr || import_name[0] == '\0')) {
// add externally visible symbols, in case the nlist record has
// been stripped/omitted.
add_this_entry = true;
}
if (add_this_entry) {
std::string name;
if (!nameSlices.empty()) {
for (auto name_slice : nameSlices)
name.append(name_slice.data(), name_slice.size());
}
if (name.size() > 1) {
// Skip the leading '_'
e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
}
if (import_name) {
// Skip the leading '_'
e.entry.import_name.SetCString(import_name + 1);
}
if (Flags(e.entry.flags).Test(EXPORT_SYMBOL_FLAGS_REEXPORT)) {
reexports.push_back(e);
} else {
if (is_arm && (e.entry.address & 1)) {
e.entry.flags |= TRIE_SYMBOL_IS_THUMB;
e.entry.address &= THUMB_ADDRESS_BIT_MASK;
}
ext_symbols.push_back(e);
}
}
}
const uint8_t childrenCount = data.GetU8(&children_offset);
for (uint8_t i = 0; i < childrenCount; ++i) {
const char *cstr = data.GetCStr(&children_offset);
if (cstr)
nameSlices.push_back(llvm::StringRef(cstr));
else
return false; // Corrupt data
lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
if (childNodeOffset) {
if (!ParseTrieEntries(data, childNodeOffset, is_arm, text_seg_base_addr,
nameSlices, resolver_addresses, reexports,
ext_symbols)) {
return false;
}
}
nameSlices.pop_back();
}
return true;
}
static SymbolType GetSymbolType(const char *&symbol_name,
bool &demangled_is_synthesized,
const SectionSP &text_section_sp,
const SectionSP &data_section_sp,
const SectionSP &data_dirty_section_sp,
const SectionSP &data_const_section_sp,
const SectionSP &symbol_section) {
SymbolType type = eSymbolTypeInvalid;
const char *symbol_sect_name = symbol_section->GetName().AsCString();
if (symbol_section->IsDescendant(text_section_sp.get())) {
if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
S_ATTR_SELF_MODIFYING_CODE |
S_ATTR_SOME_INSTRUCTIONS))
type = eSymbolTypeData;
else
type = eSymbolTypeCode;
} else if (symbol_section->IsDescendant(data_section_sp.get()) ||
symbol_section->IsDescendant(data_dirty_section_sp.get()) ||
symbol_section->IsDescendant(data_const_section_sp.get())) {
if (symbol_sect_name &&
::strstr(symbol_sect_name, "__objc") == symbol_sect_name) {
type = eSymbolTypeRuntime;
if (symbol_name) {
llvm::StringRef symbol_name_ref(symbol_name);
if (symbol_name_ref.starts_with("OBJC_")) {
static const llvm::StringRef g_objc_v2_prefix_class("OBJC_CLASS_$_");
static const llvm::StringRef g_objc_v2_prefix_metaclass(
"OBJC_METACLASS_$_");
static const llvm::StringRef g_objc_v2_prefix_ivar("OBJC_IVAR_$_");
if (symbol_name_ref.starts_with(g_objc_v2_prefix_class)) {
symbol_name = symbol_name + g_objc_v2_prefix_class.size();
type = eSymbolTypeObjCClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.starts_with(g_objc_v2_prefix_metaclass)) {
symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
type = eSymbolTypeObjCMetaClass;
demangled_is_synthesized = true;
} else if (symbol_name_ref.starts_with(g_objc_v2_prefix_ivar)) {
symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
type = eSymbolTypeObjCIVar;
demangled_is_synthesized = true;
}
}
}
} else if (symbol_sect_name &&
::strstr(symbol_sect_name, "__gcc_except_tab") ==
symbol_sect_name) {
type = eSymbolTypeException;
} else {
type = eSymbolTypeData;
}
} else if (symbol_sect_name &&
::strstr(symbol_sect_name, "__IMPORT") == symbol_sect_name) {
type = eSymbolTypeTrampoline;
}
return type;
}
static std::optional<struct nlist_64>
ParseNList(DataExtractor &nlist_data, lldb::offset_t &nlist_data_offset,
size_t nlist_byte_size) {
struct nlist_64 nlist;
if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
return {};
nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
return nlist;
}
enum { DebugSymbols = true, NonDebugSymbols = false };
void ObjectFileMachO::ParseSymtab(Symtab &symtab) {
ModuleSP module_sp(GetModule());
if (!module_sp)
return;
Log *log = GetLog(LLDBLog::Symbols);
const FileSpec &file = m_file ? m_file : module_sp->GetFileSpec();
const char *file_name = file.GetFilename().AsCString("<Unknown>");
LLDB_SCOPED_TIMERF("ObjectFileMachO::ParseSymtab () module = %s", file_name);
LLDB_LOG(log, "Parsing symbol table for {0}", file_name);
Progress progress("Parsing symbol table", file_name);
llvm::MachO::symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
llvm::MachO::linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
llvm::MachO::linkedit_data_command exports_trie_load_command = {0, 0, 0, 0};
llvm::MachO::dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
llvm::MachO::dysymtab_command dysymtab = m_dysymtab;
// The data element of type bool indicates that this entry is thumb
// code.
typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
// Record the address of every function/data that we add to the symtab.
// We add symbols to the table in the order of most information (nlist
// records) to least (function starts), and avoid duplicating symbols
// via this set.
llvm::DenseSet<addr_t> symbols_added;
// We are using a llvm::DenseSet for "symbols_added" so we must be sure we
// do not add the tombstone or empty keys to the set.
auto add_symbol_addr = [&symbols_added](lldb::addr_t file_addr) {
// Don't add the tombstone or empty keys.
if (file_addr == UINT64_MAX || file_addr == UINT64_MAX - 1)
return;
symbols_added.insert(file_addr);
};
FunctionStarts function_starts;
lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
uint32_t i;
FileSpecList dylib_files;
llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
UUID image_uuid;
for (i = 0; i < m_header.ncmds; ++i) {
const lldb::offset_t cmd_offset = offset;
// Read in the load command and load command size
llvm::MachO::load_command lc;
if (m_data.GetU32(&offset, &lc, 2) == nullptr)
break;
// Watch for the symbol table load command
switch (lc.cmd) {
case LC_SYMTAB:
symtab_load_command.cmd = lc.cmd;
symtab_load_command.cmdsize = lc.cmdsize;
// Read in the rest of the symtab load command
if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
nullptr) // fill in symoff, nsyms, stroff, strsize fields
return;
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
dyld_info.cmd = lc.cmd;
dyld_info.cmdsize = lc.cmdsize;
} else {
memset(&dyld_info, 0, sizeof(dyld_info));
}
break;
case LC_LOAD_DYLIB:
case LC_LOAD_WEAK_DYLIB:
case LC_REEXPORT_DYLIB:
case LC_LOADFVMLIB:
case LC_LOAD_UPWARD_DYLIB: {
uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
const char *path = m_data.PeekCStr(name_offset);
if (path) {
FileSpec file_spec(path);
// Strip the path if there is @rpath, @executable, etc so we just use
// the basename
if (path[0] == '@')
file_spec.ClearDirectory();
if (lc.cmd == LC_REEXPORT_DYLIB) {
m_reexported_dylibs.AppendIfUnique(file_spec);
}
dylib_files.Append(file_spec);
}
} break;
case LC_DYLD_EXPORTS_TRIE:
exports_trie_load_command.cmd = lc.cmd;
exports_trie_load_command.cmdsize = lc.cmdsize;
if (m_data.GetU32(&offset, &exports_trie_load_command.dataoff, 2) ==
nullptr) // fill in offset and size fields
memset(&exports_trie_load_command, 0,
sizeof(exports_trie_load_command));
break;
case LC_FUNCTION_STARTS:
function_starts_load_command.cmd = lc.cmd;
function_starts_load_command.cmdsize = lc.cmdsize;
if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
nullptr) // fill in data offset and size fields
memset(&function_starts_load_command, 0,
sizeof(function_starts_load_command));
break;
case LC_UUID: {
const uint8_t *uuid_bytes = m_data.PeekData(offset, 16);
if (uuid_bytes)
image_uuid = UUID(uuid_bytes, 16);
break;
}
default:
break;
}
offset = cmd_offset + lc.cmdsize;
}
if (!symtab_load_command.cmd)
return;
SectionList *section_list = GetSectionList();
if (section_list == nullptr)
return;
const uint32_t addr_byte_size = m_data.GetAddressByteSize();
const ByteOrder byte_order = m_data.GetByteOrder();
bool bit_width_32 = addr_byte_size == 4;
const size_t nlist_byte_size =
bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size);
DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size);
DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size);
DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order,
addr_byte_size);
DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size);
const addr_t nlist_data_byte_size =
symtab_load_command.nsyms * nlist_byte_size;
const addr_t strtab_data_byte_size = symtab_load_command.strsize;
addr_t strtab_addr = LLDB_INVALID_ADDRESS;
ProcessSP process_sp(m_process_wp.lock());
Process *process = process_sp.get();
uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
bool is_shared_cache_image = IsSharedCacheBinary();
bool is_local_shared_cache_image = is_shared_cache_image && !IsInMemory();
SectionSP linkedit_section_sp(
section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
if (process && m_header.filetype != llvm::MachO::MH_OBJECT &&
!is_local_shared_cache_image) {
Target &target = process->GetTarget();
memory_module_load_level = target.GetMemoryModuleLoadLevel();
// Reading mach file from memory in a process or core file...
if (linkedit_section_sp) {
addr_t linkedit_load_addr =
linkedit_section_sp->GetLoadBaseAddress(&target);
if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
// We might be trying to access the symbol table before the
// __LINKEDIT's load address has been set in the target. We can't
// fail to read the symbol table, so calculate the right address
// manually
linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
}
const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
const addr_t symoff_addr = linkedit_load_addr +
symtab_load_command.symoff -
linkedit_file_offset;
strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
linkedit_file_offset;
// Always load dyld - the dynamic linker - from memory if we didn't
// find a binary anywhere else. lldb will not register
// dylib/framework/bundle loads/unloads if we don't have the dyld
// symbols, we force dyld to load from memory despite the user's
// target.memory-module-load-level setting.
if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
m_header.filetype == llvm::MachO::MH_DYLINKER) {
DataBufferSP nlist_data_sp(
ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
if (nlist_data_sp)
nlist_data.SetData(nlist_data_sp, 0, nlist_data_sp->GetByteSize());
if (dysymtab.nindirectsyms != 0) {
const addr_t indirect_syms_addr = linkedit_load_addr +
dysymtab.indirectsymoff -
linkedit_file_offset;
DataBufferSP indirect_syms_data_sp(ReadMemory(
process_sp, indirect_syms_addr, dysymtab.nindirectsyms * 4));
if (indirect_syms_data_sp)
indirect_symbol_index_data.SetData(
indirect_syms_data_sp, 0, indirect_syms_data_sp->GetByteSize());
// If this binary is outside the shared cache,
// cache the string table.
// Binaries in the shared cache all share a giant string table,
// and we can't share the string tables across multiple
// ObjectFileMachO's, so we'd end up re-reading this mega-strtab
// for every binary in the shared cache - it would be a big perf
// problem. For binaries outside the shared cache, it's faster to
// read the entire strtab at once instead of piece-by-piece as we
// process the nlist records.
if (!is_shared_cache_image) {
DataBufferSP strtab_data_sp(
ReadMemory(process_sp, strtab_addr, strtab_data_byte_size));
if (strtab_data_sp) {
strtab_data.SetData(strtab_data_sp, 0,
strtab_data_sp->GetByteSize());
}
}
}
if (memory_module_load_level >= eMemoryModuleLoadLevelPartial) {
if (function_starts_load_command.cmd) {
const addr_t func_start_addr =
linkedit_load_addr + function_starts_load_command.dataoff -
linkedit_file_offset;
DataBufferSP func_start_data_sp(
ReadMemory(process_sp, func_start_addr,
function_starts_load_command.datasize));
if (func_start_data_sp)
function_starts_data.SetData(func_start_data_sp, 0,
func_start_data_sp->GetByteSize());
}
}
}
}
} else {
if (is_local_shared_cache_image) {
// The load commands in shared cache images are relative to the
// beginning of the shared cache, not the library image. The
// data we get handed when creating the ObjectFileMachO starts
// at the beginning of a specific library and spans to the end
// of the cache to be able to reach the shared LINKEDIT
// segments. We need to convert the load command offsets to be
// relative to the beginning of our specific image.
lldb::addr_t linkedit_offset = linkedit_section_sp->GetFileOffset();
lldb::offset_t linkedit_slide =
linkedit_offset - m_linkedit_original_offset;
symtab_load_command.symoff += linkedit_slide;
symtab_load_command.stroff += linkedit_slide;
dyld_info.export_off += linkedit_slide;
dysymtab.indirectsymoff += linkedit_slide;
function_starts_load_command.dataoff += linkedit_slide;
exports_trie_load_command.dataoff += linkedit_slide;
}
nlist_data.SetData(m_data, symtab_load_command.symoff,
nlist_data_byte_size);
strtab_data.SetData(m_data, symtab_load_command.stroff,
strtab_data_byte_size);
// We shouldn't have exports data from both the LC_DYLD_INFO command
// AND the LC_DYLD_EXPORTS_TRIE command in the same binary:
lldbassert(!((dyld_info.export_size > 0)
&& (exports_trie_load_command.datasize > 0)));
if (dyld_info.export_size > 0) {
dyld_trie_data.SetData(m_data, dyld_info.export_off,
dyld_info.export_size);
} else if (exports_trie_load_command.datasize > 0) {
dyld_trie_data.SetData(m_data, exports_trie_load_command.dataoff,
exports_trie_load_command.datasize);
}
if (dysymtab.nindirectsyms != 0) {
indirect_symbol_index_data.SetData(m_data, dysymtab.indirectsymoff,
dysymtab.nindirectsyms * 4);
}
if (function_starts_load_command.cmd) {
function_starts_data.SetData(m_data, function_starts_load_command.dataoff,
function_starts_load_command.datasize);
}
}
const bool have_strtab_data = strtab_data.GetByteSize() > 0;
ConstString g_segment_name_TEXT = GetSegmentNameTEXT();
ConstString g_segment_name_DATA = GetSegmentNameDATA();
ConstString g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
ConstString g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
ConstString g_segment_name_OBJC = GetSegmentNameOBJC();
ConstString g_section_name_eh_frame = GetSectionNameEHFrame();
SectionSP text_section_sp(
section_list->FindSectionByName(g_segment_name_TEXT));
SectionSP data_section_sp(
section_list->FindSectionByName(g_segment_name_DATA));
SectionSP data_dirty_section_sp(
section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
SectionSP data_const_section_sp(
section_list->FindSectionByName(g_segment_name_DATA_CONST));
SectionSP objc_section_sp(
section_list->FindSectionByName(g_segment_name_OBJC));
SectionSP eh_frame_section_sp;
if (text_section_sp.get())
eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
g_section_name_eh_frame);
else
eh_frame_section_sp =
section_list->FindSectionByName(g_section_name_eh_frame);
const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
const bool always_thumb = GetArchitecture().IsAlwaysThumbInstructions();
// lldb works best if it knows the start address of all functions in a
// module. Linker symbols or debug info are normally the best source of
// information for start addr / size but they may be stripped in a released
// binary. Two additional sources of information exist in Mach-O binaries:
// LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
// function's start address in the
// binary, relative to the text section.
// eh_frame - the eh_frame FDEs have the start addr & size of
// each function
// LC_FUNCTION_STARTS is the fastest source to read in, and is present on
// all modern binaries.
// Binaries built to run on older releases may need to use eh_frame
// information.
if (text_section_sp && function_starts_data.GetByteSize()) {
FunctionStarts::Entry function_start_entry;
function_start_entry.data = false;
lldb::offset_t function_start_offset = 0;
function_start_entry.addr = text_section_sp->GetFileAddress();
uint64_t delta;
while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
0) {
// Now append the current entry
function_start_entry.addr += delta;
if (is_arm) {
if (function_start_entry.addr & 1) {
function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
function_start_entry.data = true;
} else if (always_thumb) {
function_start_entry.data = true;
}
}
function_starts.Append(function_start_entry);
}
} else {
// If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
// load command claiming an eh_frame but it doesn't actually have the
// eh_frame content. And if we have a dSYM, we don't need to do any of
// this fill-in-the-missing-symbols works anyway - the debug info should
// give us all the functions in the module.
if (text_section_sp.get() && eh_frame_section_sp.get() &&
m_type != eTypeDebugInfo) {
DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
DWARFCallFrameInfo::EH);
DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
eh_frame.GetFunctionAddressAndSizeVector(functions);
addr_t text_base_addr = text_section_sp->GetFileAddress();
size_t count = functions.GetSize();
for (size_t i = 0; i < count; ++i) {
const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
functions.GetEntryAtIndex(i);
if (func) {
FunctionStarts::Entry function_start_entry;
function_start_entry.addr = func->base - text_base_addr;
if (is_arm) {
if (function_start_entry.addr & 1) {
function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
function_start_entry.data = true;
} else if (always_thumb) {
function_start_entry.data = true;
}
}
function_starts.Append(function_start_entry);
}
}
}
}
const size_t function_starts_count = function_starts.GetSize();
// For user process binaries (executables, dylibs, frameworks, bundles), if
// we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
// going to assume the binary has been stripped. Don't allow assembly
// language instruction emulation because we don't know proper function
// start boundaries.
//
// For all other types of binaries (kernels, stand-alone bare board
// binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
// sections - we should not make any assumptions about them based on that.
if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
m_allow_assembly_emulation_unwind_plans = false;
Log *unwind_or_symbol_log(GetLog(LLDBLog::Symbols | LLDBLog::Unwind));
if (unwind_or_symbol_log)
module_sp->LogMessage(
unwind_or_symbol_log,
"no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
}
const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get()
? eh_frame_section_sp->GetID()
: static_cast<user_id_t>(NO_SECT);
uint32_t N_SO_index = UINT32_MAX;
MachSymtabSectionInfo section_info(section_list);
std::vector<uint32_t> N_FUN_indexes;
std::vector<uint32_t> N_NSYM_indexes;
std::vector<uint32_t> N_INCL_indexes;
std::vector<uint32_t> N_BRAC_indexes;
std::vector<uint32_t> N_COMM_indexes;
typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
typedef llvm::DenseMap<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
typedef llvm::DenseMap<const char *, uint32_t> ConstNameToSymbolIndexMap;
ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
// Any symbols that get merged into another will get an entry in this map
// so we know
NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
uint32_t nlist_idx = 0;
Symbol *symbol_ptr = nullptr;
uint32_t sym_idx = 0;
Symbol *sym = nullptr;
size_t num_syms = 0;
std::string memory_symbol_name;
uint32_t unmapped_local_symbols_found = 0;
std::vector<TrieEntryWithOffset> reexport_trie_entries;
std::vector<TrieEntryWithOffset> external_sym_trie_entries;
std::set<lldb::addr_t> resolver_addresses;
const size_t dyld_trie_data_size = dyld_trie_data.GetByteSize();
if (dyld_trie_data_size > 0) {
LLDB_LOG(log, "Parsing {0} bytes of dyld trie data", dyld_trie_data_size);
SectionSP text_segment_sp =
GetSectionList()->FindSectionByName(GetSegmentNameTEXT());
lldb::addr_t text_segment_file_addr = LLDB_INVALID_ADDRESS;
if (text_segment_sp)
text_segment_file_addr = text_segment_sp->GetFileAddress();
std::vector<llvm::StringRef> nameSlices;
ParseTrieEntries(dyld_trie_data, 0, is_arm, text_segment_file_addr,
nameSlices, resolver_addresses, reexport_trie_entries,
external_sym_trie_entries);
}
typedef std::set<ConstString> IndirectSymbols;
IndirectSymbols indirect_symbol_names;
#if TARGET_OS_IPHONE
// Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
// optimized by moving LOCAL symbols out of the memory mapped portion of
// the DSC. The symbol information has all been retained, but it isn't
// available in the normal nlist data. However, there *are* duplicate
// entries of *some*
// LOCAL symbols in the normal nlist data. To handle this situation
// correctly, we must first attempt
// to parse any DSC unmapped symbol information. If we find any, we set a
// flag that tells the normal nlist parser to ignore all LOCAL symbols.
if (IsSharedCacheBinary()) {
// Before we can start mapping the DSC, we need to make certain the
// target process is actually using the cache we can find.
// Next we need to determine the correct path for the dyld shared cache.
ArchSpec header_arch = GetArchitecture();
UUID dsc_uuid;
UUID process_shared_cache_uuid;
addr_t process_shared_cache_base_addr;
if (process) {
GetProcessSharedCacheUUID(process, process_shared_cache_base_addr,
process_shared_cache_uuid);
}
__block bool found_image = false;
__block void *nlist_buffer = nullptr;
__block unsigned nlist_count = 0;
__block char *string_table = nullptr;
__block vm_offset_t vm_nlist_memory = 0;
__block mach_msg_type_number_t vm_nlist_bytes_read = 0;
__block vm_offset_t vm_string_memory = 0;
__block mach_msg_type_number_t vm_string_bytes_read = 0;
auto _ = llvm::make_scope_exit(^{
if (vm_nlist_memory)
vm_deallocate(mach_task_self(), vm_nlist_memory, vm_nlist_bytes_read);
if (vm_string_memory)
vm_deallocate(mach_task_self(), vm_string_memory, vm_string_bytes_read);
});
typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
UndefinedNameToDescMap undefined_name_to_desc;
SymbolIndexToName reexport_shlib_needs_fixup;
dyld_for_each_installed_shared_cache(^(dyld_shared_cache_t shared_cache) {
uuid_t cache_uuid;
dyld_shared_cache_copy_uuid(shared_cache, &cache_uuid);
if (found_image)
return;
if (process_shared_cache_uuid.IsValid() &&
process_shared_cache_uuid != UUID::fromData(&cache_uuid, 16))
return;
dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
uuid_t dsc_image_uuid;
if (found_image)
return;
dyld_image_copy_uuid(image, &dsc_image_uuid);
if (image_uuid != UUID::fromData(dsc_image_uuid, 16))
return;
found_image = true;
// Compute the size of the string table. We need to ask dyld for a
// new SPI to avoid this step.
dyld_image_local_nlist_content_4Symbolication(
image, ^(const void *nlistStart, uint64_t nlistCount,
const char